blob: e59897c1f78f7283ecc110edef755ecf6873f194 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0
Stephen Warren10e50632016-01-15 11:15:24 -07002# Copyright (c) 2015 Stephen Warren
3# Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
Stephen Warren10e50632016-01-15 11:15:24 -07004
5# Implementation of pytest run-time hook functions. These are invoked by
6# pytest at certain points during operation, e.g. startup, for each executed
7# test, at shutdown etc. These hooks perform functions such as:
8# - Parsing custom command-line options.
9# - Pullilng in user-specified board configuration.
Simon Glassfb916372025-02-09 09:07:15 -070010# - Creating the ubman test fixture.
Stephen Warren10e50632016-01-15 11:15:24 -070011# - Creating the HTML log file.
12# - Monitoring each test's results.
13# - Implementing custom pytest markers.
14
15import atexit
Tom Rini6a990412019-10-24 11:59:21 -040016import configparser
Stephen Warren10e50632016-01-15 11:15:24 -070017import errno
Simon Glass62b92f82022-08-06 17:51:57 -060018import filelock
Tom Rini6a990412019-10-24 11:59:21 -040019import io
Stephen Warren10e50632016-01-15 11:15:24 -070020import os
21import os.path
Simon Glass62b92f82022-08-06 17:51:57 -060022from pathlib import Path
Stephen Warren10e50632016-01-15 11:15:24 -070023import pytest
Stephen Warren770fe172016-02-08 14:44:16 -070024import re
Tom Rini6a990412019-10-24 11:59:21 -040025from _pytest.runner import runtestprotocol
Simon Glassf6dbc362024-11-12 07:13:18 -070026import subprocess
Stephen Warren10e50632016-01-15 11:15:24 -070027import sys
Simon Glassfb916372025-02-09 09:07:15 -070028from spawn import BootFail, Timeout, Unexpected, handle_exception
Simon Glass1dffd532025-01-27 07:52:54 -070029import time
Stephen Warren10e50632016-01-15 11:15:24 -070030
Simon Glassfb916372025-02-09 09:07:15 -070031# Globals: The HTML log file, and the top-level fixture
Stephen Warren10e50632016-01-15 11:15:24 -070032log = None
Simon Glassfb916372025-02-09 09:07:15 -070033ubman_fix = None
Stephen Warren10e50632016-01-15 11:15:24 -070034
Simon Glass62b92f82022-08-06 17:51:57 -060035TEST_PY_DIR = os.path.dirname(os.path.abspath(__file__))
36
Simon Glassb15512c2025-01-20 14:25:32 -070037# Regex for test-function symbols
38RE_UT_TEST_LIST = re.compile(r'[^a-zA-Z0-9_]_u_boot_list_2_ut_(.*)_2_(.*)\s*$')
39
Stephen Warren10e50632016-01-15 11:15:24 -070040def mkdir_p(path):
Stephen Warren75e731e2016-01-26 13:41:30 -070041 """Create a directory path.
Stephen Warren10e50632016-01-15 11:15:24 -070042
43 This includes creating any intermediate/parent directories. Any errors
44 caused due to already extant directories are ignored.
45
46 Args:
47 path: The directory path to create.
48
49 Returns:
50 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070051 """
Stephen Warren10e50632016-01-15 11:15:24 -070052
53 try:
54 os.makedirs(path)
55 except OSError as exc:
56 if exc.errno == errno.EEXIST and os.path.isdir(path):
57 pass
58 else:
59 raise
60
61def pytest_addoption(parser):
Stephen Warren75e731e2016-01-26 13:41:30 -070062 """pytest hook: Add custom command-line options to the cmdline parser.
Stephen Warren10e50632016-01-15 11:15:24 -070063
64 Args:
65 parser: The pytest command-line parser.
66
67 Returns:
68 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070069 """
Stephen Warren10e50632016-01-15 11:15:24 -070070
71 parser.addoption('--build-dir', default=None,
72 help='U-Boot build directory (O=)')
Simon Glass5a63a4b2024-11-12 07:13:24 -070073 parser.addoption('--build-dir-extra', default=None,
74 help='U-Boot build directory for extra build (O=)')
Stephen Warren10e50632016-01-15 11:15:24 -070075 parser.addoption('--result-dir', default=None,
76 help='U-Boot test result/tmp directory')
77 parser.addoption('--persistent-data-dir', default=None,
78 help='U-Boot test persistent generated data directory')
79 parser.addoption('--board-type', '--bd', '-B', default='sandbox',
80 help='U-Boot board type')
Simon Glass5a63a4b2024-11-12 07:13:24 -070081 parser.addoption('--board-type-extra', '--bde', default='sandbox',
82 help='U-Boot extra board type')
Stephen Warren10e50632016-01-15 11:15:24 -070083 parser.addoption('--board-identity', '--id', default='na',
84 help='U-Boot board identity/instance')
85 parser.addoption('--build', default=False, action='store_true',
86 help='Compile U-Boot before running tests')
Simon Glass6e094842020-03-18 09:43:01 -060087 parser.addoption('--buildman', default=False, action='store_true',
88 help='Use buildman to build U-Boot (assuming --build is given)')
Stephen Warren33db1ee2016-02-04 16:11:50 -070089 parser.addoption('--gdbserver', default=None,
90 help='Run sandbox under gdbserver. The argument is the channel '+
91 'over which gdbserver should communicate, e.g. localhost:1234')
Simon Glassf6dbc362024-11-12 07:13:18 -070092 parser.addoption('--role', help='U-Boot board role (for Labgrid-sjg)')
Simon Glassf1b1bb82024-11-12 07:13:17 -070093 parser.addoption('--use-running-system', default=False, action='store_true',
94 help="Assume that U-Boot is ready and don't wait for a prompt")
Simon Glass1dffd532025-01-27 07:52:54 -070095 parser.addoption('--timing', default=False, action='store_true',
96 help='Show info on test timing')
97
Stephen Warren10e50632016-01-15 11:15:24 -070098
Simon Glass686fad72022-08-06 17:51:56 -060099def run_build(config, source_dir, build_dir, board_type, log):
100 """run_build: Build U-Boot
101
102 Args:
103 config: The pytest configuration.
104 soruce_dir (str): Directory containing source code
105 build_dir (str): Directory to build in
106 board_type (str): board_type parameter (e.g. 'sandbox')
107 log (Logfile): Log file to use
108 """
109 if config.getoption('buildman'):
110 if build_dir != source_dir:
111 dest_args = ['-o', build_dir, '-w']
112 else:
113 dest_args = ['-i']
114 cmds = (['buildman', '--board', board_type] + dest_args,)
115 name = 'buildman'
116 else:
117 if build_dir != source_dir:
118 o_opt = 'O=%s' % build_dir
119 else:
120 o_opt = ''
121 cmds = (
122 ['make', o_opt, '-s', board_type + '_defconfig'],
123 ['make', o_opt, '-s', '-j{}'.format(os.cpu_count())],
124 )
125 name = 'make'
126
127 with log.section(name):
128 runner = log.get_runner(name, sys.stdout)
129 for cmd in cmds:
130 runner.run(cmd, cwd=source_dir)
131 runner.close()
132 log.status_pass('OK')
133
Simon Glass35ad4322024-10-09 18:29:00 -0600134def get_details(config):
135 """Obtain salient details about the board and directories to use
136
137 Args:
138 config (pytest.Config): pytest configuration
139
140 Returns:
141 tuple:
142 str: Board type (U-Boot build name)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700143 str: Extra board type (where two U-Boot builds are needed)
Simon Glass35ad4322024-10-09 18:29:00 -0600144 str: Identity for the lab board
145 str: Build directory
Simon Glass5a63a4b2024-11-12 07:13:24 -0700146 str: Extra build directory (where two U-Boot builds are needed)
Simon Glass35ad4322024-10-09 18:29:00 -0600147 str: Source directory
148 """
Simon Glassf6dbc362024-11-12 07:13:18 -0700149 role = config.getoption('role')
150
151 # Get a few provided parameters
Simon Glass35ad4322024-10-09 18:29:00 -0600152 build_dir = config.getoption('build_dir')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700153 build_dir_extra = config.getoption('build_dir_extra')
Simon Glass068f6a72024-12-11 06:18:58 -0700154
155 # The source tree must be the current directory
156 source_dir = os.path.dirname(os.path.dirname(TEST_PY_DIR))
Simon Glassf6dbc362024-11-12 07:13:18 -0700157 if role:
158 # When using a role, build_dir and build_dir_extra are normally not set,
159 # since they are picked up from Labgrid-sjg via the u-boot-test-getrole
160 # script
161 board_identity = role
162 cmd = ['u-boot-test-getrole', role, '--configure']
163 env = os.environ.copy()
164 if build_dir:
165 env['U_BOOT_BUILD_DIR'] = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700166 if build_dir_extra:
167 env['U_BOOT_BUILD_DIR_EXTRA'] = build_dir_extra
Simon Glass97fb3452024-12-14 11:20:20 -0700168
169 # Make sure the script sees that it is being run from pytest
170 env['U_BOOT_SOURCE_DIR'] = source_dir
171
Simon Glass2873ca252024-12-14 11:20:21 -0700172 proc = subprocess.run(cmd, stdout=subprocess.PIPE,
173 stderr=subprocess.STDOUT, encoding='utf-8',
Simon Glassf6dbc362024-11-12 07:13:18 -0700174 env=env)
175 if proc.returncode:
Simon Glass2873ca252024-12-14 11:20:21 -0700176 raise ValueError(f"Error {proc.returncode} running {cmd}: '{proc.stderr} '{proc.stdout}'")
Simon Glassf6dbc362024-11-12 07:13:18 -0700177 # For debugging
178 # print('conftest: lab:', proc.stdout)
179 vals = {}
180 for line in proc.stdout.splitlines():
181 item, value = line.split(' ', maxsplit=1)
182 k = item.split(':')[-1]
183 vals[k] = value
184 # For debugging
185 # print('conftest: lab info:', vals)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700186
187 # Read the build directories here, in case none were provided in the
188 # command-line arguments
189 (board_type, board_type_extra, default_build_dir,
Simon Glass068f6a72024-12-11 06:18:58 -0700190 default_build_dir_extra) = (vals['board'],
191 vals['board_extra'], vals['build_dir'], vals['build_dir_extra'])
Simon Glassf6dbc362024-11-12 07:13:18 -0700192 else:
193 board_type = config.getoption('board_type')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700194 board_type_extra = config.getoption('board_type_extra')
Simon Glassf6dbc362024-11-12 07:13:18 -0700195 board_identity = config.getoption('board_identity')
Simon Glass35ad4322024-10-09 18:29:00 -0600196
Simon Glassf6dbc362024-11-12 07:13:18 -0700197 default_build_dir = source_dir + '/build-' + board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700198 default_build_dir_extra = source_dir + '/build-' + board_type_extra
199
200 # Use the provided command-line arguments if present, else fall back to
Simon Glass62b92f82022-08-06 17:51:57 -0600201 if not build_dir:
Simon Glass35ad4322024-10-09 18:29:00 -0600202 build_dir = default_build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700203 if not build_dir_extra:
204 build_dir_extra = default_build_dir_extra
Simon Glass35ad4322024-10-09 18:29:00 -0600205
Simon Glass5a63a4b2024-11-12 07:13:24 -0700206 return (board_type, board_type_extra, board_identity, build_dir,
207 build_dir_extra, source_dir)
Simon Glass35ad4322024-10-09 18:29:00 -0600208
209def pytest_xdist_setupnodes(config, specs):
210 """Clear out any 'done' file from a previous build"""
211 global build_done_file
212
Simon Glass5a63a4b2024-11-12 07:13:24 -0700213 build_dir = get_details(config)[3]
Simon Glass35ad4322024-10-09 18:29:00 -0600214
Simon Glass62b92f82022-08-06 17:51:57 -0600215 build_done_file = Path(build_dir) / 'build.done'
216 if build_done_file.exists():
217 os.remove(build_done_file)
218
Stephen Warren10e50632016-01-15 11:15:24 -0700219def pytest_configure(config):
Stephen Warren75e731e2016-01-26 13:41:30 -0700220 """pytest hook: Perform custom initialization at startup time.
Stephen Warren10e50632016-01-15 11:15:24 -0700221
222 Args:
223 config: The pytest configuration.
224
225 Returns:
226 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700227 """
Simon Glassde8e25b2019-12-01 19:34:18 -0700228 def parse_config(conf_file):
229 """Parse a config file, loading it into the ubconfig container
230
231 Args:
232 conf_file: Filename to load (within build_dir)
233
234 Raises
235 Exception if the file does not exist
236 """
237 dot_config = build_dir + '/' + conf_file
238 if not os.path.exists(dot_config):
239 raise Exception(conf_file + ' does not exist; ' +
240 'try passing --build option?')
241
242 with open(dot_config, 'rt') as f:
243 ini_str = '[root]\n' + f.read()
244 ini_sio = io.StringIO(ini_str)
245 parser = configparser.RawConfigParser()
246 parser.read_file(ini_sio)
247 ubconfig.buildconfig.update(parser.items('root'))
Stephen Warren10e50632016-01-15 11:15:24 -0700248
249 global log
Simon Glassfb916372025-02-09 09:07:15 -0700250 global ubman_fix
Stephen Warren10e50632016-01-15 11:15:24 -0700251 global ubconfig
252
Simon Glass5a63a4b2024-11-12 07:13:24 -0700253 (board_type, board_type_extra, board_identity, build_dir, build_dir_extra,
254 source_dir) = get_details(config)
Stephen Warren10e50632016-01-15 11:15:24 -0700255
Stephen Warren10e50632016-01-15 11:15:24 -0700256 board_type_filename = board_type.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700257 board_identity_filename = board_identity.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700258 mkdir_p(build_dir)
259
260 result_dir = config.getoption('result_dir')
261 if not result_dir:
262 result_dir = build_dir
263 mkdir_p(result_dir)
264
265 persistent_data_dir = config.getoption('persistent_data_dir')
266 if not persistent_data_dir:
267 persistent_data_dir = build_dir + '/persistent-data'
268 mkdir_p(persistent_data_dir)
269
Stephen Warren33db1ee2016-02-04 16:11:50 -0700270 gdbserver = config.getoption('gdbserver')
Igor Opaniukea5f17d2019-02-12 16:18:14 +0200271 if gdbserver and not board_type.startswith('sandbox'):
272 raise Exception('--gdbserver only supported with sandbox targets')
Stephen Warren33db1ee2016-02-04 16:11:50 -0700273
Stephen Warren10e50632016-01-15 11:15:24 -0700274 import multiplexed_log
275 log = multiplexed_log.Logfile(result_dir + '/test-log.html')
276
277 if config.getoption('build'):
Simon Glass62b92f82022-08-06 17:51:57 -0600278 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
279 with filelock.FileLock(os.path.join(build_dir, 'build.lock')):
280 build_done_file = Path(build_dir) / 'build.done'
281 if (not worker_id or worker_id == 'master' or
282 not build_done_file.exists()):
283 run_build(config, source_dir, build_dir, board_type, log)
284 build_done_file.touch()
Stephen Warren10e50632016-01-15 11:15:24 -0700285
286 class ArbitraryAttributeContainer(object):
287 pass
288
289 ubconfig = ArbitraryAttributeContainer()
290 ubconfig.brd = dict()
291 ubconfig.env = dict()
Simon Glass20202472025-02-09 09:07:18 -0700292 not_found = []
293
294 with log.section('Loading lab modules', 'load_modules'):
295 modules = [
296 (ubconfig.brd, 'u_boot_board_' + board_type_filename),
297 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
298 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
299 board_identity_filename),
300 ]
301 for (dict_to_fill, module_name) in modules:
302 try:
303 module = __import__(module_name)
304 except ImportError:
305 not_found.append(module_name)
306 continue
307 dict_to_fill.update(module.__dict__)
308 log.info(f"Loaded {module}")
Stephen Warren10e50632016-01-15 11:15:24 -0700309
Simon Glass20202472025-02-09 09:07:18 -0700310 if not_found:
311 log.warning(f"Failed to find modules: {' '.join(not_found)}")
Stephen Warren10e50632016-01-15 11:15:24 -0700312
313 ubconfig.buildconfig = dict()
314
Simon Glassde8e25b2019-12-01 19:34:18 -0700315 # buildman -k puts autoconf.mk in the rootdir, so handle this as well
316 # as the standard U-Boot build which leaves it in include/autoconf.mk
317 parse_config('.config')
318 if os.path.exists(build_dir + '/' + 'autoconf.mk'):
319 parse_config('autoconf.mk')
320 else:
321 parse_config('include/autoconf.mk')
Stephen Warren10e50632016-01-15 11:15:24 -0700322
Simon Glass62b92f82022-08-06 17:51:57 -0600323 ubconfig.test_py_dir = TEST_PY_DIR
Stephen Warren10e50632016-01-15 11:15:24 -0700324 ubconfig.source_dir = source_dir
325 ubconfig.build_dir = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700326 ubconfig.build_dir_extra = build_dir_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700327 ubconfig.result_dir = result_dir
328 ubconfig.persistent_data_dir = persistent_data_dir
329 ubconfig.board_type = board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700330 ubconfig.board_type_extra = board_type_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700331 ubconfig.board_identity = board_identity
Stephen Warren33db1ee2016-02-04 16:11:50 -0700332 ubconfig.gdbserver = gdbserver
Simon Glassf1b1bb82024-11-12 07:13:17 -0700333 ubconfig.use_running_system = config.getoption('use_running_system')
Simon Glass3b097872016-07-03 09:40:36 -0600334 ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
Simon Glassd834d9a2024-10-09 18:29:03 -0600335 ubconfig.connection_ok = True
Simon Glass1dffd532025-01-27 07:52:54 -0700336 ubconfig.timing = config.getoption('timing')
Stephen Warren10e50632016-01-15 11:15:24 -0700337
338 env_vars = (
339 'board_type',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700340 'board_type_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700341 'board_identity',
342 'source_dir',
343 'test_py_dir',
344 'build_dir',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700345 'build_dir_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700346 'result_dir',
347 'persistent_data_dir',
348 )
349 for v in env_vars:
350 os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
351
Simon Glass13f422e2016-07-04 11:58:37 -0600352 if board_type.startswith('sandbox'):
Simon Glassfb916372025-02-09 09:07:15 -0700353 import console_sandbox
354 ubman_fix = console_sandbox.ConsoleSandbox(log, ubconfig)
Stephen Warren10e50632016-01-15 11:15:24 -0700355 else:
Simon Glassfb916372025-02-09 09:07:15 -0700356 import console_board
357 ubman_fix = console_board.ConsoleExecAttach(log, ubconfig)
Stephen Warren10e50632016-01-15 11:15:24 -0700358
Simon Glassb15512c2025-01-20 14:25:32 -0700359
Simon Glassed298be2020-10-25 20:38:31 -0600360def generate_ut_subtest(metafunc, fixture_name, sym_path):
Stephen Warren770fe172016-02-08 14:44:16 -0700361 """Provide parametrization for a ut_subtest fixture.
362
363 Determines the set of unit tests built into a U-Boot binary by parsing the
364 list of symbols generated by the build process. Provides this information
365 to test functions by parameterizing their ut_subtest fixture parameter.
366
367 Args:
368 metafunc: The pytest test function.
369 fixture_name: The fixture name to test.
Simon Glassed298be2020-10-25 20:38:31 -0600370 sym_path: Relative path to the symbol file with preceding '/'
371 (e.g. '/u-boot.sym')
Stephen Warren770fe172016-02-08 14:44:16 -0700372
373 Returns:
374 Nothing.
375 """
Simon Glassfb916372025-02-09 09:07:15 -0700376 fn = ubman_fix.config.build_dir + sym_path
Stephen Warren770fe172016-02-08 14:44:16 -0700377 try:
378 with open(fn, 'rt') as f:
379 lines = f.readlines()
380 except:
381 lines = []
382 lines.sort()
383
384 vals = []
385 for l in lines:
Simon Glassb15512c2025-01-20 14:25:32 -0700386 m = RE_UT_TEST_LIST.search(l)
Stephen Warren770fe172016-02-08 14:44:16 -0700387 if not m:
388 continue
Simon Glass1f1614b2022-10-20 18:22:50 -0600389 suite, name = m.groups()
390
391 # Tests marked with _norun should only be run manually using 'ut -f'
392 if name.endswith('_norun'):
393 continue
394
395 vals.append(f'{suite} {name}')
Stephen Warren770fe172016-02-08 14:44:16 -0700396
397 ids = ['ut_' + s.replace(' ', '_') for s in vals]
398 metafunc.parametrize(fixture_name, vals, ids=ids)
399
400def generate_config(metafunc, fixture_name):
401 """Provide parametrization for {env,brd}__ fixtures.
Stephen Warren10e50632016-01-15 11:15:24 -0700402
403 If a test function takes parameter(s) (fixture names) of the form brd__xxx
404 or env__xxx, the brd and env configuration dictionaries are consulted to
405 find the list of values to use for those parameters, and the test is
406 parametrized so that it runs once for each combination of values.
407
408 Args:
409 metafunc: The pytest test function.
Stephen Warren770fe172016-02-08 14:44:16 -0700410 fixture_name: The fixture name to test.
Stephen Warren10e50632016-01-15 11:15:24 -0700411
412 Returns:
413 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700414 """
Stephen Warren10e50632016-01-15 11:15:24 -0700415
416 subconfigs = {
Simon Glassfb916372025-02-09 09:07:15 -0700417 'brd': ubman_fix.config.brd,
418 'env': ubman_fix.config.env,
Stephen Warren10e50632016-01-15 11:15:24 -0700419 }
Stephen Warren770fe172016-02-08 14:44:16 -0700420 parts = fixture_name.split('__')
421 if len(parts) < 2:
422 return
423 if parts[0] not in subconfigs:
424 return
425 subconfig = subconfigs[parts[0]]
426 vals = []
427 val = subconfig.get(fixture_name, [])
428 # If that exact name is a key in the data source:
429 if val:
430 # ... use the dict value as a single parameter value.
431 vals = (val, )
432 else:
433 # ... otherwise, see if there's a key that contains a list of
434 # values to use instead.
435 vals = subconfig.get(fixture_name+ 's', [])
436 def fixture_id(index, val):
437 try:
438 return val['fixture_id']
439 except:
440 return fixture_name + str(index)
441 ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
442 metafunc.parametrize(fixture_name, vals, ids=ids)
443
444def pytest_generate_tests(metafunc):
445 """pytest hook: parameterize test functions based on custom rules.
446
447 Check each test function parameter (fixture name) to see if it is one of
448 our custom names, and if so, provide the correct parametrization for that
449 parameter.
450
451 Args:
452 metafunc: The pytest test function.
453
454 Returns:
455 Nothing.
456 """
Stephen Warren10e50632016-01-15 11:15:24 -0700457 for fn in metafunc.fixturenames:
Stephen Warren770fe172016-02-08 14:44:16 -0700458 if fn == 'ut_subtest':
Simon Glassed298be2020-10-25 20:38:31 -0600459 generate_ut_subtest(metafunc, fn, '/u-boot.sym')
460 continue
Simon Glassb6c665f2022-04-30 00:56:55 -0600461 m_subtest = re.match('ut_(.)pl_subtest', fn)
462 if m_subtest:
463 spl_name = m_subtest.group(1)
464 generate_ut_subtest(
465 metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
Stephen Warren10e50632016-01-15 11:15:24 -0700466 continue
Stephen Warren770fe172016-02-08 14:44:16 -0700467 generate_config(metafunc, fn)
Stephen Warren10e50632016-01-15 11:15:24 -0700468
Stefan Brüns364ea872016-11-05 17:45:32 +0100469@pytest.fixture(scope='session')
470def u_boot_log(request):
471 """Generate the value of a test's log fixture.
472
473 Args:
474 request: The pytest request.
475
476 Returns:
477 The fixture value.
478 """
479
Simon Glassfb916372025-02-09 09:07:15 -0700480 return ubman_fix.log
Stefan Brüns364ea872016-11-05 17:45:32 +0100481
482@pytest.fixture(scope='session')
483def u_boot_config(request):
484 """Generate the value of a test's u_boot_config fixture.
485
486 Args:
487 request: The pytest request.
488
489 Returns:
490 The fixture value.
491 """
492
Simon Glassfb916372025-02-09 09:07:15 -0700493 return ubman_fix.config
Stefan Brüns364ea872016-11-05 17:45:32 +0100494
Stephen Warrene1d24d02016-01-22 12:30:08 -0700495@pytest.fixture(scope='function')
Simon Glassddba5202025-02-09 09:07:14 -0700496def ubman(request):
497 """Generate the value of a test's ubman fixture.
Stephen Warren10e50632016-01-15 11:15:24 -0700498
499 Args:
500 request: The pytest request.
501
502 Returns:
503 The fixture value.
Stephen Warren75e731e2016-01-26 13:41:30 -0700504 """
Simon Glassd834d9a2024-10-09 18:29:03 -0600505 if not ubconfig.connection_ok:
506 pytest.skip('Cannot get target connection')
507 return None
508 try:
Simon Glassfb916372025-02-09 09:07:15 -0700509 ubman_fix.ensure_spawned()
Simon Glassd834d9a2024-10-09 18:29:03 -0600510 except OSError as err:
Simon Glassfb916372025-02-09 09:07:15 -0700511 handle_exception(ubconfig, ubman_fix, log, err, 'Lab failure', True)
Simon Glassd834d9a2024-10-09 18:29:03 -0600512 except Timeout as err:
Simon Glassfb916372025-02-09 09:07:15 -0700513 handle_exception(ubconfig, ubman_fix, log, err, 'Lab timeout', True)
Simon Glassd834d9a2024-10-09 18:29:03 -0600514 except BootFail as err:
Simon Glassfb916372025-02-09 09:07:15 -0700515 handle_exception(ubconfig, ubman_fix, log, err, 'Boot fail', True,
516 ubman.get_spawn_output())
Simon Glassd834d9a2024-10-09 18:29:03 -0600517 except Unexpected:
Simon Glassfb916372025-02-09 09:07:15 -0700518 handle_exception(ubconfig, ubman_fix, log, err, 'Unexpected test output',
Simon Glassd834d9a2024-10-09 18:29:03 -0600519 False)
Simon Glassfb916372025-02-09 09:07:15 -0700520 return ubman_fix
Stephen Warren10e50632016-01-15 11:15:24 -0700521
Stephen Warrene3f2a502016-02-03 16:46:34 -0700522anchors = {}
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700523tests_not_run = []
524tests_failed = []
525tests_xpassed = []
526tests_xfailed = []
527tests_skipped = []
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700528tests_warning = []
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700529tests_passed = []
Stephen Warren10e50632016-01-15 11:15:24 -0700530
Simon Glass1dffd532025-01-27 07:52:54 -0700531# Duration of each test:
532# key (string): test name
533# value (float): duration in ms
534test_durations = {}
535
536
Stephen Warren10e50632016-01-15 11:15:24 -0700537def pytest_itemcollected(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700538 """pytest hook: Called once for each test found during collection.
Stephen Warren10e50632016-01-15 11:15:24 -0700539
540 This enables our custom result analysis code to see the list of all tests
541 that should eventually be run.
542
543 Args:
544 item: The item that was collected.
545
546 Returns:
547 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700548 """
Stephen Warren10e50632016-01-15 11:15:24 -0700549
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700550 tests_not_run.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700551
Simon Glass1dffd532025-01-27 07:52:54 -0700552
553def show_timings():
554 """Write timings for each test, along with a histogram"""
555
556 def get_time_delta(msecs):
557 """Convert milliseconds into a user-friendly string"""
558 if msecs >= 1000:
559 return f'{msecs / 1000:.1f}s'
560 else:
561 return f'{msecs:.0f}ms'
562
563 def show_bar(key, msecs, value):
564 """Show a single bar (line) of the histogram
565
566 Args:
567 key (str): Key to write on the left
568 value (int): Value to display, i.e. the relative length of the bar
569 """
570 if value:
571 bar_length = int((value / max_count) * max_bar_length)
572 print(f"{key:>8} : {get_time_delta(msecs):>7} |{'#' * bar_length} {value}", file=buf)
573
574 # Create the buckets we will use, each has a count and a total time
575 bucket = {}
576 for power in range(5):
577 for i in [1, 2, 3, 4, 5, 7.5]:
578 bucket[i * 10 ** power] = {'count': 0, 'msecs': 0.0}
579 max_dur = max(bucket.keys())
580
581 # Collect counts for each bucket; if outside the range, add to too_long
582 # Also show a sorted list of test timings from longest to shortest
583 too_long = 0
584 too_long_msecs = 0.0
585 max_count = 0
586 with log.section('Timing Report', 'timing_report'):
587 for name, dur in sorted(test_durations.items(), key=lambda kv: kv[1],
588 reverse=True):
589 log.info(f'{get_time_delta(dur):>8} {name}')
590 greater = [k for k in bucket.keys() if dur <= k]
591 if greater:
592 buck = bucket[min(greater)]
593 buck['count'] += 1
594 max_count = max(max_count, buck['count'])
595 buck['msecs'] += dur
596 else:
597 too_long += 1
598 too_long_msecs += dur
599
600 # Set the maximum length of a histogram bar, in characters
601 max_bar_length = 40
602
603 # Show a a summary with histogram
604 buf = io.StringIO()
605 with log.section('Timing Summary', 'timing_summary'):
606 print('Duration : Total | Number of tests', file=buf)
607 print(f'{"=" * 8} : {"=" * 7} |{"=" * max_bar_length}', file=buf)
608 for dur, buck in bucket.items():
609 if buck['count']:
610 label = get_time_delta(dur)
611 show_bar(f'<{label}', buck['msecs'], buck['count'])
612 if too_long:
613 show_bar(f'>{get_time_delta(max_dur)}', too_long_msecs, too_long)
614 log.info(buf.getvalue())
615 if ubconfig.timing:
616 print(buf.getvalue(), end='')
617
618
Stephen Warren10e50632016-01-15 11:15:24 -0700619def cleanup():
Stephen Warren75e731e2016-01-26 13:41:30 -0700620 """Clean up all global state.
Stephen Warren10e50632016-01-15 11:15:24 -0700621
622 Executed (via atexit) once the entire test process is complete. This
623 includes logging the status of all tests, and the identity of any failed
624 or skipped tests.
625
626 Args:
627 None.
628
629 Returns:
630 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700631 """
Stephen Warren10e50632016-01-15 11:15:24 -0700632
Simon Glassfb916372025-02-09 09:07:15 -0700633 if ubman_fix:
634 ubman_fix.close()
Stephen Warren10e50632016-01-15 11:15:24 -0700635 if log:
Stephen Warrene3f2a502016-02-03 16:46:34 -0700636 with log.section('Status Report', 'status_report'):
637 log.status_pass('%d passed' % len(tests_passed))
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700638 if tests_warning:
639 log.status_warning('%d passed with warning' % len(tests_warning))
640 for test in tests_warning:
641 anchor = anchors.get(test, None)
642 log.status_warning('... ' + test, anchor)
Stephen Warrene3f2a502016-02-03 16:46:34 -0700643 if tests_skipped:
644 log.status_skipped('%d skipped' % len(tests_skipped))
645 for test in tests_skipped:
646 anchor = anchors.get(test, None)
647 log.status_skipped('... ' + test, anchor)
648 if tests_xpassed:
649 log.status_xpass('%d xpass' % len(tests_xpassed))
650 for test in tests_xpassed:
651 anchor = anchors.get(test, None)
652 log.status_xpass('... ' + test, anchor)
653 if tests_xfailed:
654 log.status_xfail('%d xfail' % len(tests_xfailed))
655 for test in tests_xfailed:
656 anchor = anchors.get(test, None)
657 log.status_xfail('... ' + test, anchor)
658 if tests_failed:
659 log.status_fail('%d failed' % len(tests_failed))
660 for test in tests_failed:
661 anchor = anchors.get(test, None)
662 log.status_fail('... ' + test, anchor)
663 if tests_not_run:
664 log.status_fail('%d not run' % len(tests_not_run))
665 for test in tests_not_run:
666 anchor = anchors.get(test, None)
667 log.status_fail('... ' + test, anchor)
Simon Glass1dffd532025-01-27 07:52:54 -0700668 show_timings()
Stephen Warren10e50632016-01-15 11:15:24 -0700669 log.close()
670atexit.register(cleanup)
671
672def setup_boardspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700673 """Process any 'boardspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700674
675 Such a marker lists the set of board types that a test does/doesn't
676 support. If tests are being executed on an unsupported board, the test is
677 marked to be skipped.
678
679 Args:
680 item: The pytest test item.
681
682 Returns:
683 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700684 """
Stephen Warren10e50632016-01-15 11:15:24 -0700685
Stephen Warren10e50632016-01-15 11:15:24 -0700686 required_boards = []
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400687 for boards in item.iter_markers('boardspec'):
688 board = boards.args[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700689 if board.startswith('!'):
690 if ubconfig.board_type == board[1:]:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600691 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700692 return
693 else:
694 required_boards.append(board)
695 if required_boards and ubconfig.board_type not in required_boards:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600696 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700697
698def setup_buildconfigspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700699 """Process any 'buildconfigspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700700
701 Such a marker lists some U-Boot configuration feature that the test
702 requires. If tests are being executed on an U-Boot build that doesn't
703 have the required feature, the test is marked to be skipped.
704
705 Args:
706 item: The pytest test item.
707
708 Returns:
709 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700710 """
Stephen Warren10e50632016-01-15 11:15:24 -0700711
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400712 for options in item.iter_markers('buildconfigspec'):
713 option = options.args[0]
714 if not ubconfig.buildconfig.get('config_' + option.lower(), None):
715 pytest.skip('.config feature "%s" not enabled' % option.lower())
Cristian Ciocaltea6c6c8072019-12-24 17:19:12 +0200716 for options in item.iter_markers('notbuildconfigspec'):
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400717 option = options.args[0]
718 if ubconfig.buildconfig.get('config_' + option.lower(), None):
719 pytest.skip('.config feature "%s" enabled' % option.lower())
Stephen Warren10e50632016-01-15 11:15:24 -0700720
Stephen Warren2079db32017-09-18 11:11:49 -0600721def tool_is_in_path(tool):
722 for path in os.environ["PATH"].split(os.pathsep):
723 fn = os.path.join(path, tool)
724 if os.path.isfile(fn) and os.access(fn, os.X_OK):
725 return True
726 return False
727
728def setup_requiredtool(item):
729 """Process any 'requiredtool' marker for a test.
730
731 Such a marker lists some external tool (binary, executable, application)
732 that the test requires. If tests are being executed on a system that
733 doesn't have the required tool, the test is marked to be skipped.
734
735 Args:
736 item: The pytest test item.
737
738 Returns:
739 Nothing.
740 """
741
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400742 for tools in item.iter_markers('requiredtool'):
743 tool = tools.args[0]
Stephen Warren2079db32017-09-18 11:11:49 -0600744 if not tool_is_in_path(tool):
745 pytest.skip('tool "%s" not in $PATH' % tool)
746
Simon Glass54ef2ca2022-08-06 17:51:47 -0600747def setup_singlethread(item):
748 """Process any 'singlethread' marker for a test.
749
750 Skip this test if running in parallel.
751
752 Args:
753 item: The pytest test item.
754
755 Returns:
756 Nothing.
757 """
758 for single in item.iter_markers('singlethread'):
759 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
760 if worker_id and worker_id != 'master':
761 pytest.skip('must run single-threaded')
762
Stephen Warren3e3d1432016-10-17 17:25:52 -0600763def start_test_section(item):
764 anchors[item.name] = log.start_section(item.name)
765
Stephen Warren10e50632016-01-15 11:15:24 -0700766def pytest_runtest_setup(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700767 """pytest hook: Configure (set up) a test item.
Stephen Warren10e50632016-01-15 11:15:24 -0700768
769 Called once for each test to perform any custom configuration. This hook
770 is used to skip the test if certain conditions apply.
771
772 Args:
773 item: The pytest test item.
774
775 Returns:
776 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700777 """
Stephen Warren10e50632016-01-15 11:15:24 -0700778
Stephen Warren3e3d1432016-10-17 17:25:52 -0600779 start_test_section(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700780 setup_boardspec(item)
781 setup_buildconfigspec(item)
Stephen Warren2079db32017-09-18 11:11:49 -0600782 setup_requiredtool(item)
Simon Glass54ef2ca2022-08-06 17:51:47 -0600783 setup_singlethread(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700784
785def pytest_runtest_protocol(item, nextitem):
Stephen Warren75e731e2016-01-26 13:41:30 -0700786 """pytest hook: Called to execute a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700787
788 This hook wraps the standard pytest runtestprotocol() function in order
789 to acquire visibility into, and record, each test function's result.
790
791 Args:
792 item: The pytest test item to execute.
793 nextitem: The pytest test item that will be executed after this one.
794
795 Returns:
796 A list of pytest reports (test result data).
Stephen Warren75e731e2016-01-26 13:41:30 -0700797 """
Stephen Warren10e50632016-01-15 11:15:24 -0700798
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700799 log.get_and_reset_warning()
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700800 ihook = item.ihook
801 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
Simon Glass1dffd532025-01-27 07:52:54 -0700802 start = time.monotonic()
Stephen Warren10e50632016-01-15 11:15:24 -0700803 reports = runtestprotocol(item, nextitem=nextitem)
Simon Glass1dffd532025-01-27 07:52:54 -0700804 duration = round((time.monotonic() - start) * 1000, 1)
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700805 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700806 was_warning = log.get_and_reset_warning()
Stephen Warren25b05242016-01-27 23:57:51 -0700807
Stephen Warren3e3d1432016-10-17 17:25:52 -0600808 # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
809 # the test is skipped. That call is required to create the test's section
810 # in the log file. The call to log.end_section() requires that the log
811 # contain a section for this test. Create a section for the test if it
812 # doesn't already exist.
813 if not item.name in anchors:
814 start_test_section(item)
815
Stephen Warren25b05242016-01-27 23:57:51 -0700816 failure_cleanup = False
Simon Glass1dffd532025-01-27 07:52:54 -0700817 record_duration = True
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700818 if not was_warning:
819 test_list = tests_passed
820 msg = 'OK'
821 msg_log = log.status_pass
822 else:
823 test_list = tests_warning
824 msg = 'OK (with warning)'
825 msg_log = log.status_warning
Stephen Warren10e50632016-01-15 11:15:24 -0700826 for report in reports:
827 if report.outcome == 'failed':
Stephen Warren25b05242016-01-27 23:57:51 -0700828 if hasattr(report, 'wasxfail'):
829 test_list = tests_xpassed
830 msg = 'XPASSED'
831 msg_log = log.status_xpass
832 else:
833 failure_cleanup = True
834 test_list = tests_failed
835 msg = 'FAILED:\n' + str(report.longrepr)
836 msg_log = log.status_fail
Stephen Warren10e50632016-01-15 11:15:24 -0700837 break
838 if report.outcome == 'skipped':
Stephen Warren25b05242016-01-27 23:57:51 -0700839 if hasattr(report, 'wasxfail'):
840 failure_cleanup = True
841 test_list = tests_xfailed
842 msg = 'XFAILED:\n' + str(report.longrepr)
843 msg_log = log.status_xfail
844 break
845 test_list = tests_skipped
846 msg = 'SKIPPED:\n' + str(report.longrepr)
847 msg_log = log.status_skipped
Simon Glass1dffd532025-01-27 07:52:54 -0700848 record_duration = False
849
850 msg += f' {duration} ms'
851 if record_duration:
852 test_durations[item.name] = duration
Stephen Warren10e50632016-01-15 11:15:24 -0700853
Stephen Warren25b05242016-01-27 23:57:51 -0700854 if failure_cleanup:
Simon Glassfb916372025-02-09 09:07:15 -0700855 ubman_fix.drain_console()
Stephen Warren25b05242016-01-27 23:57:51 -0700856
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700857 test_list.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700858 tests_not_run.remove(item.name)
859
860 try:
Stephen Warren25b05242016-01-27 23:57:51 -0700861 msg_log(msg)
Stephen Warren10e50632016-01-15 11:15:24 -0700862 except:
863 # If something went wrong with logging, it's better to let the test
864 # process continue, which may report other exceptions that triggered
Simon Glassfb916372025-02-09 09:07:15 -0700865 # the logging issue (e.g. ubman_fix.log wasn't created). Hence, just
Stephen Warren10e50632016-01-15 11:15:24 -0700866 # squash the exception. If the test setup failed due to e.g. syntax
867 # error somewhere else, this won't be seen. However, once that issue
868 # is fixed, if this exception still exists, it will then be logged as
869 # part of the test's stdout.
870 import traceback
Paul Burton00f2d202017-09-14 14:34:43 -0700871 print('Exception occurred while logging runtest status:')
Stephen Warren10e50632016-01-15 11:15:24 -0700872 traceback.print_exc()
873 # FIXME: Can we force a test failure here?
874
875 log.end_section(item.name)
876
Stephen Warren25b05242016-01-27 23:57:51 -0700877 if failure_cleanup:
Simon Glassfb916372025-02-09 09:07:15 -0700878 ubman_fix.cleanup_spawn()
Stephen Warren10e50632016-01-15 11:15:24 -0700879
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700880 return True