test_util.py 6.8 KB

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