TestTools.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. from __future__ import print_function
  2. ## @file
  3. # Utility functions and classes for BaseTools unit tests
  4. #
  5. # Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.<BR>
  6. #
  7. # SPDX-License-Identifier: BSD-2-Clause-Patent
  8. #
  9. ##
  10. # Import Modules
  11. #
  12. import base64
  13. import os
  14. import os.path
  15. import random
  16. import shutil
  17. import subprocess
  18. import sys
  19. import unittest
  20. import codecs
  21. TestsDir = os.path.realpath(os.path.split(sys.argv[0])[0])
  22. BaseToolsDir = os.path.realpath(os.path.join(TestsDir, '..'))
  23. CSourceDir = os.path.join(BaseToolsDir, 'Source', 'C')
  24. PythonSourceDir = os.path.join(BaseToolsDir, 'Source', 'Python')
  25. TestTempDir = os.path.join(TestsDir, 'TestTempDir')
  26. if PythonSourceDir not in sys.path:
  27. #
  28. # Allow unit tests to import BaseTools python modules. This is very useful
  29. # for writing unit tests.
  30. #
  31. sys.path.append(PythonSourceDir)
  32. def MakeTheTestSuite(localItems):
  33. tests = []
  34. for name, item in localItems.items():
  35. if isinstance(item, type):
  36. if issubclass(item, unittest.TestCase):
  37. tests.append(unittest.TestLoader().loadTestsFromTestCase(item))
  38. elif issubclass(item, unittest.TestSuite):
  39. tests.append(item())
  40. return lambda: unittest.TestSuite(tests)
  41. def GetBaseToolsPaths():
  42. if sys.platform in ('win32', 'win64'):
  43. return [ os.path.join(BaseToolsDir, 'Bin', sys.platform.title()) ]
  44. else:
  45. uname = os.popen('uname -sm').read().strip()
  46. for char in (' ', '/'):
  47. uname = uname.replace(char, '-')
  48. return [
  49. os.path.join(BaseToolsDir, 'Bin', uname),
  50. os.path.join(BaseToolsDir, 'BinWrappers', uname),
  51. os.path.join(BaseToolsDir, 'BinWrappers', 'PosixLike')
  52. ]
  53. BaseToolsBinPaths = GetBaseToolsPaths()
  54. class BaseToolsTest(unittest.TestCase):
  55. def cleanOutDir(self, dir):
  56. for dirItem in os.listdir(dir):
  57. if dirItem in ('.', '..'): continue
  58. dirItem = os.path.join(dir, dirItem)
  59. self.RemoveFileOrDir(dirItem)
  60. def CleanUpTmpDir(self):
  61. if os.path.exists(self.testDir):
  62. self.cleanOutDir(self.testDir)
  63. def HandleTreeDeleteError(self, function, path, excinfo):
  64. os.chmod(path, stat.S_IWRITE)
  65. function(path)
  66. def RemoveDir(self, dir):
  67. shutil.rmtree(dir, False, self.HandleTreeDeleteError)
  68. def RemoveFileOrDir(self, path):
  69. if not os.path.exists(path):
  70. return
  71. elif os.path.isdir(path):
  72. self.RemoveDir(path)
  73. else:
  74. os.remove(path)
  75. def DisplayBinaryData(self, description, data):
  76. print(description, '(base64 encoded):')
  77. b64data = base64.b64encode(data)
  78. print(b64data)
  79. def DisplayFile(self, fileName):
  80. sys.stdout.write(self.ReadTmpFile(fileName))
  81. sys.stdout.flush()
  82. def FindToolBin(self, toolName):
  83. for binPath in BaseToolsBinPaths:
  84. bin = os.path.join(binPath, toolName)
  85. if os.path.exists(bin):
  86. break
  87. assert os.path.exists(bin)
  88. return bin
  89. def RunTool(self, *args, **kwd):
  90. if 'toolName' in kwd: toolName = kwd['toolName']
  91. else: toolName = None
  92. if 'logFile' in kwd: logFile = kwd['logFile']
  93. else: logFile = None
  94. if toolName is None: toolName = self.toolName
  95. bin = self.FindToolBin(toolName)
  96. if logFile is not None:
  97. logFile = open(os.path.join(self.testDir, logFile), 'w')
  98. popenOut = logFile
  99. else:
  100. popenOut = subprocess.PIPE
  101. args = [toolName] + list(args)
  102. Proc = subprocess.Popen(
  103. args, executable=bin,
  104. stdout=popenOut, stderr=subprocess.STDOUT
  105. )
  106. if logFile is None:
  107. Proc.stdout.read()
  108. return Proc.wait()
  109. def GetTmpFilePath(self, fileName):
  110. return os.path.join(self.testDir, fileName)
  111. def OpenTmpFile(self, fileName, mode = 'r'):
  112. return open(os.path.join(self.testDir, fileName), mode)
  113. def ReadTmpFile(self, fileName):
  114. f = open(self.GetTmpFilePath(fileName), 'r')
  115. data = f.read()
  116. f.close()
  117. return data
  118. def WriteTmpFile(self, fileName, data):
  119. if isinstance(data, bytes):
  120. with open(self.GetTmpFilePath(fileName), 'wb') as f:
  121. f.write(data)
  122. else:
  123. with codecs.open(self.GetTmpFilePath(fileName), 'w', encoding='utf-8') as f:
  124. f.write(data)
  125. def GenRandomFileData(self, fileName, minlen = None, maxlen = None):
  126. if maxlen is None: maxlen = minlen
  127. f = self.OpenTmpFile(fileName, 'w')
  128. f.write(self.GetRandomString(minlen, maxlen))
  129. f.close()
  130. def GetRandomString(self, minlen = None, maxlen = None):
  131. if minlen is None: minlen = 1024
  132. if maxlen is None: maxlen = minlen
  133. return ''.join(
  134. [chr(random.randint(0, 255))
  135. for x in range(random.randint(minlen, maxlen))
  136. ])
  137. def setUp(self):
  138. self.savedEnvPath = os.environ['PATH']
  139. self.savedSysPath = sys.path[:]
  140. for binPath in BaseToolsBinPaths:
  141. os.environ['PATH'] = \
  142. os.path.pathsep.join((os.environ['PATH'], binPath))
  143. self.testDir = TestTempDir
  144. if not os.path.exists(self.testDir):
  145. os.mkdir(self.testDir)
  146. else:
  147. self.cleanOutDir(self.testDir)
  148. def tearDown(self):
  149. self.RemoveFileOrDir(self.testDir)
  150. os.environ['PATH'] = self.savedEnvPath
  151. sys.path = self.savedSysPath