blob: 4835847bfc67e5d21d36a1f2deb2b26a0c4799d8 [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
Simon Glass66827cc2025-04-10 06:43:04 -060011import re
Simon Glass132be852018-07-06 10:27:23 -060012import sys
Simon Glass73306922020-04-17 18:09:01 -060013import unittest
Simon Glass132be852018-07-06 10:27:23 -060014
Simon Glass131444f2023-02-23 18:18:04 -070015from u_boot_pylib import command
Simon Glass132be852018-07-06 10:27:23 -060016
Simon Glass945328b2020-04-17 18:08:55 -060017from io import StringIO
Simon Glass3609d5e2018-07-06 10:27:34 -060018
Simon Glass73306922020-04-17 18:09:01 -060019use_concurrent = True
20try:
Simon Glassf715ab92023-02-23 18:18:03 -070021 from concurrencytest import ConcurrentTestSuite
22 from concurrencytest import fork_for_tests
Simon Glass73306922020-04-17 18:09:01 -060023except:
24 use_concurrent = False
25
Simon Glass3609d5e2018-07-06 10:27:34 -060026
Simon Glass0ce8fed2024-09-30 12:51:36 -060027def run_test_coverage(prog, filter_fname, exclude_list, build_dir,
28 required=None, extra_args=None, single_thread='-P1',
Simon Glass66827cc2025-04-10 06:43:04 -060029 args=None, allow_failures=None):
Simon Glass132be852018-07-06 10:27:23 -060030 """Run tests and check that we get 100% coverage
31
32 Args:
33 prog: Program to run (with be passed a '-t' argument to run tests
34 filter_fname: Normally all *.py files in the program's directory will
35 be included. If this is not None, then it is used to filter the
36 list so that only filenames that don't contain filter_fname are
37 included.
38 exclude_list: List of file patterns to exclude from the coverage
39 calculation
40 build_dir: Build directory, used to locate libfdt.py
41 required: List of modules which must be in the coverage report
Simon Glass5d5930d2020-07-09 18:39:29 -060042 extra_args (str): Extra arguments to pass to the tool before the -t/test
43 arg
Simon Glassc8b99b12023-07-19 17:49:31 -060044 single_thread (str): Argument string to make the tests run
45 single-threaded. This is necessary to get proper coverage results.
46 The default is '-P0'
Simon Glass0ce8fed2024-09-30 12:51:36 -060047 args (list of str): List of tests to run, or None to run all
Simon Glass132be852018-07-06 10:27:23 -060048
49 Raises:
50 ValueError if the code coverage is not 100%
51 """
52 # This uses the build output from sandbox_spl to get _libfdt.so
53 path = os.path.dirname(prog)
54 if filter_fname:
55 glob_list = glob.glob(os.path.join(path, '*.py'))
56 glob_list = [fname for fname in glob_list if filter_fname in fname]
57 else:
58 glob_list = []
59 glob_list += exclude_list
Simon Glass0eca03c2025-04-10 06:42:59 -060060 glob_list += ['*libfdt.py', '*/site-packages/*', '*/dist-packages/*']
Simon Glass6eb63c72020-07-09 18:39:34 -060061 glob_list += ['*concurrencytest*']
Simon Glass109e84e2020-07-05 21:41:55 -060062 test_cmd = 'test' if 'binman' in prog or 'patman' in prog else '-t'
Simon Glassf156e3b2020-04-17 18:09:00 -060063 prefix = ''
64 if build_dir:
65 prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir
Simon Glassbd75bea2024-06-23 11:56:21 -060066
67 # Detect a Python virtualenv and use 'coverage' instead
68 covtool = ('python3-coverage' if sys.prefix == sys.base_prefix else
69 'coverage')
70
71 cmd = ('%s%s run '
Simon Glass0ce8fed2024-09-30 12:51:36 -060072 '--omit "%s" %s %s %s %s %s' % (prefix, covtool, ','.join(glob_list),
73 prog, extra_args or '', test_cmd,
74 single_thread or '-P1',
75 ' '.join(args) if args else ''))
Simon Glass132be852018-07-06 10:27:23 -060076 os.system(cmd)
Simon Glassbd75bea2024-06-23 11:56:21 -060077 stdout = command.output(covtool, 'report')
Simon Glass132be852018-07-06 10:27:23 -060078 lines = stdout.splitlines()
79 if required:
80 # Convert '/path/to/name.py' just the module name 'name'
81 test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0]
82 for line in lines if '/etype/' in line])
83 missing_list = required
Simon Glass0baeab72019-07-08 14:25:32 -060084 missing_list.discard('__init__')
Simon Glass132be852018-07-06 10:27:23 -060085 missing_list.difference_update(test_set)
86 if missing_list:
Simon Glass23b8a192019-05-14 15:53:36 -060087 print('Missing tests for %s' % (', '.join(missing_list)))
88 print(stdout)
Simon Glass132be852018-07-06 10:27:23 -060089 ok = False
90
91 coverage = lines[-1].split(' ')[-1]
92 ok = True
Simon Glass23b8a192019-05-14 15:53:36 -060093 print(coverage)
Simon Glass132be852018-07-06 10:27:23 -060094 if coverage != '100%':
Simon Glass23b8a192019-05-14 15:53:36 -060095 print(stdout)
Simon Glass58816412022-08-13 11:40:41 -060096 print("To get a report in 'htmlcov/index.html', type: python3-coverage html")
Simon Glass23b8a192019-05-14 15:53:36 -060097 print('Coverage error: %s, but should be 100%%' % coverage)
Simon Glass132be852018-07-06 10:27:23 -060098 ok = False
99 if not ok:
Simon Glass66827cc2025-04-10 06:43:04 -0600100 if allow_failures:
101 # for line in lines:
102 # print('.', line, re.match(r'^(tools/.*py) *\d+ *(\d+) *(\d+)%$', line))
103 lines = [re.match(r'^(tools/.*py) *\d+ *(\d+) *\d+%$', line)
104 for line in stdout.splitlines()]
105 bad = []
106 for mat in lines:
107 if mat and mat.group(2) != '0':
108 fname = mat.group(1)
109 if fname not in allow_failures:
110 bad.append(fname)
111 if not bad:
112 return
Simon Glass132be852018-07-06 10:27:23 -0600113 raise ValueError('Test coverage failure')
Simon Glass3609d5e2018-07-06 10:27:34 -0600114
115
116# Use this to suppress stdout/stderr output:
117# with capture_sys_output() as (stdout, stderr)
118# ...do something...
119@contextmanager
120def capture_sys_output():
121 capture_out, capture_err = StringIO(), StringIO()
122 old_out, old_err = sys.stdout, sys.stderr
123 try:
124 sys.stdout, sys.stderr = capture_out, capture_err
125 yield capture_out, capture_err
126 finally:
127 sys.stdout, sys.stderr = old_out, old_err
Simon Glass73306922020-04-17 18:09:01 -0600128
129
Alper Nebi Yasakfedac7b2022-04-02 20:06:07 +0300130class FullTextTestResult(unittest.TextTestResult):
131 """A test result class that can print extended text results to a stream
132
133 This is meant to be used by a TestRunner as a result class. Like
134 TextTestResult, this prints out the names of tests as they are run,
135 errors as they occur, and a summary of the results at the end of the
136 test run. Beyond those, this prints information about skipped tests,
137 expected failures and unexpected successes.
138
139 Args:
140 stream: A file-like object to write results to
141 descriptions (bool): True to print descriptions with test names
142 verbosity (int): Detail of printed output per test as they run
143 Test stdout and stderr always get printed when buffering
144 them is disabled by the test runner. In addition to that,
145 0: Print nothing
146 1: Print a dot per test
147 2: Print test names
148 """
149 def __init__(self, stream, descriptions, verbosity):
150 self.verbosity = verbosity
151 super().__init__(stream, descriptions, verbosity)
152
153 def printErrors(self):
154 "Called by TestRunner after test run to summarize the tests"
155 # The parent class doesn't keep unexpected successes in the same
156 # format as the rest. Adapt it to what printErrorList expects.
157 unexpected_successes = [
158 (test, 'Test was expected to fail, but succeeded.\n')
159 for test in self.unexpectedSuccesses
160 ]
161
162 super().printErrors() # FAIL and ERROR
163 self.printErrorList('SKIP', self.skipped)
164 self.printErrorList('XFAIL', self.expectedFailures)
165 self.printErrorList('XPASS', unexpected_successes)
166
167 def addSkip(self, test, reason):
168 """Called when a test is skipped."""
169 # Add empty line to keep spacing consistent with other results
170 if not reason.endswith('\n'):
171 reason += '\n'
172 super().addSkip(test, reason)
173
174
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300175def run_test_suites(toolname, debug, verbosity, test_preserve_dirs, processes,
Simon Glass1b53d902022-01-29 14:14:14 -0700176 test_name, toolpath, class_and_module_list):
Simon Glass73306922020-04-17 18:09:01 -0600177 """Run a series of test suites and collect the results
178
179 Args:
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300180 toolname: Name of the tool that ran the tests
Simon Glass73306922020-04-17 18:09:01 -0600181 debug: True to enable debugging, which shows a full stack trace on error
182 verbosity: Verbosity level to use (0-4)
183 test_preserve_dirs: True to preserve the input directory used by tests
184 so that it can be examined afterwards (only useful for debugging
185 tests). If a single test is selected (in args[0]) it also preserves
186 the output directory for this test. Both directories are displayed
187 on the command line.
188 processes: Number of processes to use to run tests (None=same as #CPUs)
189 test_name: Name of test to run, or None for all
190 toolpath: List of paths to use for tools
Simon Glassc27d22d2022-01-22 05:07:28 -0700191 class_and_module_list: List of test classes (type class) and module
192 names (type str) to run
Simon Glass73306922020-04-17 18:09:01 -0600193 """
Simon Glass73306922020-04-17 18:09:01 -0600194 sys.argv = [sys.argv[0]]
195 if debug:
196 sys.argv.append('-D')
197 if verbosity:
198 sys.argv.append('-v%d' % verbosity)
199 if toolpath:
200 for path in toolpath:
201 sys.argv += ['--toolpath', path]
202
203 suite = unittest.TestSuite()
204 loader = unittest.TestLoader()
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300205 runner = unittest.TextTestRunner(
206 stream=sys.stdout,
207 verbosity=(1 if verbosity is None else verbosity),
Alper Nebi Yasakfedac7b2022-04-02 20:06:07 +0300208 resultclass=FullTextTestResult,
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300209 )
210
211 if use_concurrent and processes != 1:
212 suite = ConcurrentTestSuite(suite,
Simon Glass1ca554e2023-02-23 18:18:02 -0700213 fork_for_tests(processes or multiprocessing.cpu_count()))
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300214
215 for module in class_and_module_list:
216 if isinstance(module, str) and (not test_name or test_name == module):
217 suite.addTests(doctest.DocTestSuite(module))
218
Simon Glassc27d22d2022-01-22 05:07:28 -0700219 for module in class_and_module_list:
220 if isinstance(module, str):
221 continue
Simon Glass73306922020-04-17 18:09:01 -0600222 # Test the test module about our arguments, if it is interested
223 if hasattr(module, 'setup_test_args'):
224 setup_test_args = getattr(module, 'setup_test_args')
225 setup_test_args(preserve_indir=test_preserve_dirs,
226 preserve_outdirs=test_preserve_dirs and test_name is not None,
227 toolpath=toolpath, verbosity=verbosity)
228 if test_name:
Alper Nebi Yasak71e9a4c2022-04-02 20:06:05 +0300229 # Since Python v3.5 If an ImportError or AttributeError occurs
230 # while traversing a name then a synthetic test that raises that
231 # error when run will be returned. Check that the requested test
232 # exists, otherwise these errors are included in the results.
233 if test_name in loader.getTestCaseNames(module):
Simon Glass73306922020-04-17 18:09:01 -0600234 suite.addTests(loader.loadTestsFromName(test_name, module))
Simon Glass73306922020-04-17 18:09:01 -0600235 else:
236 suite.addTests(loader.loadTestsFromTestCase(module))
Alper Nebi Yasakca1c5882022-04-02 20:06:06 +0300237
238 print(f" Running {toolname} tests ".center(70, "="))
239 result = runner.run(suite)
240 print()
241
242 return result