test_util.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # SPDX-License-Identifier: GPL-2.0+
  2. #
  3. # Copyright (c) 2016 Google, Inc
  4. #
  5. from contextlib import contextmanager
  6. import glob
  7. import multiprocessing
  8. import os
  9. import sys
  10. import unittest
  11. from patman import command
  12. from patman import test_util
  13. from io import StringIO
  14. use_concurrent = True
  15. try:
  16. from concurrencytest import ConcurrentTestSuite, fork_for_tests
  17. except:
  18. use_concurrent = False
  19. def RunTestCoverage(prog, filter_fname, exclude_list, build_dir, required=None):
  20. """Run tests and check that we get 100% coverage
  21. Args:
  22. prog: Program to run (with be passed a '-t' argument to run tests
  23. filter_fname: Normally all *.py files in the program's directory will
  24. be included. If this is not None, then it is used to filter the
  25. list so that only filenames that don't contain filter_fname are
  26. included.
  27. exclude_list: List of file patterns to exclude from the coverage
  28. calculation
  29. build_dir: Build directory, used to locate libfdt.py
  30. required: List of modules which must be in the coverage report
  31. Raises:
  32. ValueError if the code coverage is not 100%
  33. """
  34. # This uses the build output from sandbox_spl to get _libfdt.so
  35. path = os.path.dirname(prog)
  36. if filter_fname:
  37. glob_list = glob.glob(os.path.join(path, '*.py'))
  38. glob_list = [fname for fname in glob_list if filter_fname in fname]
  39. else:
  40. glob_list = []
  41. glob_list += exclude_list
  42. glob_list += ['*libfdt.py', '*site-packages*', '*dist-packages*']
  43. test_cmd = 'test' if 'binman' in prog else '-t'
  44. prefix = ''
  45. if build_dir:
  46. prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir
  47. cmd = ('%spython3-coverage run '
  48. '--omit "%s" %s %s -P1' % (prefix, ','.join(glob_list),
  49. prog, test_cmd))
  50. os.system(cmd)
  51. stdout = command.Output('python3-coverage', 'report')
  52. lines = stdout.splitlines()
  53. if required:
  54. # Convert '/path/to/name.py' just the module name 'name'
  55. test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0]
  56. for line in lines if '/etype/' in line])
  57. missing_list = required
  58. missing_list.discard('__init__')
  59. missing_list.difference_update(test_set)
  60. if missing_list:
  61. print('Missing tests for %s' % (', '.join(missing_list)))
  62. print(stdout)
  63. ok = False
  64. coverage = lines[-1].split(' ')[-1]
  65. ok = True
  66. print(coverage)
  67. if coverage != '100%':
  68. print(stdout)
  69. print("Type 'python3-coverage html' to get a report in "
  70. 'htmlcov/index.html')
  71. print('Coverage error: %s, but should be 100%%' % coverage)
  72. ok = False
  73. if not ok:
  74. raise ValueError('Test coverage failure')
  75. # Use this to suppress stdout/stderr output:
  76. # with capture_sys_output() as (stdout, stderr)
  77. # ...do something...
  78. @contextmanager
  79. def capture_sys_output():
  80. capture_out, capture_err = StringIO(), StringIO()
  81. old_out, old_err = sys.stdout, sys.stderr
  82. try:
  83. sys.stdout, sys.stderr = capture_out, capture_err
  84. yield capture_out, capture_err
  85. finally:
  86. sys.stdout, sys.stderr = old_out, old_err
  87. def ReportResult(toolname:str, test_name: str, result: unittest.TestResult):
  88. """Report the results from a suite of tests
  89. Args:
  90. toolname: Name of the tool that ran the tests
  91. test_name: Name of test that was run, or None for all
  92. result: A unittest.TestResult object containing the results
  93. """
  94. # Remove errors which just indicate a missing test. Since Python v3.5 If an
  95. # ImportError or AttributeError occurs while traversing name then a
  96. # synthetic test that raises that error when run will be returned. These
  97. # errors are included in the errors accumulated by result.errors.
  98. if test_name:
  99. errors = []
  100. for test, err in result.errors:
  101. if ("has no attribute '%s'" % test_name) not in err:
  102. errors.append((test, err))
  103. result.testsRun -= 1
  104. result.errors = errors
  105. print(result)
  106. for test, err in result.errors:
  107. print(test.id(), err)
  108. for test, err in result.failures:
  109. print(err, result.failures)
  110. if result.skipped:
  111. print('%d binman test%s SKIPPED:' %
  112. (len(result.skipped), 's' if len(result.skipped) > 1 else ''))
  113. for skip_info in result.skipped:
  114. print('%s: %s' % (skip_info[0], skip_info[1]))
  115. if result.errors or result.failures:
  116. print('binman tests FAILED')
  117. return 1
  118. return 0
  119. def RunTestSuites(result, debug, verbosity, test_preserve_dirs, processes,
  120. test_name, toolpath, test_class_list):
  121. """Run a series of test suites and collect the results
  122. Args:
  123. result: A unittest.TestResult object to add the results to
  124. debug: True to enable debugging, which shows a full stack trace on error
  125. verbosity: Verbosity level to use (0-4)
  126. test_preserve_dirs: True to preserve the input directory used by tests
  127. so that it can be examined afterwards (only useful for debugging
  128. tests). If a single test is selected (in args[0]) it also preserves
  129. the output directory for this test. Both directories are displayed
  130. on the command line.
  131. processes: Number of processes to use to run tests (None=same as #CPUs)
  132. test_name: Name of test to run, or None for all
  133. toolpath: List of paths to use for tools
  134. test_class_list: List of test classes to run
  135. """
  136. for module in []:
  137. suite = doctest.DocTestSuite(module)
  138. suite.run(result)
  139. sys.argv = [sys.argv[0]]
  140. if debug:
  141. sys.argv.append('-D')
  142. if verbosity:
  143. sys.argv.append('-v%d' % verbosity)
  144. if toolpath:
  145. for path in toolpath:
  146. sys.argv += ['--toolpath', path]
  147. suite = unittest.TestSuite()
  148. loader = unittest.TestLoader()
  149. for module in test_class_list:
  150. # Test the test module about our arguments, if it is interested
  151. if hasattr(module, 'setup_test_args'):
  152. setup_test_args = getattr(module, 'setup_test_args')
  153. setup_test_args(preserve_indir=test_preserve_dirs,
  154. preserve_outdirs=test_preserve_dirs and test_name is not None,
  155. toolpath=toolpath, verbosity=verbosity)
  156. if test_name:
  157. try:
  158. suite.addTests(loader.loadTestsFromName(test_name, module))
  159. except AttributeError:
  160. continue
  161. else:
  162. suite.addTests(loader.loadTestsFromTestCase(module))
  163. if use_concurrent and processes != 1:
  164. concurrent_suite = ConcurrentTestSuite(suite,
  165. fork_for_tests(processes or multiprocessing.cpu_count()))
  166. concurrent_suite.run(result)
  167. else:
  168. suite.run(result)