blob: ba8f87f75f03b9eda0aea74f00c40e20a15820f3 [file] [log] [blame]
Simon Glassff1fd6c2018-07-06 10:27:23 -06001# SPDX-License-Identifier: GPL-2.0+
2#
3# Copyright (c) 2016 Google, Inc
4#
5
Simon Glassc3f94542018-07-06 10:27:34 -06006from contextlib import contextmanager
Simon Glass1d0f30e2022-01-22 05:07:28 -07007import doctest
Simon Glassff1fd6c2018-07-06 10:27:23 -06008import glob
Simon Glassce0dc2e2020-04-17 18:09:01 -06009import multiprocessing
Simon Glassff1fd6c2018-07-06 10:27:23 -060010import os
11import sys
Simon Glassce0dc2e2020-04-17 18:09:01 -060012import unittest
Simon Glassff1fd6c2018-07-06 10:27:23 -060013
Simon Glassbf776672020-04-17 18:09:04 -060014from patman import command
Simon Glassff1fd6c2018-07-06 10:27:23 -060015
Simon Glassc3a13cc2020-04-17 18:08:55 -060016from io import StringIO
Simon Glassc3f94542018-07-06 10:27:34 -060017
Simon Glassce0dc2e2020-04-17 18:09:01 -060018use_concurrent = True
19try:
Simon Glass347e0f02020-07-09 18:39:34 -060020 from concurrencytest.concurrencytest import ConcurrentTestSuite
21 from concurrencytest.concurrencytest import fork_for_tests
Simon Glassce0dc2e2020-04-17 18:09:01 -060022except:
23 use_concurrent = False
24
Simon Glassc3f94542018-07-06 10:27:34 -060025
Simon Glass5e2ab402022-01-29 14:14:14 -070026def run_test_coverage(prog, filter_fname, exclude_list, build_dir, required=None,
Simon Glass32eb66d2020-07-09 18:39:29 -060027 extra_args=None):
Simon Glassff1fd6c2018-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 Glass32eb66d2020-07-09 18:39:29 -060040 extra_args (str): Extra arguments to pass to the tool before the -t/test
41 arg
Simon Glassff1fd6c2018-07-06 10:27:23 -060042
43 Raises:
44 ValueError if the code coverage is not 100%
45 """
46 # This uses the build output from sandbox_spl to get _libfdt.so
47 path = os.path.dirname(prog)
48 if filter_fname:
49 glob_list = glob.glob(os.path.join(path, '*.py'))
50 glob_list = [fname for fname in glob_list if filter_fname in fname]
51 else:
52 glob_list = []
53 glob_list += exclude_list
Simon Glass9550f9a2019-05-17 22:00:54 -060054 glob_list += ['*libfdt.py', '*site-packages*', '*dist-packages*']
Simon Glass347e0f02020-07-09 18:39:34 -060055 glob_list += ['*concurrencytest*']
Simon Glass6bb74de2020-07-05 21:41:55 -060056 test_cmd = 'test' if 'binman' in prog or 'patman' in prog else '-t'
Simon Glass428e7732020-04-17 18:09:00 -060057 prefix = ''
58 if build_dir:
59 prefix = 'PYTHONPATH=$PYTHONPATH:%s/sandbox_spl/tools ' % build_dir
60 cmd = ('%spython3-coverage run '
Simon Glass32eb66d2020-07-09 18:39:29 -060061 '--omit "%s" %s %s %s -P1' % (prefix, ','.join(glob_list),
62 prog, extra_args or '', test_cmd))
Simon Glassff1fd6c2018-07-06 10:27:23 -060063 os.system(cmd)
Simon Glassd9800692022-01-29 14:14:05 -070064 stdout = command.output('python3-coverage', 'report')
Simon Glassff1fd6c2018-07-06 10:27:23 -060065 lines = stdout.splitlines()
66 if required:
67 # Convert '/path/to/name.py' just the module name 'name'
68 test_set = set([os.path.splitext(os.path.basename(line.split()[0]))[0]
69 for line in lines if '/etype/' in line])
70 missing_list = required
Simon Glasse4304402019-07-08 14:25:32 -060071 missing_list.discard('__init__')
Simon Glassff1fd6c2018-07-06 10:27:23 -060072 missing_list.difference_update(test_set)
73 if missing_list:
Simon Glass5a1af1d2019-05-14 15:53:36 -060074 print('Missing tests for %s' % (', '.join(missing_list)))
75 print(stdout)
Simon Glassff1fd6c2018-07-06 10:27:23 -060076 ok = False
77
78 coverage = lines[-1].split(' ')[-1]
79 ok = True
Simon Glass5a1af1d2019-05-14 15:53:36 -060080 print(coverage)
Simon Glassff1fd6c2018-07-06 10:27:23 -060081 if coverage != '100%':
Simon Glass5a1af1d2019-05-14 15:53:36 -060082 print(stdout)
Simon Glass428e7732020-04-17 18:09:00 -060083 print("Type 'python3-coverage html' to get a report in "
84 'htmlcov/index.html')
Simon Glass5a1af1d2019-05-14 15:53:36 -060085 print('Coverage error: %s, but should be 100%%' % coverage)
Simon Glassff1fd6c2018-07-06 10:27:23 -060086 ok = False
87 if not ok:
88 raise ValueError('Test coverage failure')
Simon Glassc3f94542018-07-06 10:27:34 -060089
90
91# Use this to suppress stdout/stderr output:
92# with capture_sys_output() as (stdout, stderr)
93# ...do something...
94@contextmanager
95def capture_sys_output():
96 capture_out, capture_err = StringIO(), StringIO()
97 old_out, old_err = sys.stdout, sys.stderr
98 try:
99 sys.stdout, sys.stderr = capture_out, capture_err
100 yield capture_out, capture_err
101 finally:
102 sys.stdout, sys.stderr = old_out, old_err
Simon Glassce0dc2e2020-04-17 18:09:01 -0600103
104
Alper Nebi Yasakd8318fe2022-04-02 20:06:06 +0300105def run_test_suites(toolname, debug, verbosity, test_preserve_dirs, processes,
Simon Glass5e2ab402022-01-29 14:14:14 -0700106 test_name, toolpath, class_and_module_list):
Simon Glassce0dc2e2020-04-17 18:09:01 -0600107 """Run a series of test suites and collect the results
108
109 Args:
Alper Nebi Yasakd8318fe2022-04-02 20:06:06 +0300110 toolname: Name of the tool that ran the tests
Simon Glassce0dc2e2020-04-17 18:09:01 -0600111 debug: True to enable debugging, which shows a full stack trace on error
112 verbosity: Verbosity level to use (0-4)
113 test_preserve_dirs: True to preserve the input directory used by tests
114 so that it can be examined afterwards (only useful for debugging
115 tests). If a single test is selected (in args[0]) it also preserves
116 the output directory for this test. Both directories are displayed
117 on the command line.
118 processes: Number of processes to use to run tests (None=same as #CPUs)
119 test_name: Name of test to run, or None for all
120 toolpath: List of paths to use for tools
Simon Glass1d0f30e2022-01-22 05:07:28 -0700121 class_and_module_list: List of test classes (type class) and module
122 names (type str) to run
Simon Glassce0dc2e2020-04-17 18:09:01 -0600123 """
Simon Glassce0dc2e2020-04-17 18:09:01 -0600124 sys.argv = [sys.argv[0]]
125 if debug:
126 sys.argv.append('-D')
127 if verbosity:
128 sys.argv.append('-v%d' % verbosity)
129 if toolpath:
130 for path in toolpath:
131 sys.argv += ['--toolpath', path]
132
133 suite = unittest.TestSuite()
134 loader = unittest.TestLoader()
Alper Nebi Yasakd8318fe2022-04-02 20:06:06 +0300135 runner = unittest.TextTestRunner(
136 stream=sys.stdout,
137 verbosity=(1 if verbosity is None else verbosity),
138 )
139
140 if use_concurrent and processes != 1:
141 suite = ConcurrentTestSuite(suite,
142 fork_for_tests(processes or multiprocessing.cpu_count()))
143
144 for module in class_and_module_list:
145 if isinstance(module, str) and (not test_name or test_name == module):
146 suite.addTests(doctest.DocTestSuite(module))
147
Simon Glass1d0f30e2022-01-22 05:07:28 -0700148 for module in class_and_module_list:
149 if isinstance(module, str):
150 continue
Simon Glassce0dc2e2020-04-17 18:09:01 -0600151 # Test the test module about our arguments, if it is interested
152 if hasattr(module, 'setup_test_args'):
153 setup_test_args = getattr(module, 'setup_test_args')
154 setup_test_args(preserve_indir=test_preserve_dirs,
155 preserve_outdirs=test_preserve_dirs and test_name is not None,
156 toolpath=toolpath, verbosity=verbosity)
157 if test_name:
Alper Nebi Yasakce12c472022-04-02 20:06:05 +0300158 # Since Python v3.5 If an ImportError or AttributeError occurs
159 # while traversing a name then a synthetic test that raises that
160 # error when run will be returned. Check that the requested test
161 # exists, otherwise these errors are included in the results.
162 if test_name in loader.getTestCaseNames(module):
Simon Glassce0dc2e2020-04-17 18:09:01 -0600163 suite.addTests(loader.loadTestsFromName(test_name, module))
Simon Glassce0dc2e2020-04-17 18:09:01 -0600164 else:
165 suite.addTests(loader.loadTestsFromTestCase(module))
Alper Nebi Yasakd8318fe2022-04-02 20:06:06 +0300166
167 print(f" Running {toolname} tests ".center(70, "="))
168 result = runner.run(suite)
169 print()
170
171 return result