diff options
| author | kx <kx@radix.pro> | 2024-06-04 06:43:08 +0300 |
|---|---|---|
| committer | kx <kx@radix.pro> | 2024-06-04 06:43:08 +0300 |
| commit | 7e2ccccace24636f29ddc210b94606abd4c7e42b (patch) | |
| tree | 545d43ea12671048956cafeb12303e84d601e571 /BaseTools/Tests | |
| parent | 27b044605cd5f6b33a3d231576003850b3fe305b (diff) | |
| download | edk2-trunk.tar.xz | |
Renormalized end-of-lines from master@27b044605cd5f6b33a3d231576003850b3fe305btrunk
Diffstat (limited to 'BaseTools/Tests')
| -rw-r--r-- | BaseTools/Tests/CToolsTests.py | 58 | ||||
| -rw-r--r-- | BaseTools/Tests/CheckPythonSyntax.py | 136 | ||||
| -rw-r--r-- | BaseTools/Tests/CheckUnicodeSourceFiles.py | 350 | ||||
| -rw-r--r-- | BaseTools/Tests/GNUmakefile | 30 | ||||
| -rw-r--r-- | BaseTools/Tests/PythonTest.py | 54 | ||||
| -rw-r--r-- | BaseTools/Tests/PythonToolsTests.py | 56 | ||||
| -rw-r--r-- | BaseTools/Tests/RunTests.py | 64 | ||||
| -rw-r--r-- | BaseTools/Tests/TestRegularExpression.py | 96 | ||||
| -rw-r--r-- | BaseTools/Tests/TestTools.py | 372 | ||||
| -rw-r--r-- | BaseTools/Tests/TianoCompress.py | 138 |
10 files changed, 677 insertions, 677 deletions
diff --git a/BaseTools/Tests/CToolsTests.py b/BaseTools/Tests/CToolsTests.py index 2bc1b62d40..e5e20f41db 100644 --- a/BaseTools/Tests/CToolsTests.py +++ b/BaseTools/Tests/CToolsTests.py @@ -1,29 +1,29 @@ -## @file
-# Unit tests for C based BaseTools
-#
-# Copyright (c) 2008, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-import os
-import sys
-import unittest
-
-import TianoCompress
-modules = (
- TianoCompress,
- )
-
-
-def TheTestSuite():
- suites = list(map(lambda module: module.TheTestSuite(), modules))
- return unittest.TestSuite(suites)
-
-if __name__ == '__main__':
- allTests = TheTestSuite()
- unittest.TextTestRunner().run(allTests)
-
+## @file +# Unit tests for C based BaseTools +# +# Copyright (c) 2008, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +import os +import sys +import unittest + +import TianoCompress +modules = ( + TianoCompress, + ) + + +def TheTestSuite(): + suites = list(map(lambda module: module.TheTestSuite(), modules)) + return unittest.TestSuite(suites) + +if __name__ == '__main__': + allTests = TheTestSuite() + unittest.TextTestRunner().run(allTests) + diff --git a/BaseTools/Tests/CheckPythonSyntax.py b/BaseTools/Tests/CheckPythonSyntax.py index 099920721f..29ed80b43f 100644 --- a/BaseTools/Tests/CheckPythonSyntax.py +++ b/BaseTools/Tests/CheckPythonSyntax.py @@ -1,68 +1,68 @@ -## @file
-# Unit tests for checking syntax of Python source code
-#
-# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-import os
-import unittest
-import py_compile
-
-import TestTools
-
-class Tests(TestTools.BaseToolsTest):
-
- def setUp(self):
- TestTools.BaseToolsTest.setUp(self)
-
- def SingleFileTest(self, filename):
- try:
- py_compile.compile(filename, doraise=True)
- except Exception as e:
- self.fail('syntax error: %s, Error is %s' % (filename, str(e)))
-
-def MakePythonSyntaxCheckTests():
- def GetAllPythonSourceFiles():
- pythonSourceFiles = []
- for (root, dirs, files) in os.walk(TestTools.PythonSourceDir):
- for filename in files:
- if filename.lower().endswith('.py'):
- pythonSourceFiles.append(
- os.path.join(root, filename)
- )
- return pythonSourceFiles
-
- def MakeTestName(filename):
- assert filename.lower().endswith('.py')
- name = filename[:-3]
- name = name.replace(TestTools.PythonSourceDir, '')
- name = name.replace(os.path.sep, '_')
- return 'test' + name
-
- def MakeNewTest(filename):
- test = MakeTestName(filename)
- newmethod = lambda self: self.SingleFileTest(filename)
- setattr(
- Tests,
- test,
- newmethod
- )
-
- for filename in GetAllPythonSourceFiles():
- MakeNewTest(filename)
-
-MakePythonSyntaxCheckTests()
-del MakePythonSyntaxCheckTests
-
-TheTestSuite = TestTools.MakeTheTestSuite(locals())
-
-if __name__ == '__main__':
- allTests = TheTestSuite()
- unittest.TextTestRunner().run(allTests)
-
-
+## @file +# Unit tests for checking syntax of Python source code +# +# Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +import os +import unittest +import py_compile + +import TestTools + +class Tests(TestTools.BaseToolsTest): + + def setUp(self): + TestTools.BaseToolsTest.setUp(self) + + def SingleFileTest(self, filename): + try: + py_compile.compile(filename, doraise=True) + except Exception as e: + self.fail('syntax error: %s, Error is %s' % (filename, str(e))) + +def MakePythonSyntaxCheckTests(): + def GetAllPythonSourceFiles(): + pythonSourceFiles = [] + for (root, dirs, files) in os.walk(TestTools.PythonSourceDir): + for filename in files: + if filename.lower().endswith('.py'): + pythonSourceFiles.append( + os.path.join(root, filename) + ) + return pythonSourceFiles + + def MakeTestName(filename): + assert filename.lower().endswith('.py') + name = filename[:-3] + name = name.replace(TestTools.PythonSourceDir, '') + name = name.replace(os.path.sep, '_') + return 'test' + name + + def MakeNewTest(filename): + test = MakeTestName(filename) + newmethod = lambda self: self.SingleFileTest(filename) + setattr( + Tests, + test, + newmethod + ) + + for filename in GetAllPythonSourceFiles(): + MakeNewTest(filename) + +MakePythonSyntaxCheckTests() +del MakePythonSyntaxCheckTests + +TheTestSuite = TestTools.MakeTheTestSuite(locals()) + +if __name__ == '__main__': + allTests = TheTestSuite() + unittest.TextTestRunner().run(allTests) + + diff --git a/BaseTools/Tests/CheckUnicodeSourceFiles.py b/BaseTools/Tests/CheckUnicodeSourceFiles.py index 1502402619..effe1661e5 100644 --- a/BaseTools/Tests/CheckUnicodeSourceFiles.py +++ b/BaseTools/Tests/CheckUnicodeSourceFiles.py @@ -1,175 +1,175 @@ -## @file
-# Unit tests for AutoGen.UniClassObject
-#
-# Copyright (c) 2015, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-import os
-import unittest
-
-import codecs
-
-import TestTools
-
-from Common.Misc import PathClass
-import AutoGen.UniClassObject as BtUni
-
-from Common import EdkLogger
-EdkLogger.InitializeForUnitTest()
-
-class Tests(TestTools.BaseToolsTest):
-
- SampleData = u'''
- #langdef en-US "English"
- #string STR_A #language en-US "STR_A for en-US"
- '''
-
- def EncodeToFile(self, encoding, string=None):
- if string is None:
- string = self.SampleData
- if encoding is not None:
- data = codecs.encode(string, encoding)
- else:
- data = string
- path = 'input.uni'
- self.WriteTmpFile(path, data)
- return PathClass(self.GetTmpFilePath(path))
-
- def ErrorFailure(self, error, encoding, shouldPass):
- msg = error + ' should '
- if shouldPass:
- msg += 'not '
- msg += 'be generated for '
- msg += '%s data in a .uni file' % encoding
- self.fail(msg)
-
- def UnicodeErrorFailure(self, encoding, shouldPass):
- self.ErrorFailure('UnicodeError', encoding, shouldPass)
-
- def EdkErrorFailure(self, encoding, shouldPass):
- self.ErrorFailure('EdkLogger.FatalError', encoding, shouldPass)
-
- def CheckFile(self, encoding, shouldPass, string=None):
- path = self.EncodeToFile(encoding, string)
- try:
- BtUni.UniFileClassObject([path])
- if shouldPass:
- return
- except UnicodeError:
- if not shouldPass:
- return
- else:
- self.UnicodeErrorFailure(encoding, shouldPass)
- except EdkLogger.FatalError:
- if not shouldPass:
- return
- else:
- self.EdkErrorFailure(encoding, shouldPass)
- except Exception:
- pass
-
- self.EdkErrorFailure(encoding, shouldPass)
-
- def testUtf16InUniFile(self):
- self.CheckFile('utf_16', shouldPass=True)
-
- def testSupplementaryPlaneUnicodeCharInUtf16File(self):
- #
- # Supplementary Plane characters can exist in UTF-16 files,
- # but they are not valid UCS-2 characters.
- #
- # This test makes sure that BaseTools rejects these characters
- # if seen in a .uni file.
- #
- data = u'''
- #langdef en-US "English"
- #string STR_A #language en-US "CodePoint (\U00010300) > 0xFFFF"
- '''
-
- self.CheckFile('utf_16', shouldPass=False, string=data)
-
- def testSurrogatePairUnicodeCharInUtf16File(self):
- #
- # Surrogate Pair code points are used in UTF-16 files to
- # encode the Supplementary Plane characters. But, a Surrogate
- # Pair code point which is not followed by another Surrogate
- # Pair code point might be interpreted as a single code point
- # with the Surrogate Pair code point.
- #
- # This test makes sure that BaseTools rejects these characters
- # if seen in a .uni file.
- #
- data = codecs.BOM_UTF16_LE + b'//\x01\xd8 '
-
- self.CheckFile(encoding=None, shouldPass=False, string=data)
-
- def testValidUtf8File(self):
- self.CheckFile(encoding='utf_8', shouldPass=True)
-
- def testValidUtf8FileWithBom(self):
- #
- # Same test as testValidUtf8File, but add the UTF-8 BOM
- #
- data = codecs.BOM_UTF8 + codecs.encode(self.SampleData, 'utf_8')
-
- self.CheckFile(encoding=None, shouldPass=True, string=data)
-
- def test32bitUnicodeCharInUtf8File(self):
- data = u'''
- #langdef en-US "English"
- #string STR_A #language en-US "CodePoint (\U00010300) > 0xFFFF"
- '''
-
- self.CheckFile('utf_16', shouldPass=False, string=data)
-
- def test32bitUnicodeCharInUtf8File(self):
- data = u'''
- #langdef en-US "English"
- #string STR_A #language en-US "CodePoint (\U00010300) > 0xFFFF"
- '''
-
- self.CheckFile('utf_8', shouldPass=False, string=data)
-
- def test32bitUnicodeCharInUtf8Comment(self):
- data = u'''
- // Even in comments, we reject non-UCS-2 chars: \U00010300
- #langdef en-US "English"
- #string STR_A #language en-US "A"
- '''
-
- self.CheckFile('utf_8', shouldPass=False, string=data)
-
- def testSurrogatePairUnicodeCharInUtf8File(self):
- #
- # Surrogate Pair code points are used in UTF-16 files to
- # encode the Supplementary Plane characters. In UTF-8, it is
- # trivial to encode these code points, but they are not valid
- # code points for characters, since they are reserved for the
- # UTF-16 Surrogate Pairs.
- #
- # This test makes sure that BaseTools rejects these characters
- # if seen in a .uni file.
- #
- data = b'\xed\xa0\x81'
-
- self.CheckFile(encoding=None, shouldPass=False, string=data)
-
- def testSurrogatePairUnicodeCharInUtf8FileWithBom(self):
- #
- # Same test as testSurrogatePairUnicodeCharInUtf8File, but add
- # the UTF-8 BOM
- #
- data = codecs.BOM_UTF8 + b'\xed\xa0\x81'
-
- self.CheckFile(encoding=None, shouldPass=False, string=data)
-
-TheTestSuite = TestTools.MakeTheTestSuite(locals())
-
-if __name__ == '__main__':
- allTests = TheTestSuite()
- unittest.TextTestRunner().run(allTests)
+## @file +# Unit tests for AutoGen.UniClassObject +# +# Copyright (c) 2015, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +import os +import unittest + +import codecs + +import TestTools + +from Common.Misc import PathClass +import AutoGen.UniClassObject as BtUni + +from Common import EdkLogger +EdkLogger.InitializeForUnitTest() + +class Tests(TestTools.BaseToolsTest): + + SampleData = u''' + #langdef en-US "English" + #string STR_A #language en-US "STR_A for en-US" + ''' + + def EncodeToFile(self, encoding, string=None): + if string is None: + string = self.SampleData + if encoding is not None: + data = codecs.encode(string, encoding) + else: + data = string + path = 'input.uni' + self.WriteTmpFile(path, data) + return PathClass(self.GetTmpFilePath(path)) + + def ErrorFailure(self, error, encoding, shouldPass): + msg = error + ' should ' + if shouldPass: + msg += 'not ' + msg += 'be generated for ' + msg += '%s data in a .uni file' % encoding + self.fail(msg) + + def UnicodeErrorFailure(self, encoding, shouldPass): + self.ErrorFailure('UnicodeError', encoding, shouldPass) + + def EdkErrorFailure(self, encoding, shouldPass): + self.ErrorFailure('EdkLogger.FatalError', encoding, shouldPass) + + def CheckFile(self, encoding, shouldPass, string=None): + path = self.EncodeToFile(encoding, string) + try: + BtUni.UniFileClassObject([path]) + if shouldPass: + return + except UnicodeError: + if not shouldPass: + return + else: + self.UnicodeErrorFailure(encoding, shouldPass) + except EdkLogger.FatalError: + if not shouldPass: + return + else: + self.EdkErrorFailure(encoding, shouldPass) + except Exception: + pass + + self.EdkErrorFailure(encoding, shouldPass) + + def testUtf16InUniFile(self): + self.CheckFile('utf_16', shouldPass=True) + + def testSupplementaryPlaneUnicodeCharInUtf16File(self): + # + # Supplementary Plane characters can exist in UTF-16 files, + # but they are not valid UCS-2 characters. + # + # This test makes sure that BaseTools rejects these characters + # if seen in a .uni file. + # + data = u''' + #langdef en-US "English" + #string STR_A #language en-US "CodePoint (\U00010300) > 0xFFFF" + ''' + + self.CheckFile('utf_16', shouldPass=False, string=data) + + def testSurrogatePairUnicodeCharInUtf16File(self): + # + # Surrogate Pair code points are used in UTF-16 files to + # encode the Supplementary Plane characters. But, a Surrogate + # Pair code point which is not followed by another Surrogate + # Pair code point might be interpreted as a single code point + # with the Surrogate Pair code point. + # + # This test makes sure that BaseTools rejects these characters + # if seen in a .uni file. + # + data = codecs.BOM_UTF16_LE + b'//\x01\xd8 ' + + self.CheckFile(encoding=None, shouldPass=False, string=data) + + def testValidUtf8File(self): + self.CheckFile(encoding='utf_8', shouldPass=True) + + def testValidUtf8FileWithBom(self): + # + # Same test as testValidUtf8File, but add the UTF-8 BOM + # + data = codecs.BOM_UTF8 + codecs.encode(self.SampleData, 'utf_8') + + self.CheckFile(encoding=None, shouldPass=True, string=data) + + def test32bitUnicodeCharInUtf8File(self): + data = u''' + #langdef en-US "English" + #string STR_A #language en-US "CodePoint (\U00010300) > 0xFFFF" + ''' + + self.CheckFile('utf_16', shouldPass=False, string=data) + + def test32bitUnicodeCharInUtf8File(self): + data = u''' + #langdef en-US "English" + #string STR_A #language en-US "CodePoint (\U00010300) > 0xFFFF" + ''' + + self.CheckFile('utf_8', shouldPass=False, string=data) + + def test32bitUnicodeCharInUtf8Comment(self): + data = u''' + // Even in comments, we reject non-UCS-2 chars: \U00010300 + #langdef en-US "English" + #string STR_A #language en-US "A" + ''' + + self.CheckFile('utf_8', shouldPass=False, string=data) + + def testSurrogatePairUnicodeCharInUtf8File(self): + # + # Surrogate Pair code points are used in UTF-16 files to + # encode the Supplementary Plane characters. In UTF-8, it is + # trivial to encode these code points, but they are not valid + # code points for characters, since they are reserved for the + # UTF-16 Surrogate Pairs. + # + # This test makes sure that BaseTools rejects these characters + # if seen in a .uni file. + # + data = b'\xed\xa0\x81' + + self.CheckFile(encoding=None, shouldPass=False, string=data) + + def testSurrogatePairUnicodeCharInUtf8FileWithBom(self): + # + # Same test as testSurrogatePairUnicodeCharInUtf8File, but add + # the UTF-8 BOM + # + data = codecs.BOM_UTF8 + b'\xed\xa0\x81' + + self.CheckFile(encoding=None, shouldPass=False, string=data) + +TheTestSuite = TestTools.MakeTheTestSuite(locals()) + +if __name__ == '__main__': + allTests = TheTestSuite() + unittest.TextTestRunner().run(allTests) diff --git a/BaseTools/Tests/GNUmakefile b/BaseTools/Tests/GNUmakefile index 20b387864f..db82973ae8 100644 --- a/BaseTools/Tests/GNUmakefile +++ b/BaseTools/Tests/GNUmakefile @@ -1,15 +1,15 @@ -## @file
-# GNU/Linux makefile for 'Tests' module build.
-#
-# Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR>
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-all: test
-
-test:
- @if command -v "${PYTHON_COMMAND}" >/dev/null 2>&1; then ${PYTHON_COMMAND} RunTests.py; else python RunTests.py; fi
-
-clean:
- find . -name '*.pyc' -exec rm '{}' ';'
-
+## @file +# GNU/Linux makefile for 'Tests' module build. +# +# Copyright (c) 2009 - 2010, Intel Corporation. All rights reserved.<BR> +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +all: test + +test: + @if command -v "${PYTHON_COMMAND}" >/dev/null 2>&1; then ${PYTHON_COMMAND} RunTests.py; else python RunTests.py; fi + +clean: + find . -name '*.pyc' -exec rm '{}' ';' + diff --git a/BaseTools/Tests/PythonTest.py b/BaseTools/Tests/PythonTest.py index b87c78570e..cf0f372166 100644 --- a/BaseTools/Tests/PythonTest.py +++ b/BaseTools/Tests/PythonTest.py @@ -1,27 +1,27 @@ -## @file
-# Test whether PYTHON_COMMAND is available and the
-# minimum Python version is installed.
-#
-# Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.<BR>
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-import sys
-
-if __name__ == '__main__':
- # Check if the major and minor versions required were specified.
- if len(sys.argv) >= 3:
- req_major_version = int(sys.argv[1])
- req_minor_version = int(sys.argv[2])
- else:
- # If the minimum version wasn't specified on the command line,
- # default to 3.6 because BaseTools uses syntax from PEP 526
- # (https://peps.python.org/pep-0526/)
- req_major_version = 3
- req_minor_version = 6
-
- if sys.version_info.major == req_major_version and \
- sys.version_info.minor >= req_minor_version:
- sys.exit(0)
- else:
- sys.exit(1)
+## @file +# Test whether PYTHON_COMMAND is available and the +# minimum Python version is installed. +# +# Copyright (c) 2013 - 2018, Intel Corporation. All rights reserved.<BR> +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +import sys + +if __name__ == '__main__': + # Check if the major and minor versions required were specified. + if len(sys.argv) >= 3: + req_major_version = int(sys.argv[1]) + req_minor_version = int(sys.argv[2]) + else: + # If the minimum version wasn't specified on the command line, + # default to 3.6 because BaseTools uses syntax from PEP 526 + # (https://peps.python.org/pep-0526/) + req_major_version = 3 + req_minor_version = 6 + + if sys.version_info.major == req_major_version and \ + sys.version_info.minor >= req_minor_version: + sys.exit(0) + else: + sys.exit(1) diff --git a/BaseTools/Tests/PythonToolsTests.py b/BaseTools/Tests/PythonToolsTests.py index 05b27ab033..a287f3a3cb 100644 --- a/BaseTools/Tests/PythonToolsTests.py +++ b/BaseTools/Tests/PythonToolsTests.py @@ -1,28 +1,28 @@ -## @file
-# Unit tests for Python based BaseTools
-#
-# Copyright (c) 2008 - 2015, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-import os
-import sys
-import unittest
-
-
-def TheTestSuite():
- suites = []
- import CheckPythonSyntax
- suites.append(CheckPythonSyntax.TheTestSuite())
- import CheckUnicodeSourceFiles
- suites.append(CheckUnicodeSourceFiles.TheTestSuite())
- return unittest.TestSuite(suites)
-
-if __name__ == '__main__':
- allTests = TheTestSuite()
- unittest.TextTestRunner().run(allTests)
-
+## @file +# Unit tests for Python based BaseTools +# +# Copyright (c) 2008 - 2015, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +import os +import sys +import unittest + + +def TheTestSuite(): + suites = [] + import CheckPythonSyntax + suites.append(CheckPythonSyntax.TheTestSuite()) + import CheckUnicodeSourceFiles + suites.append(CheckUnicodeSourceFiles.TheTestSuite()) + return unittest.TestSuite(suites) + +if __name__ == '__main__': + allTests = TheTestSuite() + unittest.TextTestRunner().run(allTests) + diff --git a/BaseTools/Tests/RunTests.py b/BaseTools/Tests/RunTests.py index 934683a446..6003f11794 100644 --- a/BaseTools/Tests/RunTests.py +++ b/BaseTools/Tests/RunTests.py @@ -1,32 +1,32 @@ -## @file
-# Unit tests for BaseTools utilities
-#
-# Copyright (c) 2008, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-import os
-import sys
-import unittest
-
-import TestTools
-
-def GetCTestSuite():
- import CToolsTests
- return CToolsTests.TheTestSuite()
-
-def GetPythonTestSuite():
- import PythonToolsTests
- return PythonToolsTests.TheTestSuite()
-
-def GetAllTestsSuite():
- return unittest.TestSuite([GetCTestSuite(), GetPythonTestSuite()])
-
-if __name__ == '__main__':
- allTests = GetAllTestsSuite()
- unittest.TextTestRunner(verbosity=2).run(allTests)
-
+## @file +# Unit tests for BaseTools utilities +# +# Copyright (c) 2008, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +import os +import sys +import unittest + +import TestTools + +def GetCTestSuite(): + import CToolsTests + return CToolsTests.TheTestSuite() + +def GetPythonTestSuite(): + import PythonToolsTests + return PythonToolsTests.TheTestSuite() + +def GetAllTestsSuite(): + return unittest.TestSuite([GetCTestSuite(), GetPythonTestSuite()]) + +if __name__ == '__main__': + allTests = GetAllTestsSuite() + unittest.TextTestRunner(verbosity=2).run(allTests) + diff --git a/BaseTools/Tests/TestRegularExpression.py b/BaseTools/Tests/TestRegularExpression.py index 3e6c5f4463..c11591f104 100644 --- a/BaseTools/Tests/TestRegularExpression.py +++ b/BaseTools/Tests/TestRegularExpression.py @@ -1,48 +1,48 @@ -## @file
-# Routines for generating Pcd Database
-#
-# Copyright (c) 2018, Intel Corporation. All rights reserved.<BR>
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-
-import unittest
-from Common.Misc import RemoveCComments
-from Workspace.BuildClassObject import ArrayIndex
-
-class TestRe(unittest.TestCase):
- def test_ccomments(self):
- TestStr1 = """ {0x01,0x02} """
- self.assertEquals(TestStr1, RemoveCComments(TestStr1))
-
- TestStr2 = """ L'TestString' """
- self.assertEquals(TestStr2, RemoveCComments(TestStr2))
-
- TestStr3 = """ 'TestString' """
- self.assertEquals(TestStr3, RemoveCComments(TestStr3))
-
- TestStr4 = """
- {CODE({
- {0x01, {0x02, 0x03, 0x04 }},// Data comment
- {0x01, {0x02, 0x03, 0x04 }},// Data comment
- })
- } /*
- This is multiple line comments
- The seconde line comment
- */
- // This is a comment
- """
- Expect_TestStr4 = """{CODE({
- {0x01, {0x02, 0x03, 0x04 }},
- {0x01, {0x02, 0x03, 0x04 }},
- })
- }"""
- self.assertEquals(Expect_TestStr4, RemoveCComments(TestStr4).strip())
-
- def Test_ArrayIndex(self):
- TestStr1 = """[1]"""
- self.assertEquals(['[1]'], ArrayIndex.findall(TestStr1))
-
- TestStr2 = """[1][2][0x1][0x01][]"""
- self.assertEquals(['[1]','[2]','[0x1]','[0x01]','[]'], ArrayIndex.findall(TestStr2))
-
-if __name__ == '__main__':
- unittest.main()
+## @file +# Routines for generating Pcd Database +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.<BR> +# SPDX-License-Identifier: BSD-2-Clause-Patent + +import unittest +from Common.Misc import RemoveCComments +from Workspace.BuildClassObject import ArrayIndex + +class TestRe(unittest.TestCase): + def test_ccomments(self): + TestStr1 = """ {0x01,0x02} """ + self.assertEquals(TestStr1, RemoveCComments(TestStr1)) + + TestStr2 = """ L'TestString' """ + self.assertEquals(TestStr2, RemoveCComments(TestStr2)) + + TestStr3 = """ 'TestString' """ + self.assertEquals(TestStr3, RemoveCComments(TestStr3)) + + TestStr4 = """ + {CODE({ + {0x01, {0x02, 0x03, 0x04 }},// Data comment + {0x01, {0x02, 0x03, 0x04 }},// Data comment + }) + } /* + This is multiple line comments + The seconde line comment + */ + // This is a comment + """ + Expect_TestStr4 = """{CODE({ + {0x01, {0x02, 0x03, 0x04 }}, + {0x01, {0x02, 0x03, 0x04 }}, + }) + }""" + self.assertEquals(Expect_TestStr4, RemoveCComments(TestStr4).strip()) + + def Test_ArrayIndex(self): + TestStr1 = """[1]""" + self.assertEquals(['[1]'], ArrayIndex.findall(TestStr1)) + + TestStr2 = """[1][2][0x1][0x01][]""" + self.assertEquals(['[1]','[2]','[0x1]','[0x01]','[]'], ArrayIndex.findall(TestStr2)) + +if __name__ == '__main__': + unittest.main() diff --git a/BaseTools/Tests/TestTools.py b/BaseTools/Tests/TestTools.py index 545e1e3c13..e789dae356 100644 --- a/BaseTools/Tests/TestTools.py +++ b/BaseTools/Tests/TestTools.py @@ -1,186 +1,186 @@ -from __future__ import print_function
-## @file
-# Utility functions and classes for BaseTools unit tests
-#
-# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-import base64
-import os
-import os.path
-import random
-import shutil
-import subprocess
-import sys
-import unittest
-import codecs
-
-TestsDir = os.path.realpath(os.path.split(sys.argv[0])[0])
-BaseToolsDir = os.path.realpath(os.path.join(TestsDir, '..'))
-CSourceDir = os.path.join(BaseToolsDir, 'Source', 'C')
-PythonSourceDir = os.path.join(BaseToolsDir, 'Source', 'Python')
-TestTempDir = os.path.join(TestsDir, 'TestTempDir')
-
-if PythonSourceDir not in sys.path:
- #
- # Allow unit tests to import BaseTools python modules. This is very useful
- # for writing unit tests.
- #
- sys.path.append(PythonSourceDir)
-
-def MakeTheTestSuite(localItems):
- tests = []
- for name, item in localItems.items():
- if isinstance(item, type):
- if issubclass(item, unittest.TestCase):
- tests.append(unittest.TestLoader().loadTestsFromTestCase(item))
- elif issubclass(item, unittest.TestSuite):
- tests.append(item())
- return lambda: unittest.TestSuite(tests)
-
-def GetBaseToolsPaths():
- if sys.platform in ('win32', 'win64'):
- return [ os.path.join(BaseToolsDir, 'Bin', sys.platform.title()) ]
- else:
- uname = os.popen('uname -sm').read().strip()
- for char in (' ', '/'):
- uname = uname.replace(char, '-')
- return [
- os.path.join(BaseToolsDir, 'Bin', uname),
- os.path.join(BaseToolsDir, 'BinWrappers', uname),
- os.path.join(BaseToolsDir, 'BinWrappers', 'PosixLike')
- ]
-
-BaseToolsBinPaths = GetBaseToolsPaths()
-
-class BaseToolsTest(unittest.TestCase):
-
- def cleanOutDir(self, dir):
- for dirItem in os.listdir(dir):
- if dirItem in ('.', '..'): continue
- dirItem = os.path.join(dir, dirItem)
- self.RemoveFileOrDir(dirItem)
-
- def CleanUpTmpDir(self):
- if os.path.exists(self.testDir):
- self.cleanOutDir(self.testDir)
-
- def HandleTreeDeleteError(self, function, path, excinfo):
- os.chmod(path, stat.S_IWRITE)
- function(path)
-
- def RemoveDir(self, dir):
- shutil.rmtree(dir, False, self.HandleTreeDeleteError)
-
- def RemoveFileOrDir(self, path):
- if not os.path.exists(path):
- return
- elif os.path.isdir(path):
- self.RemoveDir(path)
- else:
- os.remove(path)
-
- def DisplayBinaryData(self, description, data):
- print(description, '(base64 encoded):')
- b64data = base64.b64encode(data)
- print(b64data)
-
- def DisplayFile(self, fileName):
- sys.stdout.write(self.ReadTmpFile(fileName))
- sys.stdout.flush()
-
- def FindToolBin(self, toolName):
- for binPath in BaseToolsBinPaths:
- bin = os.path.join(binPath, toolName)
- if os.path.exists(bin):
- break
- assert os.path.exists(bin)
- return bin
-
- def RunTool(self, *args, **kwd):
- if 'toolName' in kwd: toolName = kwd['toolName']
- else: toolName = None
- if 'logFile' in kwd: logFile = kwd['logFile']
- else: logFile = None
-
- if toolName is None: toolName = self.toolName
- if sys.platform == "win32":
- toolName += ".exe"
- bin = self.FindToolBin(toolName)
- if logFile is not None:
- logFile = open(os.path.join(self.testDir, logFile), 'w')
- popenOut = logFile
- else:
- popenOut = subprocess.PIPE
-
- args = [toolName] + list(args)
-
- Proc = subprocess.Popen(
- args, executable=bin,
- stdout=popenOut, stderr=subprocess.STDOUT
- )
-
- if logFile is None:
- Proc.stdout.read()
-
- return Proc.wait()
-
- def GetTmpFilePath(self, fileName):
- return os.path.join(self.testDir, fileName)
-
- def OpenTmpFile(self, fileName, mode = 'r'):
- return open(os.path.join(self.testDir, fileName), mode)
-
- def ReadTmpFile(self, fileName):
- f = open(self.GetTmpFilePath(fileName), 'rb')
- data = f.read()
- f.close()
- return data
-
- def WriteTmpFile(self, fileName, data):
- if isinstance(data, bytes):
- with open(self.GetTmpFilePath(fileName), 'wb') as f:
- f.write(data)
- else:
- with codecs.open(self.GetTmpFilePath(fileName), 'w', encoding='utf-8') as f:
- f.write(data)
-
- def GenRandomFileData(self, fileName, minlen = None, maxlen = None):
- if maxlen is None: maxlen = minlen
- f = self.OpenTmpFile(fileName, 'w')
- f.write(self.GetRandomString(minlen, maxlen))
- f.close()
-
- def GetRandomString(self, minlen = None, maxlen = None):
- if minlen is None: minlen = 1024
- if maxlen is None: maxlen = minlen
- return ''.join(
- [chr(random.randint(0, 255))
- for x in range(random.randint(minlen, maxlen))
- ])
-
- def setUp(self):
- self.savedEnvPath = os.environ['PATH']
- self.savedSysPath = sys.path[:]
-
- for binPath in BaseToolsBinPaths:
- os.environ['PATH'] = \
- os.path.pathsep.join((os.environ['PATH'], binPath))
-
- self.testDir = TestTempDir
- if not os.path.exists(self.testDir):
- os.mkdir(self.testDir)
- else:
- self.cleanOutDir(self.testDir)
-
- def tearDown(self):
- self.RemoveFileOrDir(self.testDir)
-
- os.environ['PATH'] = self.savedEnvPath
- sys.path = self.savedSysPath
-
+from __future__ import print_function +## @file +# Utility functions and classes for BaseTools unit tests +# +# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +import base64 +import os +import os.path +import random +import shutil +import subprocess +import sys +import unittest +import codecs + +TestsDir = os.path.realpath(os.path.split(sys.argv[0])[0]) +BaseToolsDir = os.path.realpath(os.path.join(TestsDir, '..')) +CSourceDir = os.path.join(BaseToolsDir, 'Source', 'C') +PythonSourceDir = os.path.join(BaseToolsDir, 'Source', 'Python') +TestTempDir = os.path.join(TestsDir, 'TestTempDir') + +if PythonSourceDir not in sys.path: + # + # Allow unit tests to import BaseTools python modules. This is very useful + # for writing unit tests. + # + sys.path.append(PythonSourceDir) + +def MakeTheTestSuite(localItems): + tests = [] + for name, item in localItems.items(): + if isinstance(item, type): + if issubclass(item, unittest.TestCase): + tests.append(unittest.TestLoader().loadTestsFromTestCase(item)) + elif issubclass(item, unittest.TestSuite): + tests.append(item()) + return lambda: unittest.TestSuite(tests) + +def GetBaseToolsPaths(): + if sys.platform in ('win32', 'win64'): + return [ os.path.join(BaseToolsDir, 'Bin', sys.platform.title()) ] + else: + uname = os.popen('uname -sm').read().strip() + for char in (' ', '/'): + uname = uname.replace(char, '-') + return [ + os.path.join(BaseToolsDir, 'Bin', uname), + os.path.join(BaseToolsDir, 'BinWrappers', uname), + os.path.join(BaseToolsDir, 'BinWrappers', 'PosixLike') + ] + +BaseToolsBinPaths = GetBaseToolsPaths() + +class BaseToolsTest(unittest.TestCase): + + def cleanOutDir(self, dir): + for dirItem in os.listdir(dir): + if dirItem in ('.', '..'): continue + dirItem = os.path.join(dir, dirItem) + self.RemoveFileOrDir(dirItem) + + def CleanUpTmpDir(self): + if os.path.exists(self.testDir): + self.cleanOutDir(self.testDir) + + def HandleTreeDeleteError(self, function, path, excinfo): + os.chmod(path, stat.S_IWRITE) + function(path) + + def RemoveDir(self, dir): + shutil.rmtree(dir, False, self.HandleTreeDeleteError) + + def RemoveFileOrDir(self, path): + if not os.path.exists(path): + return + elif os.path.isdir(path): + self.RemoveDir(path) + else: + os.remove(path) + + def DisplayBinaryData(self, description, data): + print(description, '(base64 encoded):') + b64data = base64.b64encode(data) + print(b64data) + + def DisplayFile(self, fileName): + sys.stdout.write(self.ReadTmpFile(fileName)) + sys.stdout.flush() + + def FindToolBin(self, toolName): + for binPath in BaseToolsBinPaths: + bin = os.path.join(binPath, toolName) + if os.path.exists(bin): + break + assert os.path.exists(bin) + return bin + + def RunTool(self, *args, **kwd): + if 'toolName' in kwd: toolName = kwd['toolName'] + else: toolName = None + if 'logFile' in kwd: logFile = kwd['logFile'] + else: logFile = None + + if toolName is None: toolName = self.toolName + if sys.platform == "win32": + toolName += ".exe" + bin = self.FindToolBin(toolName) + if logFile is not None: + logFile = open(os.path.join(self.testDir, logFile), 'w') + popenOut = logFile + else: + popenOut = subprocess.PIPE + + args = [toolName] + list(args) + + Proc = subprocess.Popen( + args, executable=bin, + stdout=popenOut, stderr=subprocess.STDOUT + ) + + if logFile is None: + Proc.stdout.read() + + return Proc.wait() + + def GetTmpFilePath(self, fileName): + return os.path.join(self.testDir, fileName) + + def OpenTmpFile(self, fileName, mode = 'r'): + return open(os.path.join(self.testDir, fileName), mode) + + def ReadTmpFile(self, fileName): + f = open(self.GetTmpFilePath(fileName), 'rb') + data = f.read() + f.close() + return data + + def WriteTmpFile(self, fileName, data): + if isinstance(data, bytes): + with open(self.GetTmpFilePath(fileName), 'wb') as f: + f.write(data) + else: + with codecs.open(self.GetTmpFilePath(fileName), 'w', encoding='utf-8') as f: + f.write(data) + + def GenRandomFileData(self, fileName, minlen = None, maxlen = None): + if maxlen is None: maxlen = minlen + f = self.OpenTmpFile(fileName, 'w') + f.write(self.GetRandomString(minlen, maxlen)) + f.close() + + def GetRandomString(self, minlen = None, maxlen = None): + if minlen is None: minlen = 1024 + if maxlen is None: maxlen = minlen + return ''.join( + [chr(random.randint(0, 255)) + for x in range(random.randint(minlen, maxlen)) + ]) + + def setUp(self): + self.savedEnvPath = os.environ['PATH'] + self.savedSysPath = sys.path[:] + + for binPath in BaseToolsBinPaths: + os.environ['PATH'] = \ + os.path.pathsep.join((os.environ['PATH'], binPath)) + + self.testDir = TestTempDir + if not os.path.exists(self.testDir): + os.mkdir(self.testDir) + else: + self.cleanOutDir(self.testDir) + + def tearDown(self): + self.RemoveFileOrDir(self.testDir) + + os.environ['PATH'] = self.savedEnvPath + sys.path = self.savedSysPath + diff --git a/BaseTools/Tests/TianoCompress.py b/BaseTools/Tests/TianoCompress.py index 685968b18f..bc419fd744 100644 --- a/BaseTools/Tests/TianoCompress.py +++ b/BaseTools/Tests/TianoCompress.py @@ -1,69 +1,69 @@ -## @file
-# Unit tests for TianoCompress utility
-#
-# Copyright (c) 2008, Intel Corporation. All rights reserved.<BR>
-#
-# SPDX-License-Identifier: BSD-2-Clause-Patent
-#
-
-##
-# Import Modules
-#
-from __future__ import print_function
-import os
-import random
-import sys
-import unittest
-
-import TestTools
-
-class Tests(TestTools.BaseToolsTest):
-
- def setUp(self):
- TestTools.BaseToolsTest.setUp(self)
- self.toolName = 'TianoCompress'
-
- def testHelp(self):
- result = self.RunTool('--help', logFile='help')
- #self.DisplayFile('help')
- self.assertTrue(result == 0)
-
- def compressionTestCycle(self, data):
- path = self.GetTmpFilePath('input')
- self.WriteTmpFile('input', data)
- result = self.RunTool(
- '-e',
- '-o', self.GetTmpFilePath('output1'),
- self.GetTmpFilePath('input')
- )
- self.assertTrue(result == 0)
- result = self.RunTool(
- '-d',
- '-o', self.GetTmpFilePath('output2'),
- self.GetTmpFilePath('output1')
- )
- self.assertTrue(result == 0)
- start = self.ReadTmpFile('input')
- finish = self.ReadTmpFile('output2')
- startEqualsFinish = start == finish
- if not startEqualsFinish:
- print()
- print('Original data did not match decompress(compress(data))')
- self.DisplayBinaryData('original data', start)
- self.DisplayBinaryData('after compression', self.ReadTmpFile('output1'))
- self.DisplayBinaryData('after decompression', finish)
- self.assertTrue(startEqualsFinish)
-
- def testRandomDataCycles(self):
- for i in range(8):
- data = self.GetRandomString(1024, 2048)
- self.compressionTestCycle(data)
- self.CleanUpTmpDir()
-
-TheTestSuite = TestTools.MakeTheTestSuite(locals())
-
-if __name__ == '__main__':
- allTests = TheTestSuite()
- unittest.TextTestRunner().run(allTests)
-
-
+## @file +# Unit tests for TianoCompress utility +# +# Copyright (c) 2008, Intel Corporation. All rights reserved.<BR> +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +## +# Import Modules +# +from __future__ import print_function +import os +import random +import sys +import unittest + +import TestTools + +class Tests(TestTools.BaseToolsTest): + + def setUp(self): + TestTools.BaseToolsTest.setUp(self) + self.toolName = 'TianoCompress' + + def testHelp(self): + result = self.RunTool('--help', logFile='help') + #self.DisplayFile('help') + self.assertTrue(result == 0) + + def compressionTestCycle(self, data): + path = self.GetTmpFilePath('input') + self.WriteTmpFile('input', data) + result = self.RunTool( + '-e', + '-o', self.GetTmpFilePath('output1'), + self.GetTmpFilePath('input') + ) + self.assertTrue(result == 0) + result = self.RunTool( + '-d', + '-o', self.GetTmpFilePath('output2'), + self.GetTmpFilePath('output1') + ) + self.assertTrue(result == 0) + start = self.ReadTmpFile('input') + finish = self.ReadTmpFile('output2') + startEqualsFinish = start == finish + if not startEqualsFinish: + print() + print('Original data did not match decompress(compress(data))') + self.DisplayBinaryData('original data', start) + self.DisplayBinaryData('after compression', self.ReadTmpFile('output1')) + self.DisplayBinaryData('after decompression', finish) + self.assertTrue(startEqualsFinish) + + def testRandomDataCycles(self): + for i in range(8): + data = self.GetRandomString(1024, 2048) + self.compressionTestCycle(data) + self.CleanUpTmpDir() + +TheTestSuite = TestTools.MakeTheTestSuite(locals()) + +if __name__ == '__main__': + allTests = TheTestSuite() + unittest.TextTestRunner().run(allTests) + + |
