Sync BaseTools Branch (version r2271) to EDKII main trunk.

BaseTool Branch:
  https://edk2-buildtools.svn.sourceforge.net/svnroot/edk2-buildtools/branches/Releases/BaseTools_r2100

Signed-off-by: lgao4
Reviewed-by: hchen30

git-svn-id: https://edk2.svn.sourceforge.net/svnroot/edk2/trunk/edk2@12214 6f19259b-4bc3-4df7-8a09-765794883524
This commit is contained in:
lgao4
2011-08-26 07:46:26 +00:00
parent ba944801a9
commit 4234283c3a
186 changed files with 37663 additions and 3133 deletions

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,923 @@
## @file
# This file contain unit test for CommentParsing
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials are licensed and made available
# under the terms and conditions of the BSD License which accompanies this
# distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
import unittest
import Logger.Log as Logger
from Library.CommentParsing import ParseHeaderCommentSection, \
ParseGenericComment, \
ParseDecPcdGenericComment, \
ParseDecPcdTailComment
from Library.CommentParsing import _IsCopyrightLine
from Library.String import GetSplitValueList
from Library.DataType import TAB_SPACE_SPLIT
from Library.DataType import LANGUAGE_EN_US
#
# Test ParseHeaderCommentSection
#
class ParseHeaderCommentSectionTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
#
# Normal case1: have license/copyright/license above @file
#
def testNormalCase1(self):
TestCommentLines1 = \
'''# License1
# License2
#
## @file
# example abstract
#
# example description
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
#
# License3
#'''
CommentList = GetSplitValueList(TestCommentLines1, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = 'example abstract'
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = 'example description'
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010,'\
' Intel Corporation. All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = 'License1\nLicense2\n\nLicense3'
self.assertEqual(License, ExpectedLicense)
#
# Normal case2: have license/copyright above @file, but no copyright after
#
def testNormalCase2(self):
TestCommentLines2 = \
''' # License1
# License2
#
## @file
# example abstract
#
# example description
#
#Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
#
##'''
CommentList = GetSplitValueList(TestCommentLines2, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = 'example abstract'
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = 'example description'
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = 'License1\nLicense2'
self.assertEqual(License, ExpectedLicense)
#
# Normal case2: have license/copyright/license above @file,
# but no abstract/description
#
def testNormalCase3(self):
TestCommentLines3 = \
''' # License1
# License2
#
## @file
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
#
# License3 Line1
# License3 Line2
##'''
CommentList = GetSplitValueList(TestCommentLines3, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = ''
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = ''
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010,'\
' Intel Corporation. All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = \
'License1\n' \
'License2\n\n' \
'License3 Line1\n' \
'License3 Line2'
self.assertEqual(License, ExpectedLicense)
#
# Normal case4: format example in spec
#
def testNormalCase4(self):
TestCommentLines = \
'''
## @file
# Abstract
#
# Description
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
#
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = 'Abstract'
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = 'Description'
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = \
'License'
self.assertEqual(License, ExpectedLicense)
#
# Normal case5: other line between copyright
#
def testNormalCase5(self):
TestCommentLines = \
'''
## @file
# Abstract
#
# Description
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# other line
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
#
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = 'Abstract'
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = 'Description'
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>\n'\
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = \
'License'
self.assertEqual(License, ExpectedLicense)
#
# Normal case6: multiple lines of copyright
#
def testNormalCase6(self):
TestCommentLines = \
'''
## @file
# Abstract
#
# Description
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2010, FOO1 Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2010, FOO2 Corporation. All rights reserved.<BR>
#
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = 'Abstract'
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = 'Description'
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>\n'\
'Copyright (c) 2007 - 2010, FOO1 Corporation.'\
' All rights reserved.<BR>\n'\
'Copyright (c) 2007 - 2010, FOO2 Corporation.'\
' All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = \
'License'
self.assertEqual(License, ExpectedLicense)
#
# Normal case7: Abstract not present
#
def testNormalCase7(self):
TestCommentLines = \
'''
## @file
#
# Description
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2010, FOO1 Corporation. All rights reserved.<BR>
# Copyright (c) 2007 - 2010, FOO2 Corporation. All rights reserved.<BR>
#
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = ''
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = 'Description'
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>\n'\
'Copyright (c) 2007 - 2010, FOO1 Corporation.'\
' All rights reserved.<BR>\n'\
'Copyright (c) 2007 - 2010, FOO2 Corporation.'\
' All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = \
'License'
self.assertEqual(License, ExpectedLicense)
#
# Normal case8: Description not present
#
def testNormalCase8(self):
TestCommentLines = \
'''
## @file
# Abstact
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
#
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
Abstract, Description, Copyright, License = \
ParseHeaderCommentSection(TestCommentLinesList, "PhonyFile")
ExpectedAbstract = 'Abstact'
self.assertEqual(Abstract, ExpectedAbstract)
ExpectedDescription = ''
self.assertEqual(Description, ExpectedDescription)
ExpectedCopyright = \
'Copyright (c) 2007 - 2010, Intel Corporation.'\
' All rights reserved.<BR>'
self.assertEqual(Copyright, ExpectedCopyright)
ExpectedLicense = \
'License'
self.assertEqual(License, ExpectedLicense)
#
# Error case1: No copyright found
#
def testErrorCase1(self):
TestCommentLines = \
'''
## @file
# Abstract
#
# Description
#
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
self.assertRaises(Logger.FatalError,
ParseHeaderCommentSection,
TestCommentLinesList,
"PhonyFile")
#
# Error case2: non-empty non-comment lines passed in
#
def testErrorCase2(self):
TestCommentLines = \
'''
## @file
# Abstract
#
this is invalid line
# Description
#
# Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
# License
#
##'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
self.assertRaises(Logger.FatalError,
ParseHeaderCommentSection,
TestCommentLinesList,
"PhonyFile")
#
# Test ParseGenericComment
#
class ParseGenericCommentTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
#
# Normal case1: one line of comment
#
def testNormalCase1(self):
TestCommentLines = \
'''# hello world'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
HelptxtObj = ParseGenericComment(TestCommentLinesList, 'testNormalCase1')
self.failIf(not HelptxtObj)
self.assertEqual(HelptxtObj.GetString(), 'hello world')
self.assertEqual(HelptxtObj.GetLang(), LANGUAGE_EN_US)
#
# Normal case2: multiple lines of comment
#
def testNormalCase2(self):
TestCommentLines = \
'''## hello world
# second line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
HelptxtObj = ParseGenericComment(TestCommentLinesList, 'testNormalCase2')
self.failIf(not HelptxtObj)
self.assertEqual(HelptxtObj.GetString(),
'hello world\n' + 'second line')
self.assertEqual(HelptxtObj.GetLang(), LANGUAGE_EN_US)
#
# Normal case3: multiple lines of comment, non comment lines will be skipped
#
def testNormalCase3(self):
TestCommentLines = \
'''## hello world
This is not comment line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
HelptxtObj = ParseGenericComment(TestCommentLinesList, 'testNormalCase3')
self.failIf(not HelptxtObj)
self.assertEqual(HelptxtObj.GetString(),
'hello world\n\n')
self.assertEqual(HelptxtObj.GetLang(), LANGUAGE_EN_US)
#
# Test ParseDecPcdGenericComment
#
class ParseDecPcdGenericCommentTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
#
# Normal case1: comments with no special comment
#
def testNormalCase1(self):
TestCommentLines = \
'''## hello world
# second line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(HelpTxt, PcdErr) = \
ParseDecPcdGenericComment(TestCommentLinesList, 'testNormalCase1')
self.failIf(not HelpTxt)
self.failIf(PcdErr)
self.assertEqual(HelpTxt,
'hello world\n' + 'second line')
#
# Normal case2: comments with valid list
#
def testNormalCase2(self):
TestCommentLines = \
'''## hello world
# second line
# @ValidList 1, 2, 3
# other line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(HelpTxt, PcdErr) = \
ParseDecPcdGenericComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpTxt)
self.failIf(not PcdErr)
self.assertEqual(HelpTxt,
'hello world\n' + 'second line\n' + 'other line')
ExpectedList = GetSplitValueList('1 2 3', TAB_SPACE_SPLIT)
ActualList = [item for item in \
GetSplitValueList(PcdErr.GetValidValue(), TAB_SPACE_SPLIT) if item]
self.assertEqual(ExpectedList, ActualList)
self.failIf(PcdErr.GetExpression())
self.failIf(PcdErr.GetValidValueRange())
#
# Normal case3: comments with valid range
#
def testNormalCase3(self):
TestCommentLines = \
'''## hello world
# second line
# @ValidRange LT 1 AND GT 2
# other line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(HelpTxt, PcdErr) = \
ParseDecPcdGenericComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpTxt)
self.failIf(not PcdErr)
self.assertEqual(HelpTxt,
'hello world\n' + 'second line\n' + 'other line')
self.assertEqual(PcdErr.GetValidValueRange().strip(), 'LT 1 AND GT 2')
self.failIf(PcdErr.GetExpression())
self.failIf(PcdErr.GetValidValue())
#
# Normal case4: comments with valid expression
#
def testNormalCase4(self):
TestCommentLines = \
'''## hello world
# second line
# @Expression LT 1 AND GT 2
# other line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(HelpTxt, PcdErr) = \
ParseDecPcdGenericComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpTxt)
self.failIf(not PcdErr)
self.assertEqual(HelpTxt,
'hello world\n' + 'second line\n' + 'other line')
self.assertEqual(PcdErr.GetExpression().strip(), 'LT 1 AND GT 2')
self.failIf(PcdErr.GetValidValueRange())
self.failIf(PcdErr.GetValidValue())
#
# Normal case5: comments with valid expression and no generic comment
#
def testNormalCase5(self):
TestCommentLines = \
'''# @Expression LT 1 AND GT 2'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(HelpTxt, PcdErr) = \
ParseDecPcdGenericComment(TestCommentLinesList, 'UnitTest')
self.failIf(HelpTxt)
self.failIf(not PcdErr)
self.assertEqual(PcdErr.GetExpression().strip(), 'LT 1 AND GT 2')
self.failIf(PcdErr.GetValidValueRange())
self.failIf(PcdErr.GetValidValue())
#
# Normal case6: comments with only generic help text
#
def testNormalCase6(self):
TestCommentLines = \
'''#'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(HelpTxt, PcdErr) = \
ParseDecPcdGenericComment(TestCommentLinesList, 'UnitTest')
self.assertEqual(HelpTxt, '\n')
self.failIf(PcdErr)
#
# Error case1: comments with both expression and valid list, use later
# ignore the former and with a warning message
#
def testErrorCase1(self):
TestCommentLines = \
'''## hello world
# second line
# @ValidList 1, 2, 3
# @Expression LT 1 AND GT 2
# other line'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
try:
ParseDecPcdGenericComment(TestCommentLinesList, 'UnitTest')
except Logger.FatalError:
pass
#
# Test ParseDecPcdTailComment
#
class ParseDecPcdTailCommentTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
#
# Normal case1: comments with no SupModeList
#
def testNormalCase1(self):
TestCommentLines = \
'''## #hello world'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(SupModeList, HelpStr) = \
ParseDecPcdTailComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpStr)
self.failIf(SupModeList)
self.assertEqual(HelpStr,
'hello world')
#
# Normal case2: comments with one SupMode
#
def testNormalCase2(self):
TestCommentLines = \
'''## BASE #hello world'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(SupModeList, HelpStr) = \
ParseDecPcdTailComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpStr)
self.failIf(not SupModeList)
self.assertEqual(HelpStr,
'hello world')
self.assertEqual(SupModeList,
['BASE'])
#
# Normal case3: comments with more than one SupMode
#
def testNormalCase3(self):
TestCommentLines = \
'''## BASE UEFI_APPLICATION #hello world'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(SupModeList, HelpStr) = \
ParseDecPcdTailComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpStr)
self.failIf(not SupModeList)
self.assertEqual(HelpStr,
'hello world')
self.assertEqual(SupModeList,
['BASE', 'UEFI_APPLICATION'])
#
# Normal case4: comments with more than one SupMode, no help text
#
def testNormalCase4(self):
TestCommentLines = \
'''## BASE UEFI_APPLICATION'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(SupModeList, HelpStr) = \
ParseDecPcdTailComment(TestCommentLinesList, 'UnitTest')
self.failIf(HelpStr)
self.failIf(not SupModeList)
self.assertEqual(SupModeList,
['BASE', 'UEFI_APPLICATION'])
#
# Normal case5: general comments with no supModList, extract from real case
#
def testNormalCase5(self):
TestCommentLines = \
''' # 1 = 128MB, 2 = 256MB, 3 = MAX'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
(SupModeList, HelpStr) = \
ParseDecPcdTailComment(TestCommentLinesList, 'UnitTest')
self.failIf(not HelpStr)
self.assertEqual(HelpStr,
'1 = 128MB, 2 = 256MB, 3 = MAX')
self.failIf(SupModeList)
#
# Error case2: comments with supModList contains valid and invalid
# module type
#
def testErrorCase2(self):
TestCommentLines = \
'''## BASE INVALID_MODULE_TYPE #hello world'''
CommentList = GetSplitValueList(TestCommentLines, "\n")
LineNum = 0
TestCommentLinesList = []
for Comment in CommentList:
LineNum += 1
TestCommentLinesList.append((Comment, LineNum))
try:
ParseDecPcdTailComment(TestCommentLinesList, 'UnitTest')
except Logger.FatalError:
pass
#
# Test _IsCopyrightLine
#
class _IsCopyrightLineTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
#
# Normal case
#
def testCase1(self):
Line = 'this is a copyright ( line'
Result = _IsCopyrightLine(Line)
self.failIf(not Result)
#
# Normal case
#
def testCase2(self):
Line = 'this is a Copyright ( line'
Result = _IsCopyrightLine(Line)
self.failIf(not Result)
#
# Normal case
#
def testCase3(self):
Line = 'this is not aCopyright ( line'
Result = _IsCopyrightLine(Line)
self.failIf(Result)
#
# Normal case
#
def testCase4(self):
Line = 'this is Copyright( line'
Result = _IsCopyrightLine(Line)
self.failIf(not Result)
#
# Normal case
#
def testCase5(self):
Line = 'this is Copyright (line'
Result = _IsCopyrightLine(Line)
self.failIf(not Result)
#
# Normal case
#
def testCase6(self):
Line = 'this is not Copyright line'
Result = _IsCopyrightLine(Line)
self.failIf(Result)
#
# Normal case
#
def testCase7(self):
Line = 'Copyright (c) line'
Result = _IsCopyrightLine(Line)
self.failIf(not Result)
#
# Normal case
#
def testCase8(self):
Line = ' Copyright (c) line'
Result = _IsCopyrightLine(Line)
self.failIf(not Result)
#
# Normal case
#
def testCase9(self):
Line = 'not a Copyright '
Result = _IsCopyrightLine(Line)
self.failIf(Result)
if __name__ == '__main__':
Logger.Initialize()
unittest.main()

View File

@@ -0,0 +1,284 @@
## @file
# This file contain unit test for DecParser
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials are licensed and made available
# under the terms and conditions of the BSD License which accompanies this
# distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
import os
import unittest
from Parser.DecParserMisc import \
IsValidCArray, \
IsValidPcdDatum
from Parser.DecParser import Dec
from Library.ParserValidate import IsValidCFormatGuid
#
# Test tool function
#
def TestToolFuncs():
assert IsValidCArray('{0x1, 0x23}')
# Empty after comma
assert not IsValidCArray('{0x1, 0x23, }')
# 0x2345 too long
assert not IsValidCArray('{0x1, 0x2345}')
# Must end with '}'
assert not IsValidCArray('{0x1, 0x23, ')
# Whitespace between numbers
assert not IsValidCArray('{0x1, 0x2 3, }')
assert IsValidPcdDatum('VOID*', '"test"')[0]
assert IsValidPcdDatum('VOID*', 'L"test"')[0]
assert IsValidPcdDatum('BOOLEAN', 'TRUE')[0]
assert IsValidPcdDatum('BOOLEAN', 'FALSE')[0]
assert IsValidPcdDatum('BOOLEAN', '0')[0]
assert IsValidPcdDatum('BOOLEAN', '1')[0]
assert IsValidPcdDatum('UINT8', '0xab')[0]
assert not IsValidPcdDatum('UNKNOWNTYPE', '0xabc')[0]
assert not IsValidPcdDatum('UINT8', 'not number')[0]
assert( IsValidCFormatGuid('{ 0xfa0b1735 , 0x87a0, 0x4193, {0xb2, 0x66 , 0x53, 0x8c , 0x38, 0xaf, 0x48, 0xce }}'))
assert( not IsValidCFormatGuid('{ 0xfa0b1735 , 0x87a0, 0x4193, {0xb2, 0x66 , 0x53, 0x8c , 0x38, 0xaf, 0x48, 0xce }} 0xaa'))
def TestTemplate(TestString, TestFunc):
Path = os.path.join(os.getcwd(), 'test.dec')
Path = os.path.normpath(Path)
try:
f = open(Path, 'w')
# Write test string to file
f.write(TestString)
# Close file
f.close()
except:
print 'Can not create temporary file [%s]!' % Path
exit(-1)
# Call test function to test
Ret = TestFunc(Path, TestString)
# Test done, remove temporary file
os.remove(Path)
return Ret
# To make test unit works OK, must set IsRaiseError to True
# This function test right syntax DEC file
# @retval: parser object
#
def TestOK(Path, TestString):
try:
Parser = Dec(Path)
except:
raise 'Bug!!! Correct syntax in DEC file, but exception raised!\n' + TestString
return Parser
# This function test wrong syntax DEC file
# if parser checked wrong syntax, exception thrown and it's expected result
def TestError(Path, TestString):
try:
Dec(Path)
except:
# Raise error, get expected result
return True
raise 'Bug!!! Wrong syntax in DEC file, but passed by DEC parser!!\n' + TestString
def TestDecDefine():
TestString = '''
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = MdePkg
PACKAGE_GUID = 1E73767F-8F52-4603-AEB4-F29B510B6766
PACKAGE_VERSION = 1.02
'''
Parser = TestTemplate(TestString, TestOK)
DefObj = Parser.GetDefineSectionObject()
assert DefObj.GetPackageSpecification() == '0x00010005'
assert DefObj.GetPackageName() == 'MdePkg'
assert DefObj.GetPackageGuid() == '1E73767F-8F52-4603-AEB4-F29B510B6766'
assert DefObj.GetPackageVersion() == '1.02'
TestString = '''
[Defines]
UNKNOW_KEY = 0x00010005 # A unknown key
'''
assert TestTemplate(TestString, TestError)
TestString = '''
[Defines]
PACKAGE_GUID = F-8F52-4603-AEB4-F29B510B6766 # Error GUID
'''
assert TestTemplate(TestString, TestError)
def TestDecInclude():
TestString = '''
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = MdePkg
PACKAGE_GUID = 1E73767F-8F52-4603-AEB4-F29B510B6766
PACKAGE_VERSION = 1.02
[ \\
Includes]
Include
[Includes.IA32]
Include/Ia32
'''
# Create directory in current directory
try:
os.makedirs('Include/Ia32')
except:
pass
Parser = TestTemplate(TestString, TestOK)
IncObj = Parser.GetIncludeSectionObject()
Items = IncObj.GetIncludes()
assert len(Items) == 1
assert Items[0].File == 'Include'
Items = IncObj.GetIncludes('IA32')
assert len(Items) == 1
# normpath is called in DEC parser so '/' is converted to '\'
assert Items[0].File == 'Include\\Ia32'
TestString = '''
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = MdePkg
PACKAGE_GUID = 1E73767F-8F52-4603-AEB4-F29B510B6766
PACKAGE_VERSION = 1.02
[Includes]
Include_not_exist # directory does not exist
'''
assert TestTemplate(TestString, TestError)
os.removedirs('Include/Ia32')
def TestDecGuidPpiProtocol():
TestString = '''
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = MdePkg
PACKAGE_GUID = 1E73767F-8F52-4603-AEB4-F29B510B6766
PACKAGE_VERSION = 1.02
[Guids]
#
# GUID defined in UEFI2.1/UEFI2.0/EFI1.1
#
## Include/Guid/GlobalVariable.h
gEfiGlobalVariableGuid = { 0x8BE4DF61, 0x93CA, 0x11D2, { 0xAA, 0x0D, 0x00, 0xE0, 0x98, 0x03, 0x2B, 0x8C }}
[Protocols]
## Include/Protocol/Bds.h
gEfiBdsArchProtocolGuid = { 0x665E3FF6, 0x46CC, 0x11D4, { 0x9A, 0x38, 0x00, 0x90, 0x27, 0x3F, 0xC1, 0x4D }}
[Ppis]
## Include/Ppi/MasterBootMode.h
gEfiPeiMasterBootModePpiGuid = { 0x7408d748, 0xfc8c, 0x4ee6, {0x92, 0x88, 0xc4, 0xbe, 0xc0, 0x92, 0xa4, 0x10 } }
'''
Parser = TestTemplate(TestString, TestOK)
Obj = Parser.GetGuidSectionObject()
Items = Obj.GetGuids()
assert Obj.GetSectionName() == 'Guids'.upper()
assert len(Items) == 1
assert Items[0].GuidCName == 'gEfiGlobalVariableGuid'
assert Items[0].GuidCValue == '{ 0x8BE4DF61, 0x93CA, 0x11D2, { 0xAA, 0x0D, 0x00, 0xE0, 0x98, 0x03, 0x2B, 0x8C }}'
Obj = Parser.GetProtocolSectionObject()
Items = Obj.GetProtocols()
assert Obj.GetSectionName() == 'Protocols'.upper()
assert len(Items) == 1
assert Items[0].GuidCName == 'gEfiBdsArchProtocolGuid'
assert Items[0].GuidCValue == '{ 0x665E3FF6, 0x46CC, 0x11D4, { 0x9A, 0x38, 0x00, 0x90, 0x27, 0x3F, 0xC1, 0x4D }}'
Obj = Parser.GetPpiSectionObject()
Items = Obj.GetPpis()
assert Obj.GetSectionName() == 'Ppis'.upper()
assert len(Items) == 1
assert Items[0].GuidCName == 'gEfiPeiMasterBootModePpiGuid'
assert Items[0].GuidCValue == '{ 0x7408d748, 0xfc8c, 0x4ee6, {0x92, 0x88, 0xc4, 0xbe, 0xc0, 0x92, 0xa4, 0x10 } }'
def TestDecPcd():
TestString = '''
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = MdePkg
PACKAGE_GUID = 1E73767F-8F52-4603-AEB4-F29B510B6766
PACKAGE_VERSION = 1.02
[PcdsFeatureFlag]
## If TRUE, the component name protocol will not be installed.
gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|FALSE|BOOLEAN|0x0000000d
[PcdsFixedAtBuild]
## Indicates the maximum length of unicode string
gEfiMdePkgTokenSpaceGuid.PcdMaximumUnicodeStringLength|1000000|UINT32|0x00000001
[PcdsFixedAtBuild.IPF]
## The base address of IO port space for IA64 arch
gEfiMdePkgTokenSpaceGuid.PcdIoBlockBaseAddressForIpf|0x0ffffc000000|UINT64|0x0000000f
[PcdsFixedAtBuild,PcdsPatchableInModule]
## This flag is used to control the printout of DebugLib
gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000|UINT32|0x00000006
[PcdsFixedAtBuild,PcdsPatchableInModule,PcdsDynamic]
## This value is used to set the base address of pci express hierarchy
gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000|UINT64|0x0000000a
'''
Parser = TestTemplate(TestString, TestOK)
Obj = Parser.GetPcdSectionObject()
Items = Obj.GetPcds('PcdsFeatureFlag', 'COMMON')
assert len(Items) == 1
assert Items[0].TokenSpaceGuidCName == 'gEfiMdePkgTokenSpaceGuid'
assert Items[0].TokenCName == 'PcdComponentNameDisable'
assert Items[0].DefaultValue == 'FALSE'
assert Items[0].DatumType == 'BOOLEAN'
assert Items[0].TokenValue == '0x0000000d'
Items = Obj.GetPcdsByType('PcdsFixedAtBuild')
assert len(Items) == 4
assert len(Obj.GetPcdsByType('PcdsPatchableInModule')) == 2
def TestDecUserExtension():
TestString = '''
[Defines]
DEC_SPECIFICATION = 0x00010005
PACKAGE_NAME = MdePkg
PACKAGE_GUID = 1E73767F-8F52-4603-AEB4-F29B510B6766
PACKAGE_VERSION = 1.02
[UserExtensions.MyID."TestString".IA32]
Some Strings...
'''
Parser = TestTemplate(TestString, TestOK)
Obj = Parser.GetUserExtensionSectionObject()
Items = Obj.GetAllUserExtensions()
assert len(Items) == 1
assert Items[0].UserString == 'Some Strings...'
assert len(Items[0].ArchAndModuleType) == 1
assert ['MyID', '"TestString"', 'IA32'] in Items[0].ArchAndModuleType
if __name__ == '__main__':
import Logger.Logger
Logger.Logger.Initialize()
unittest.FunctionTestCase(TestToolFuncs).runTest()
unittest.FunctionTestCase(TestDecDefine).runTest()
unittest.FunctionTestCase(TestDecInclude).runTest()
unittest.FunctionTestCase(TestDecGuidPpiProtocol).runTest()
unittest.FunctionTestCase(TestDecPcd).runTest()
unittest.FunctionTestCase(TestDecUserExtension).runTest()
print 'All tests passed...'

View File

@@ -0,0 +1,534 @@
## @file
# This file contain unit test for DecParser
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials are licensed and made available
# under the terms and conditions of the BSD License which accompanies this
# distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
import os
import unittest
from Logger.Log import FatalError
from Parser.DecParser import \
Dec, \
_DecDefine, \
_DecLibraryclass, \
_DecPcd, \
_DecGuid, \
FileContent, \
_DecBase, \
CleanString
from Object.Parser.DecObject import _DecComments
#
# Test CleanString
#
class CleanStringTestCase(unittest.TestCase):
def testCleanString(self):
Line, Comment = CleanString('')
self.assertEqual(Line, '')
self.assertEqual(Comment, '')
Line, Comment = CleanString('line without comment')
self.assertEqual(Line, 'line without comment')
self.assertEqual(Comment, '')
Line, Comment = CleanString('# pure comment')
self.assertEqual(Line, '')
self.assertEqual(Comment, '# pure comment')
Line, Comment = CleanString('line # and comment')
self.assertEqual(Line, 'line')
self.assertEqual(Comment, '# and comment')
def testCleanStringCpp(self):
Line, Comment = CleanString('line // and comment', AllowCppStyleComment = True)
self.assertEqual(Line, 'line')
self.assertEqual(Comment, '# and comment')
#
# Test _DecBase._MacroParser function
#
class MacroParserTestCase(unittest.TestCase):
def setUp(self):
self.dec = _DecBase(FileContent('dummy', []))
def testCorrectMacro(self):
self.dec._MacroParser('DEFINE MARCRO1 = test1')
self.failIf('MARCRO1' not in self.dec._LocalMacro)
self.assertEqual(self.dec._LocalMacro['MARCRO1'], 'test1')
def testErrorMacro1(self):
# Raise fatal error, macro name must be upper case letter
self.assertRaises(FatalError, self.dec._MacroParser, 'DEFINE not_upper_case = test2')
def testErrorMacro2(self):
# No macro name given
self.assertRaises(FatalError, self.dec._MacroParser, 'DEFINE ')
#
# Test _DecBase._TryBackSlash function
#
class TryBackSlashTestCase(unittest.TestCase):
def setUp(self):
Content = [
# Right case
'test no backslash',
'test with backslash \\',
'continue second line',
# Do not precede with whitespace
'\\',
# Empty line after backlash is not allowed
'line with backslash \\',
''
]
self.dec = _DecBase(FileContent('dummy', Content))
def testBackSlash(self):
#
# Right case, assert return values
#
ConcatLine, CommentList = self.dec._TryBackSlash(self.dec._RawData.GetNextLine(), [])
self.assertEqual(ConcatLine, 'test no backslash')
self.assertEqual(CommentList, [])
ConcatLine, CommentList = self.dec._TryBackSlash(self.dec._RawData.GetNextLine(), [])
self.assertEqual(CommentList, [])
self.assertEqual(ConcatLine, 'test with backslash continue second line')
#
# Error cases, assert raise exception
#
self.assertRaises(FatalError, self.dec._TryBackSlash, self.dec._RawData.GetNextLine(), [])
self.assertRaises(FatalError, self.dec._TryBackSlash, self.dec._RawData.GetNextLine(), [])
#
# Test _DecBase.Parse function
#
class DataItem(_DecComments):
def __init__(self):
_DecComments.__init__(self)
self.String = ''
class Data(_DecComments):
def __init__(self):
_DecComments.__init__(self)
# List of DataItem
self.ItemList = []
class TestInner(_DecBase):
def __init__(self, RawData):
_DecBase.__init__(self, RawData)
self.ItemObject = Data()
def _StopCurrentParsing(self, Line):
return Line == '[TOP]'
def _ParseItem(self):
Item = DataItem()
Item.String = self._RawData.CurrentLine
self.ItemObject.ItemList.append(Item)
return Item
def _TailCommentStrategy(self, Comment):
return Comment.find('@comment') != -1
class TestTop(_DecBase):
def __init__(self, RawData):
_DecBase.__init__(self, RawData)
# List of Data
self.ItemObject = []
# Top parser
def _StopCurrentParsing(self, Line):
return False
def _ParseItem(self):
TestParser = TestInner(self._RawData)
TestParser.Parse()
self.ItemObject.append(TestParser.ItemObject)
return TestParser.ItemObject
class ParseTestCase(unittest.TestCase):
def setUp(self):
pass
def testParse(self):
Content = \
'''# Top comment
[TOP]
# sub1 head comment
(test item has both head and tail comment) # sub1 tail comment
# sub2 head comment
(test item has head and special tail comment)
# @comment test TailCommentStrategy branch
(test item has no comment)
# test NextLine branch
[TOP]
sub-item
'''
dec = TestTop(FileContent('dummy', Content.splitlines()))
dec.Parse()
# Two sections
self.assertEqual(len(dec.ItemObject), 2)
data = dec.ItemObject[0]
self.assertEqual(data._HeadComment[0][0], '# Top comment')
self.assertEqual(data._HeadComment[0][1], 1)
# 3 subitems
self.assertEqual(len(data.ItemList), 3)
dataitem = data.ItemList[0]
self.assertEqual(dataitem.String, '(test item has both head and tail comment)')
# Comment content
self.assertEqual(dataitem._HeadComment[0][0], '# sub1 head comment')
self.assertEqual(dataitem._TailComment[0][0], '# sub1 tail comment')
# Comment line number
self.assertEqual(dataitem._HeadComment[0][1], 3)
self.assertEqual(dataitem._TailComment[0][1], 4)
dataitem = data.ItemList[1]
self.assertEqual(dataitem.String, '(test item has head and special tail comment)')
# Comment content
self.assertEqual(dataitem._HeadComment[0][0], '# sub2 head comment')
self.assertEqual(dataitem._TailComment[0][0], '# @comment test TailCommentStrategy branch')
# Comment line number
self.assertEqual(dataitem._HeadComment[0][1], 5)
self.assertEqual(dataitem._TailComment[0][1], 7)
dataitem = data.ItemList[2]
self.assertEqual(dataitem.String, '(test item has no comment)')
# Comment content
self.assertEqual(dataitem._HeadComment, [])
self.assertEqual(dataitem._TailComment, [])
data = dec.ItemObject[1]
self.assertEqual(data._HeadComment[0][0], '# test NextLine branch')
self.assertEqual(data._HeadComment[0][1], 11)
# 1 subitems
self.assertEqual(len(data.ItemList), 1)
dataitem = data.ItemList[0]
self.assertEqual(dataitem.String, 'sub-item')
self.assertEqual(dataitem._HeadComment, [])
self.assertEqual(dataitem._TailComment, [])
#
# Test _DecDefine._ParseItem
#
class DecDefineTestCase(unittest.TestCase):
def GetObj(self, Content):
Obj = _DecDefine(FileContent('dummy', Content.splitlines()))
Obj._RawData.CurrentLine = Obj._RawData.GetNextLine()
return Obj
def testDecDefine(self):
item = self.GetObj('PACKAGE_NAME = MdePkg')._ParseItem()
self.assertEqual(item.Key, 'PACKAGE_NAME')
self.assertEqual(item.Value, 'MdePkg')
def testDecDefine1(self):
obj = self.GetObj('PACKAGE_NAME')
self.assertRaises(FatalError, obj._ParseItem)
def testDecDefine2(self):
obj = self.GetObj('unknown_key = ')
self.assertRaises(FatalError, obj._ParseItem)
def testDecDefine3(self):
obj = self.GetObj('PACKAGE_NAME = ')
self.assertRaises(FatalError, obj._ParseItem)
#
# Test _DecLibraryclass._ParseItem
#
class DecLibraryTestCase(unittest.TestCase):
def GetObj(self, Content):
Obj = _DecLibraryclass(FileContent('dummy', Content.splitlines()))
Obj._RawData.CurrentLine = Obj._RawData.GetNextLine()
return Obj
def testNoInc(self):
obj = self.GetObj('UefiRuntimeLib')
self.assertRaises(FatalError, obj._ParseItem)
def testEmpty(self):
obj = self.GetObj(' | ')
self.assertRaises(FatalError, obj._ParseItem)
def testLibclassNaming(self):
obj = self.GetObj('lowercase_efiRuntimeLib|Include/Library/UefiRuntimeLib.h')
self.assertRaises(FatalError, obj._ParseItem)
def testLibclassExt(self):
obj = self.GetObj('RuntimeLib|Include/Library/UefiRuntimeLib.no_h')
self.assertRaises(FatalError, obj._ParseItem)
def testLibclassRelative(self):
obj = self.GetObj('RuntimeLib|Include/../UefiRuntimeLib.h')
self.assertRaises(FatalError, obj._ParseItem)
#
# Test _DecPcd._ParseItem
#
class DecPcdTestCase(unittest.TestCase):
def GetObj(self, Content):
Obj = _DecPcd(FileContent('dummy', Content.splitlines()))
Obj._RawData.CurrentLine = Obj._RawData.GetNextLine()
Obj._RawData.CurrentScope = [('PcdsFeatureFlag'.upper(), 'COMMON')]
return Obj
def testOK(self):
item = self.GetObj('gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|FALSE|BOOLEAN|0x0000000d')._ParseItem()
self.assertEqual(item.TokenSpaceGuidCName, 'gEfiMdePkgTokenSpaceGuid')
self.assertEqual(item.TokenCName, 'PcdComponentNameDisable')
self.assertEqual(item.DefaultValue, 'FALSE')
self.assertEqual(item.DatumType, 'BOOLEAN')
self.assertEqual(item.TokenValue, '0x0000000d')
def testNoCvar(self):
obj = self.GetObj('123ai.PcdComponentNameDisable|FALSE|BOOLEAN|0x0000000d')
self.assertRaises(FatalError, obj._ParseItem)
def testSplit(self):
obj = self.GetObj('gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable FALSE|BOOLEAN|0x0000000d')
self.assertRaises(FatalError, obj._ParseItem)
obj = self.GetObj('gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|FALSE|BOOLEAN|0x0000000d | abc')
self.assertRaises(FatalError, obj._ParseItem)
def testUnknownType(self):
obj = self.GetObj('gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|FALSE|unknown|0x0000000d')
self.assertRaises(FatalError, obj._ParseItem)
def testVoid(self):
obj = self.GetObj('gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|abc|VOID*|0x0000000d')
self.assertRaises(FatalError, obj._ParseItem)
def testUINT(self):
obj = self.GetObj('gEfiMdePkgTokenSpaceGuid.PcdComponentNameDisable|0xabc|UINT8|0x0000000d')
self.assertRaises(FatalError, obj._ParseItem)
#
# Test _DecInclude._ParseItem
#
class DecIncludeTestCase(unittest.TestCase):
#
# Test code to be added
#
pass
#
# Test _DecGuid._ParseItem
#
class DecGuidTestCase(unittest.TestCase):
def GetObj(self, Content):
Obj = _DecGuid(FileContent('dummy', Content.splitlines()))
Obj._RawData.CurrentLine = Obj._RawData.GetNextLine()
Obj._RawData.CurrentScope = [('guids'.upper(), 'COMMON')]
return Obj
def testCValue(self):
item = self.GetObj('gEfiIpSecProtocolGuid={ 0xdfb386f7, 0xe100, 0x43ad,'
' {0x9c, 0x9a, 0xed, 0x90, 0xd0, 0x8a, 0x5e, 0x12 }}')._ParseItem()
self.assertEqual(item.GuidCName, 'gEfiIpSecProtocolGuid')
self.assertEqual(item.GuidCValue, '{ 0xdfb386f7, 0xe100, 0x43ad, {0x9c, 0x9a, 0xed, 0x90, 0xd0, 0x8a, 0x5e, 0x12 }}')
def testGuidString(self):
item = self.GetObj('gEfiIpSecProtocolGuid=1E73767F-8F52-4603-AEB4-F29B510B6766')._ParseItem()
self.assertEqual(item.GuidCName, 'gEfiIpSecProtocolGuid')
self.assertEqual(item.GuidCValue, '1E73767F-8F52-4603-AEB4-F29B510B6766')
def testNoValue1(self):
obj = self.GetObj('gEfiIpSecProtocolGuid')
self.assertRaises(FatalError, obj._ParseItem)
def testNoValue2(self):
obj = self.GetObj('gEfiIpSecProtocolGuid=')
self.assertRaises(FatalError, obj._ParseItem)
def testNoName(self):
obj = self.GetObj('=')
self.assertRaises(FatalError, obj._ParseItem)
#
# Test Dec.__init__
#
class DecDecInitTestCase(unittest.TestCase):
def testNoDecFile(self):
self.assertRaises(FatalError, Dec, 'No_Such_File')
class TmpFile:
def __init__(self, File):
self.File = File
def Write(self, Content):
try:
FileObj = open(self.File, 'w')
FileObj.write(Content)
FileObj.close()
except:
pass
def Remove(self):
try:
os.remove(self.File)
except:
pass
#
# Test Dec._UserExtentionSectionParser
#
class DecUESectionTestCase(unittest.TestCase):
def setUp(self):
self.File = TmpFile('test.dec')
self.File.Write(
'''[userextensions.intel."myid"]
[userextensions.intel."myid".IA32]
[userextensions.intel."myid".IA32,]
[userextensions.intel."myid]
'''
)
def tearDown(self):
self.File.Remove()
def testUserExtentionHeader(self):
dec = Dec('test.dec', False)
# OK: [userextensions.intel."myid"]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
dec._UserExtentionSectionParser()
self.assertEqual(len(dec._RawData.CurrentScope), 1)
self.assertEqual(dec._RawData.CurrentScope[0][0], 'userextensions'.upper())
self.assertEqual(dec._RawData.CurrentScope[0][1], 'intel')
self.assertEqual(dec._RawData.CurrentScope[0][2], '"myid"')
self.assertEqual(dec._RawData.CurrentScope[0][3], 'COMMON')
# OK: [userextensions.intel."myid".IA32]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
dec._UserExtentionSectionParser()
self.assertEqual(len(dec._RawData.CurrentScope), 1)
self.assertEqual(dec._RawData.CurrentScope[0][0], 'userextensions'.upper())
self.assertEqual(dec._RawData.CurrentScope[0][1], 'intel')
self.assertEqual(dec._RawData.CurrentScope[0][2], '"myid"')
self.assertEqual(dec._RawData.CurrentScope[0][3], 'IA32')
# Fail: [userextensions.intel."myid".IA32,]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._UserExtentionSectionParser)
# Fail: [userextensions.intel."myid]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._UserExtentionSectionParser)
#
# Test Dec._SectionHeaderParser
#
class DecSectionTestCase(unittest.TestCase):
def setUp(self):
self.File = TmpFile('test.dec')
self.File.Write(
'''[no section start or end
[,] # empty sub-section
[unknow_section_name]
[Includes.IA32.other] # no third one
[PcdsFeatureFlag, PcdsFixedAtBuild] # feature flag PCD must not be in the same section of other types of PCD
[Includes.IA32, Includes.IA32]
[Includes, Includes.IA32] # common cannot be with other arch
[Includes.IA32, PcdsFeatureFlag] # different section name
''' )
def tearDown(self):
self.File.Remove()
def testSectionHeader(self):
dec = Dec('test.dec', False)
# [no section start or end
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
#[,] # empty sub-section
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
# [unknow_section_name]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
# [Includes.IA32.other] # no third one
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
# [PcdsFeatureFlag, PcdsFixedAtBuild]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
# [Includes.IA32, Includes.IA32]
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
dec._SectionHeaderParser()
self.assertEqual(len(dec._RawData.CurrentScope), 1)
self.assertEqual(dec._RawData.CurrentScope[0][0], 'Includes'.upper())
self.assertEqual(dec._RawData.CurrentScope[0][1], 'IA32')
# [Includes, Includes.IA32] # common cannot be with other arch
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
# [Includes.IA32, PcdsFeatureFlag] # different section name not allowed
dec._RawData.CurrentLine = CleanString(dec._RawData.GetNextLine())[0]
self.assertRaises(FatalError, dec._SectionHeaderParser)
#
# Test Dec._ParseDecComment
#
class DecDecCommentTestCase(unittest.TestCase):
def testDecHeadComment(self):
File = TmpFile('test.dec')
File.Write(
'''# abc
##''')
dec = Dec('test.dec', False)
dec.ParseDecComment()
self.assertEqual(len(dec._HeadComment), 2)
self.assertEqual(dec._HeadComment[0][0], '# abc')
self.assertEqual(dec._HeadComment[0][1], 1)
self.assertEqual(dec._HeadComment[1][0], '##')
self.assertEqual(dec._HeadComment[1][1], 2)
File.Remove()
def testNoDoubleComment(self):
File = TmpFile('test.dec')
File.Write(
'''# abc
#
[section_start]''')
dec = Dec('test.dec', False)
dec.ParseDecComment()
self.assertEqual(len(dec._HeadComment), 2)
self.assertEqual(dec._HeadComment[0][0], '# abc')
self.assertEqual(dec._HeadComment[0][1], 1)
self.assertEqual(dec._HeadComment[1][0], '#')
self.assertEqual(dec._HeadComment[1][1], 2)
File.Remove()
if __name__ == '__main__':
import Logger.Logger
Logger.Logger.Initialize()
unittest.main()

View File

@@ -0,0 +1,386 @@
## @file
# This file contain unit test for Test [Binary] section part of InfParser
#
# Copyright (c) 2011, Intel Corporation. All rights reserved.<BR>
#
# This program and the accompanying materials are licensed and made available
# under the terms and conditions of the BSD License which accompanies this
# distribution. The full text of the license may be found at
# http://opensource.org/licenses/bsd-license.php
#
# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
import os
#import Object.Parser.InfObject as InfObject
from Object.Parser.InfCommonObject import CurrentLine
from Object.Parser.InfCommonObject import InfLineCommentObject
from Object.Parser.InfBinaryObject import InfBinariesObject
import Logger.Log as Logger
import Library.GlobalData as Global
##
# Test Common binary item
#
#-------------start of common binary item test input--------------------------#
#
# Only has 1 element, binary item Type
#
SectionStringsCommonItem1 = \
"""
GUID
"""
#
# Have 2 elements, binary item Type and FileName
#
SectionStringsCommonItem2 = \
"""
GUID | Test/Test.guid
"""
#
# Have 3 elements, Type | FileName | Target | Family | TagName | FeatureFlagExp
#
SectionStringsCommonItem3 = \
"""
GUID | Test/Test.guid | DEBUG
"""
#
# Have 3 elements, Type | FileName | Target
# Target with MACRO defined in [Define] section
#
SectionStringsCommonItem4 = \
"""
GUID | Test/Test.guid | $(TARGET)
"""
#
# Have 3 elements, Type | FileName | Target
# FileName with MACRO defined in [Binary] section
#
SectionStringsCommonItem5 = \
"""
DEFINE BINARY_FILE_PATH = Test
GUID | $(BINARY_FILE_PATH)/Test.guid | $(TARGET)
"""
#
# Have 4 elements, Type | FileName | Target | Family
#
SectionStringsCommonItem6 = \
"""
GUID | Test/Test.guid | DEBUG | *
"""
#
# Have 4 elements, Type | FileName | Target | Family
#
SectionStringsCommonItem7 = \
"""
GUID | Test/Test.guid | DEBUG | MSFT
"""
#
# Have 5 elements, Type | FileName | Target | Family | TagName
#
SectionStringsCommonItem8 = \
"""
GUID | Test/Test.guid | DEBUG | MSFT | TEST
"""
#
# Have 6 elements, Type | FileName | Target | Family | TagName | FFE
#
SectionStringsCommonItem9 = \
"""
GUID | Test/Test.guid | DEBUG | MSFT | TEST | TRUE
"""
#
# Have 7 elements, Type | FileName | Target | Family | TagName | FFE | Overflow
# Test wrong format
#
SectionStringsCommonItem10 = \
"""
GUID | Test/Test.guid | DEBUG | MSFT | TEST | TRUE | OVERFLOW
"""
#-------------end of common binary item test input----------------------------#
#-------------start of VER type binary item test input------------------------#
#
# Has 1 element, error format
#
SectionStringsVerItem1 = \
"""
VER
"""
#
# Have 5 elements, error format(Maximum elements amount is 4)
#
SectionStringsVerItem2 = \
"""
VER | Test/Test.ver | * | TRUE | OverFlow
"""
#
# Have 2 elements, Type | FileName
#
SectionStringsVerItem3 = \
"""
VER | Test/Test.ver
"""
#
# Have 3 elements, Type | FileName | Target
#
SectionStringsVerItem4 = \
"""
VER | Test/Test.ver | DEBUG
"""
#
# Have 4 elements, Type | FileName | Target | FeatureFlagExp
#
SectionStringsVerItem5 = \
"""
VER | Test/Test.ver | DEBUG | TRUE
"""
#
# Exist 2 VER items, both opened.
#
SectionStringsVerItem6 = \
"""
VER | Test/Test.ver | * | TRUE
VER | Test/Test2.ver | * | TRUE
"""
#
# Exist 2 VER items, only 1 opened.
#
SectionStringsVerItem7 = \
"""
VER | Test/Test.ver | * | TRUE
VER | Test/Test2.ver | * | FALSE
"""
#-------------end of VER type binary item test input--------------------------#
#-------------start of UI type binary item test input-------------------------#
#
# Test only one UI section can exist
#
SectionStringsUiItem1 = \
"""
UI | Test/Test.ui | * | TRUE
UI | Test/Test2.ui | * | TRUE
"""
SectionStringsUiItem2 = \
"""
UI | Test/Test.ui | * | TRUE
SEC_UI | Test/Test2.ui | * | TRUE
"""
SectionStringsUiItem3 = \
"""
UI | Test/Test.ui | * | TRUE
UI | Test/Test2.ui | * | FALSE
"""
#
# Has 1 element, error format
#
SectionStringsUiItem4 = \
"""
UI
"""
#
# Have 5 elements, error format(Maximum elements amount is 4)
#
SectionStringsUiItem5 = \
"""
UI | Test/Test.ui | * | TRUE | OverFlow
"""
#
# Have 2 elements, Type | FileName
#
SectionStringsUiItem6 = \
"""
UI | Test/Test.ui
"""
#
# Have 3 elements, Type | FileName | Target
#
SectionStringsUiItem7 = \
"""
UI | Test/Test.ui | DEBUG
"""
#
# Have 4 elements, Type | FileName | Target | FeatureFlagExp
#
SectionStringsUiItem8 = \
"""
UI | Test/Test.ui | DEBUG | TRUE
"""
#---------------end of UI type binary item test input-------------------------#
gFileName = "BinarySectionTest.inf"
##
# Construct SectionString for call section parser usage.
#
def StringToSectionString(String):
Lines = String.split('\n')
LineNo = 0
SectionString = []
for Line in Lines:
if Line.strip() == '':
continue
SectionString.append((Line, LineNo, ''))
LineNo = LineNo + 1
return SectionString
def PrepareTest(String):
SectionString = StringToSectionString(String)
ItemList = []
for Item in SectionString:
ValueList = Item[0].split('|')
for count in range(len(ValueList)):
ValueList[count] = ValueList[count].strip()
if len(ValueList) >= 2:
#
# Create a temp file for test.
#
FileName = os.path.normpath(os.path.realpath(ValueList[1].strip()))
try:
TempFile = open (FileName, "w")
TempFile.close()
except:
print "File Create Error"
CurrentLine = CurrentLine()
CurrentLine.SetFileName("Test")
CurrentLine.SetLineString(Item[0])
CurrentLine.SetLineNo(Item[1])
InfLineCommentObject = InfLineCommentObject()
ItemList.append((ValueList, InfLineCommentObject, CurrentLine))
return ItemList
if __name__ == '__main__':
Logger.Initialize()
InfBinariesInstance = InfBinariesObject()
ArchList = ['COMMON']
Global.gINF_MODULE_DIR = os.getcwd()
AllPassedFlag = True
#
# For All Ui test
#
UiStringList = [
SectionStringsUiItem1,
SectionStringsUiItem2,
SectionStringsUiItem3,
SectionStringsUiItem4,
SectionStringsUiItem5,
SectionStringsUiItem6,
SectionStringsUiItem7,
SectionStringsUiItem8
]
for Item in UiStringList:
Ui = PrepareTest(Item)
if Item == SectionStringsUiItem4 or Item == SectionStringsUiItem5:
try:
InfBinariesInstance.SetBinary(Ui = Ui, ArchList = ArchList)
except Logger.FatalError:
pass
else:
try:
InfBinariesInstance.SetBinary(Ui = Ui, ArchList = ArchList)
except:
AllPassedFlag = False
#
# For All Ver Test
#
VerStringList = [
SectionStringsVerItem1,
SectionStringsVerItem2,
SectionStringsVerItem3,
SectionStringsVerItem4,
SectionStringsVerItem5,
SectionStringsVerItem6,
SectionStringsVerItem7
]
for Item in VerStringList:
Ver = PrepareTest(Item)
if Item == SectionStringsVerItem1 or \
Item == SectionStringsVerItem2:
try:
InfBinariesInstance.SetBinary(Ver = Ver, ArchList = ArchList)
except:
pass
else:
try:
InfBinariesInstance.SetBinary(Ver = Ver, ArchList = ArchList)
except:
AllPassedFlag = False
#
# For All Common Test
#
CommonStringList = [
SectionStringsCommonItem1,
SectionStringsCommonItem2,
SectionStringsCommonItem3,
SectionStringsCommonItem4,
SectionStringsCommonItem5,
SectionStringsCommonItem6,
SectionStringsCommonItem7,
SectionStringsCommonItem8,
SectionStringsCommonItem9,
SectionStringsCommonItem10
]
for Item in CommonStringList:
CommonBin = PrepareTest(Item)
if Item == SectionStringsCommonItem10 or \
Item == SectionStringsCommonItem1:
try:
InfBinariesInstance.SetBinary(CommonBinary = CommonBin, ArchList = ArchList)
except:
pass
else:
try:
InfBinariesInstance.SetBinary(Ver = Ver, ArchList = ArchList)
except:
print "Test Failed!"
AllPassedFlag = False
if AllPassedFlag :
print 'All tests passed...'
else:
print 'Some unit test failed!'