blob: 857ce58c98cb41bf11db0661ff0c764d0deacd35 [file] [log] [blame]
Simon Glass132be852018-07-06 10:27:23 -06001# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright (c) 2016 Google, Inc
4#
5
Simon Glass3609d5e2018-07-06 10:27:34 -06006from contextlib import contextmanager
Simon Glassc27d22d2022-01-22 05:07:28 -07007import doctest
Simon Glass132be852018-07-06 10:27:23 -06008import glob
Simon Glass73306922020-04-17 18:09:01 -06009import multiprocessing
Simon Glass132be852018-07-06 10:27:23 -060010import os
11import sys
Simon Glass73306922020-04-17 18:09:01 -060012import unittest
Simon Glass132be852018-07-06 10:27:23 -060013
Simon Glass131444f2023-02-23 18:18:04 -070014from u_boot_pylib import command
Simon Glass132be852018-07-06 10:27:23 -060015
Simon Glass945328b2020-04-17 18:08:55 -060016from io import StringIO
Simon Glass3609d5e2018-07-06 10:27:34 -060017
Simon Glass73306922020-04-17 18:09:01 -060018use_concurrent = True
19try:
Simon Glassf715ab92023-02-23 18:18:03 -070020 from concurrencytest import ConcurrentTestSuite
21 from concurrencytest import fork_for_tests
Simon Glass73306922020-04-17 18:09:01 -060022except:
23 use_concurrent = False
24
Simon Glass3609d5e2018-07-06 10:27:34 -060025
Simon Glass1b53d902022-01-29 14:14:14 -070026def run_test_coverage(prog, filter_fname, exclude_list, build_dir, required=None,
Simon Glassc8b99b12023-07-19 17:49:31 -060027 extra_args=None, single_thread='-P1'):
Simon Glass132be852018-07-06 10:27:23 -060028 """Run tests and check that we get 100% coverage
29
30 Args:
31 prog: Program to run (with be passed a '-t' argument to run tests
32 filter_fname: Normally all *.py files in the program's directory will
33 be included. If this is not None, then it is used to filter the
34 list so that only filenames that don't contain filter_fname are
35 included.
36 exclude_list: List of file patterns to exclude from the coverage
37 calculation
38 build_dir: Build directory, used to locate libfdt.py
39 required: List of modules which must be in the coverage report
Simon Glass5d5930d2020-07-09 18:39:29 -060040 extra_args (str): Extra arguments to pass to the tool before the -t/test
41 arg
Simon Glassc8b99b12023-07-19 17:49:31 -060042 single_thread (str): Argument string to make the tests run
43 single-threaded. This is necessary to get proper coverage results.
44 The default is '-P0'
Simon Glass132be852018-07-06 10:27:23 -060045
46 Raises:
47 ValueError if the code coverage is not 100%
48 """
49 # This uses the build output from sandbox_spl to get _libfdt.so
50 path = os.path.dirname(prog)
51 if filter_fname:
52 glob_list = glob.glob(os.path.join(path, '*.py'))
53 glob_list = [fname for fname in glob_list if filter_fname in fname]
54 else:
55 glob_list = []
56 glob_list += exclude_list
Simon Glass102b21c2019-05-17 22:00:54 -060057 glob_list += ['*libfdt.py', '*site-packages*', '*dist-packages*']
Simon Glass6eb63c72020-07-09 18:39:34 -060058 glob_list += ['*concurrencytest*']
Simon Glass109e84e2020-07-05 21:41:55 -060059 test_cmd = 'test' if 'binman' in prog or 'patman' in prog else '-t'
Simon Glassf156e3b2020-04-17 18:09:00 -060060 prefix = ''
61 if build_dir:
62 prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir
Simon Glassbd75bea2024-06-23 11:56:21 -060063
64 # Detect a Python virtualenv and use 'coverage' instead
65 covtool = ('python3-coverage' if sys.prefix == sys.base_prefix else
66 'coverage')
67
68 cmd = ('%s%s run '
69 '--omit "%s" %s %s %s %s' % (prefix, covtool, ','.join(glob_list),
Simon Glassc8b99b12023-07-19 17:49:31 -060070 prog, extra_args or '', test_cmd,
71 single_thread or '-P1'))
Simon Glass132be852018-07-06 10:27:23 -060072 os.system(cmd)
Simon Glassbd75bea2024-06-23 11:56:21 -060073 stdout = command.output(covtool, 'report')
Simon Glass132be852018-07-06 10:27:23 -060074 lines = stdout.splitlines()
75 if required:
76 # Convert '/path/to/name.py' just the module name 'name'
77 test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0]
78 for line in lines if '/etype/' in line])
79 missing_list = required
Simon Glass0baeab72019-07-08 14:25:32 -060080 missing_list.discard('__init__')
Simon Glass132be852018-07-06 10:27:23 -060081 missing_list.difference_update(test_set)
82 if missing_list:
Simon Glass23b8a192019-05-14 15:53:36 -060083 print('Missing tests for %s' % (', '.join(missing_list)))
84 print(stdout)
Simon Glass132be852018-07-06 10:27:23 -060085 ok = False
86
87 coverage = lines[-1].split(' ')[-1]
88 ok = True
Simon Glass23b8a192019-05-14 15:53:36 -060089 print(coverage)
Simon Glass132be852018-07-06 10:27:23 -060090 if coverage != '100%':
Simon Glass23b8a192019-05-14 15:53:36 -060091 print(stdout)
Simon Glass58816412022-08-13 11:40:41 -060092 print("To get a report in 'htmlcov/index.html', type: python3-coverage html")
Simon Glass23b8a192019-05-14 15:53:36 -060093 print('Coverage error: %s, but should be 100%%' % coverage)
Simon Glass132be852018-07-06 10:27:23 -060094 ok = False
95 if not ok:
96 raise ValueError('Test coverage failure')
Simon Glass3609d5e2018-07-06 10:27:34 -060097
98
99# Use this to suppress stdout/stderr output:
100# with capture_sys_output() as (stdout, stderr)
101# ...do something...
102@contextmanager
103def capture_sys_output():
104 capture_out, capture_err = StringIO(), StringIO()
105 old_out, old_err = sys.stdout, sys.stderr
106 try:
107 sys.stdout, sys.stderr = capture_out, capture_err
108 yield capture_out, capture_err
109 finally:
110 sys.stdout, sys.stderr = old_out, old_err
Simon Glass73306922020-04-17 18:09:01 -0600111
112
Alper Nebi Yasakfedac7b2022-04-02 20:06:07 +0300113class FullTextTestResult(unittest.TextTestResult):
114 """A test result class that can print extended text results to a stream
115
116 This is meant to be used by a TestRunner as a result class. Like
117 TextTestResult, this prints out the names of tests as they are run,
118 errors as they occur, and a summary of the results at the end of the
119 test run. Beyond those, this prints information about skipped tests,
120 expected failures and unexpected successes.
121
122 Args:
123 stream: A file-like object to write results to
124 descriptions (bool): True to print descriptions with test names
125 verbosity (int): Detail of printed output per test as they run
126 Test stdout and stderr always get printed when buffering
127 them is disabled by the test runner. In addition to that,
128 0: Print nothing
129 1: Print a dot per test
130 2: Print test names
131 """
132 def __init__(self, stream, descriptions, verbosity):
133 self.verbosity = verbosity
134 super().__init__(stream, descriptions, verbosity)
135
136 def printErrors(self):
137 "Called by TestRunner after test run to summarize the tests"
138 # The parent class doesn't keep unexpected successes in the same
139 # format as the rest. Adapt it to what printErrorList expects.
140 unexpected_successes = [
141 (test, 'Test was expected to fail, but succeeded.\n')
142 for test in self.unexpectedSuccesses
143 ]
144
145 super().printErrors() # FAIL and ERROR
146 self.printErrorList('SKIP', self.skipped)
147 self.printErrorList('XFAIL', self.expectedFailures)
148 self.printErrorList('XPASS', unexpected_successes)
149
150 def addSkip(self, test, reason):
151 """Called when a test is skipped."""
152 # Add empty line to keep spacing consistent with other results
153 if not reason.endswith('\n'):
154 reason += '\n'
155 super().addSkip(test, reason)
156
157
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300158def run_test_suites(toolname, debug, verbosity, test_preserve_dirs, processes,
Simon Glass1b53d902022-01-29 14:14:14 -0700159 test_name, toolpath, class_and_module_list):
Simon Glass73306922020-04-17 18:09:01 -0600160 """Run a series of test suites and collect the results
161
162 Args:
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300163 toolname: Name of the tool that ran the tests
Simon Glass73306922020-04-17 18:09:01 -0600164 debug: True to enable debugging, which shows a full stack trace on error
165 verbosity: Verbosity level to use (0-4)
166 test_preserve_dirs: True to preserve the input directory used by tests
167 so that it can be examined afterwards (only useful for debugging
168 tests). If a single test is selected (in args[0]) it also preserves
169 the output directory for this test. Both directories are displayed
170 on the command line.
171 processes: Number of processes to use to run tests (None=same as #CPUs)
172 test_name: Name of test to run, or None for all
173 toolpath: List of paths to use for tools
Simon Glassc27d22d2022-01-22 05:07:28 -0700174 class_and_module_list: List of test classes (type class) and module
175 names (type str) to run
Simon Glass73306922020-04-17 18:09:01 -0600176 """
Simon Glass73306922020-04-17 18:09:01 -0600177 sys.argv = [sys.argv[0]]
178 if debug:
179 sys.argv.append('-D')
180 if verbosity:
181 sys.argv.append('-v%d' % verbosity)
182 if toolpath:
183 for path in toolpath:
184 sys.argv += ['--toolpath', path]
185
186 suite = unittest.TestSuite()
187 loader = unittest.TestLoader()
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300188 runner = unittest.TextTestRunner(
189 stream=sys.stdout,
190 verbosity=(1 if verbosity is None else verbosity),
Alper Nebi Yasakfedac7b2022-04-02 20:06:07 +0300191 resultclass=FullTextTestResult,
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300192 )
193
194 if use_concurrent and processes != 1:
195 suite = ConcurrentTestSuite(suite,
Simon Glass1ca554e2023-02-23 18:18:02 -0700196 fork_for_tests(processes or multiprocessing.cpu_count()))
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300197
198 for module in class_and_module_list:
199 if isinstance(module, str) and (not test_name or test_name == module):
200 suite.addTests(doctest.DocTestSuite(module))
201
Simon Glassc27d22d2022-01-22 05:07:28 -0700202 for module in class_and_module_list:
203 if isinstance(module, str):
204 continue
Simon Glass73306922020-04-17 18:09:01 -0600205 # Test the test module about our arguments, if it is interested
206 if hasattr(module, 'setup_test_args'):
207 setup_test_args = getattr(module, 'setup_test_args')
208 setup_test_args(preserve_indir=test_preserve_dirs,
209 preserve_outdirs=test_preserve_dirs and test_name is not None,
210 toolpath=toolpath, verbosity=verbosity)
211 if test_name:
Alper Nebi Yasak71e9a4c2022-04-02 20:06:05 +0300212 # Since Python v3.5 If an ImportError or AttributeError occurs
213 # while traversing a name then a synthetic test that raises that
214 # error when run will be returned. Check that the requested test
215 # exists, otherwise these errors are included in the results.
216 if test_name in loader.getTestCaseNames(module):
Simon Glass73306922020-04-17 18:09:01 -0600217 suite.addTests(loader.loadTestsFromName(test_name, module))
Simon Glass73306922020-04-17 18:09:01 -0600218 else:
219 suite.addTests(loader.loadTestsFromTestCase(module))
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300220
221 print(f" Running {toolname} tests ".center(70, "="))
222 result = runner.run(suite)
223 print()
224
225 return result