blob: 5aea85647afd519fc1db050915910b39dbee9624 [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')
Simon Glass4619fc72025-03-15 14:25:51 +0000337 ubconfig.role = config.getoption('role')
Stephen Warren10e50632016-01-15 11:15:24 -0700338
339 env_vars = (
340 'board_type',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700341 'board_type_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700342 'board_identity',
343 'source_dir',
344 'test_py_dir',
345 'build_dir',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700346 'build_dir_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700347 'result_dir',
348 'persistent_data_dir',
349 )
350 for v in env_vars:
351 os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
352
Simon Glass13f422e2016-07-04 11:58:37 -0600353 if board_type.startswith('sandbox'):
Simon Glassfb916372025-02-09 09:07:15 -0700354 import console_sandbox
355 ubman_fix = console_sandbox.ConsoleSandbox(log, ubconfig)
Stephen Warren10e50632016-01-15 11:15:24 -0700356 else:
Simon Glassfb916372025-02-09 09:07:15 -0700357 import console_board
358 ubman_fix = console_board.ConsoleExecAttach(log, ubconfig)
Stephen Warren10e50632016-01-15 11:15:24 -0700359
Simon Glassb15512c2025-01-20 14:25:32 -0700360
Simon Glassed298be2020-10-25 20:38:31 -0600361def generate_ut_subtest(metafunc, fixture_name, sym_path):
Stephen Warren770fe172016-02-08 14:44:16 -0700362 """Provide parametrization for a ut_subtest fixture.
363
364 Determines the set of unit tests built into a U-Boot binary by parsing the
365 list of symbols generated by the build process. Provides this information
366 to test functions by parameterizing their ut_subtest fixture parameter.
367
368 Args:
369 metafunc: The pytest test function.
370 fixture_name: The fixture name to test.
Simon Glassed298be2020-10-25 20:38:31 -0600371 sym_path: Relative path to the symbol file with preceding '/'
372 (e.g. '/u-boot.sym')
Stephen Warren770fe172016-02-08 14:44:16 -0700373
374 Returns:
375 Nothing.
376 """
Simon Glassfb916372025-02-09 09:07:15 -0700377 fn = ubman_fix.config.build_dir + sym_path
Stephen Warren770fe172016-02-08 14:44:16 -0700378 try:
379 with open(fn, 'rt') as f:
380 lines = f.readlines()
381 except:
382 lines = []
383 lines.sort()
384
385 vals = []
386 for l in lines:
Simon Glassb15512c2025-01-20 14:25:32 -0700387 m = RE_UT_TEST_LIST.search(l)
Stephen Warren770fe172016-02-08 14:44:16 -0700388 if not m:
389 continue
Simon Glass1f1614b2022-10-20 18:22:50 -0600390 suite, name = m.groups()
391
392 # Tests marked with _norun should only be run manually using 'ut -f'
393 if name.endswith('_norun'):
394 continue
395
396 vals.append(f'{suite} {name}')
Stephen Warren770fe172016-02-08 14:44:16 -0700397
398 ids = ['ut_' + s.replace(' ', '_') for s in vals]
399 metafunc.parametrize(fixture_name, vals, ids=ids)
400
401def generate_config(metafunc, fixture_name):
402 """Provide parametrization for {env,brd}__ fixtures.
Stephen Warren10e50632016-01-15 11:15:24 -0700403
404 If a test function takes parameter(s) (fixture names) of the form brd__xxx
405 or env__xxx, the brd and env configuration dictionaries are consulted to
406 find the list of values to use for those parameters, and the test is
407 parametrized so that it runs once for each combination of values.
408
409 Args:
410 metafunc: The pytest test function.
Stephen Warren770fe172016-02-08 14:44:16 -0700411 fixture_name: The fixture name to test.
Stephen Warren10e50632016-01-15 11:15:24 -0700412
413 Returns:
414 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700415 """
Stephen Warren10e50632016-01-15 11:15:24 -0700416
417 subconfigs = {
Simon Glassfb916372025-02-09 09:07:15 -0700418 'brd': ubman_fix.config.brd,
419 'env': ubman_fix.config.env,
Stephen Warren10e50632016-01-15 11:15:24 -0700420 }
Stephen Warren770fe172016-02-08 14:44:16 -0700421 parts = fixture_name.split('__')
422 if len(parts) < 2:
423 return
424 if parts[0] not in subconfigs:
425 return
426 subconfig = subconfigs[parts[0]]
427 vals = []
428 val = subconfig.get(fixture_name, [])
429 # If that exact name is a key in the data source:
430 if val:
431 # ... use the dict value as a single parameter value.
432 vals = (val, )
433 else:
434 # ... otherwise, see if there's a key that contains a list of
435 # values to use instead.
436 vals = subconfig.get(fixture_name+ 's', [])
437 def fixture_id(index, val):
438 try:
439 return val['fixture_id']
440 except:
441 return fixture_name + str(index)
442 ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
443 metafunc.parametrize(fixture_name, vals, ids=ids)
444
445def pytest_generate_tests(metafunc):
446 """pytest hook: parameterize test functions based on custom rules.
447
448 Check each test function parameter (fixture name) to see if it is one of
449 our custom names, and if so, provide the correct parametrization for that
450 parameter.
451
452 Args:
453 metafunc: The pytest test function.
454
455 Returns:
456 Nothing.
457 """
Stephen Warren10e50632016-01-15 11:15:24 -0700458 for fn in metafunc.fixturenames:
Stephen Warren770fe172016-02-08 14:44:16 -0700459 if fn == 'ut_subtest':
Simon Glassed298be2020-10-25 20:38:31 -0600460 generate_ut_subtest(metafunc, fn, '/u-boot.sym')
461 continue
Simon Glassb6c665f2022-04-30 00:56:55 -0600462 m_subtest = re.match('ut_(.)pl_subtest', fn)
463 if m_subtest:
464 spl_name = m_subtest.group(1)
465 generate_ut_subtest(
466 metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
Stephen Warren10e50632016-01-15 11:15:24 -0700467 continue
Stephen Warren770fe172016-02-08 14:44:16 -0700468 generate_config(metafunc, fn)
Stephen Warren10e50632016-01-15 11:15:24 -0700469
Stefan Brüns364ea872016-11-05 17:45:32 +0100470@pytest.fixture(scope='session')
471def u_boot_log(request):
472 """Generate the value of a test's log fixture.
473
474 Args:
475 request: The pytest request.
476
477 Returns:
478 The fixture value.
479 """
480
Simon Glassfb916372025-02-09 09:07:15 -0700481 return ubman_fix.log
Stefan Brüns364ea872016-11-05 17:45:32 +0100482
483@pytest.fixture(scope='session')
484def u_boot_config(request):
485 """Generate the value of a test's u_boot_config fixture.
486
487 Args:
488 request: The pytest request.
489
490 Returns:
491 The fixture value.
492 """
493
Simon Glassfb916372025-02-09 09:07:15 -0700494 return ubman_fix.config
Stefan Brüns364ea872016-11-05 17:45:32 +0100495
Stephen Warrene1d24d02016-01-22 12:30:08 -0700496@pytest.fixture(scope='function')
Simon Glassddba5202025-02-09 09:07:14 -0700497def ubman(request):
498 """Generate the value of a test's ubman fixture.
Stephen Warren10e50632016-01-15 11:15:24 -0700499
500 Args:
501 request: The pytest request.
502
503 Returns:
504 The fixture value.
Stephen Warren75e731e2016-01-26 13:41:30 -0700505 """
Simon Glassd834d9a2024-10-09 18:29:03 -0600506 if not ubconfig.connection_ok:
507 pytest.skip('Cannot get target connection')
508 return None
509 try:
Simon Glassfb916372025-02-09 09:07:15 -0700510 ubman_fix.ensure_spawned()
Simon Glassd834d9a2024-10-09 18:29:03 -0600511 except OSError as err:
Simon Glassfb916372025-02-09 09:07:15 -0700512 handle_exception(ubconfig, ubman_fix, log, err, 'Lab failure', True)
Simon Glassd834d9a2024-10-09 18:29:03 -0600513 except Timeout as err:
Simon Glassfb916372025-02-09 09:07:15 -0700514 handle_exception(ubconfig, ubman_fix, log, err, 'Lab timeout', True)
Simon Glassd834d9a2024-10-09 18:29:03 -0600515 except BootFail as err:
Simon Glassfb916372025-02-09 09:07:15 -0700516 handle_exception(ubconfig, ubman_fix, log, err, 'Boot fail', True,
517 ubman.get_spawn_output())
Simon Glassd834d9a2024-10-09 18:29:03 -0600518 except Unexpected:
Simon Glassfb916372025-02-09 09:07:15 -0700519 handle_exception(ubconfig, ubman_fix, log, err, 'Unexpected test output',
Simon Glassd834d9a2024-10-09 18:29:03 -0600520 False)
Simon Glassfb916372025-02-09 09:07:15 -0700521 return ubman_fix
Stephen Warren10e50632016-01-15 11:15:24 -0700522
Stephen Warrene3f2a502016-02-03 16:46:34 -0700523anchors = {}
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700524tests_not_run = []
525tests_failed = []
526tests_xpassed = []
527tests_xfailed = []
528tests_skipped = []
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700529tests_warning = []
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700530tests_passed = []
Stephen Warren10e50632016-01-15 11:15:24 -0700531
Simon Glass1dffd532025-01-27 07:52:54 -0700532# Duration of each test:
533# key (string): test name
534# value (float): duration in ms
535test_durations = {}
536
537
Stephen Warren10e50632016-01-15 11:15:24 -0700538def pytest_itemcollected(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700539 """pytest hook: Called once for each test found during collection.
Stephen Warren10e50632016-01-15 11:15:24 -0700540
541 This enables our custom result analysis code to see the list of all tests
542 that should eventually be run.
543
544 Args:
545 item: The item that was collected.
546
547 Returns:
548 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700549 """
Stephen Warren10e50632016-01-15 11:15:24 -0700550
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700551 tests_not_run.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700552
Simon Glass1dffd532025-01-27 07:52:54 -0700553
554def show_timings():
555 """Write timings for each test, along with a histogram"""
556
557 def get_time_delta(msecs):
558 """Convert milliseconds into a user-friendly string"""
559 if msecs >= 1000:
560 return f'{msecs / 1000:.1f}s'
561 else:
562 return f'{msecs:.0f}ms'
563
564 def show_bar(key, msecs, value):
565 """Show a single bar (line) of the histogram
566
567 Args:
568 key (str): Key to write on the left
569 value (int): Value to display, i.e. the relative length of the bar
570 """
571 if value:
572 bar_length = int((value / max_count) * max_bar_length)
573 print(f"{key:>8} : {get_time_delta(msecs):>7} |{'#' * bar_length} {value}", file=buf)
574
575 # Create the buckets we will use, each has a count and a total time
576 bucket = {}
577 for power in range(5):
578 for i in [1, 2, 3, 4, 5, 7.5]:
579 bucket[i * 10 ** power] = {'count': 0, 'msecs': 0.0}
580 max_dur = max(bucket.keys())
581
582 # Collect counts for each bucket; if outside the range, add to too_long
583 # Also show a sorted list of test timings from longest to shortest
584 too_long = 0
585 too_long_msecs = 0.0
586 max_count = 0
587 with log.section('Timing Report', 'timing_report'):
588 for name, dur in sorted(test_durations.items(), key=lambda kv: kv[1],
589 reverse=True):
590 log.info(f'{get_time_delta(dur):>8} {name}')
591 greater = [k for k in bucket.keys() if dur <= k]
592 if greater:
593 buck = bucket[min(greater)]
594 buck['count'] += 1
595 max_count = max(max_count, buck['count'])
596 buck['msecs'] += dur
597 else:
598 too_long += 1
599 too_long_msecs += dur
600
601 # Set the maximum length of a histogram bar, in characters
602 max_bar_length = 40
603
604 # Show a a summary with histogram
605 buf = io.StringIO()
606 with log.section('Timing Summary', 'timing_summary'):
607 print('Duration : Total | Number of tests', file=buf)
608 print(f'{"=" * 8} : {"=" * 7} |{"=" * max_bar_length}', file=buf)
609 for dur, buck in bucket.items():
610 if buck['count']:
611 label = get_time_delta(dur)
612 show_bar(f'<{label}', buck['msecs'], buck['count'])
613 if too_long:
614 show_bar(f'>{get_time_delta(max_dur)}', too_long_msecs, too_long)
615 log.info(buf.getvalue())
616 if ubconfig.timing:
617 print(buf.getvalue(), end='')
618
619
Stephen Warren10e50632016-01-15 11:15:24 -0700620def cleanup():
Stephen Warren75e731e2016-01-26 13:41:30 -0700621 """Clean up all global state.
Stephen Warren10e50632016-01-15 11:15:24 -0700622
623 Executed (via atexit) once the entire test process is complete. This
624 includes logging the status of all tests, and the identity of any failed
625 or skipped tests.
626
627 Args:
628 None.
629
630 Returns:
631 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700632 """
Stephen Warren10e50632016-01-15 11:15:24 -0700633
Simon Glassfb916372025-02-09 09:07:15 -0700634 if ubman_fix:
635 ubman_fix.close()
Stephen Warren10e50632016-01-15 11:15:24 -0700636 if log:
Stephen Warrene3f2a502016-02-03 16:46:34 -0700637 with log.section('Status Report', 'status_report'):
638 log.status_pass('%d passed' % len(tests_passed))
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700639 if tests_warning:
640 log.status_warning('%d passed with warning' % len(tests_warning))
641 for test in tests_warning:
642 anchor = anchors.get(test, None)
643 log.status_warning('... ' + test, anchor)
Stephen Warrene3f2a502016-02-03 16:46:34 -0700644 if tests_skipped:
645 log.status_skipped('%d skipped' % len(tests_skipped))
646 for test in tests_skipped:
647 anchor = anchors.get(test, None)
648 log.status_skipped('... ' + test, anchor)
649 if tests_xpassed:
650 log.status_xpass('%d xpass' % len(tests_xpassed))
651 for test in tests_xpassed:
652 anchor = anchors.get(test, None)
653 log.status_xpass('... ' + test, anchor)
654 if tests_xfailed:
655 log.status_xfail('%d xfail' % len(tests_xfailed))
656 for test in tests_xfailed:
657 anchor = anchors.get(test, None)
658 log.status_xfail('... ' + test, anchor)
659 if tests_failed:
660 log.status_fail('%d failed' % len(tests_failed))
661 for test in tests_failed:
662 anchor = anchors.get(test, None)
663 log.status_fail('... ' + test, anchor)
664 if tests_not_run:
665 log.status_fail('%d not run' % len(tests_not_run))
666 for test in tests_not_run:
667 anchor = anchors.get(test, None)
668 log.status_fail('... ' + test, anchor)
Simon Glass1dffd532025-01-27 07:52:54 -0700669 show_timings()
Stephen Warren10e50632016-01-15 11:15:24 -0700670 log.close()
671atexit.register(cleanup)
672
673def setup_boardspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700674 """Process any 'boardspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700675
676 Such a marker lists the set of board types that a test does/doesn't
677 support. If tests are being executed on an unsupported board, the test is
678 marked to be skipped.
679
680 Args:
681 item: The pytest test item.
682
683 Returns:
684 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700685 """
Stephen Warren10e50632016-01-15 11:15:24 -0700686
Stephen Warren10e50632016-01-15 11:15:24 -0700687 required_boards = []
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400688 for boards in item.iter_markers('boardspec'):
689 board = boards.args[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700690 if board.startswith('!'):
691 if ubconfig.board_type == board[1:]:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600692 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700693 return
694 else:
695 required_boards.append(board)
696 if required_boards and ubconfig.board_type not in required_boards:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600697 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700698
699def setup_buildconfigspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700700 """Process any 'buildconfigspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700701
702 Such a marker lists some U-Boot configuration feature that the test
703 requires. If tests are being executed on an U-Boot build that doesn't
704 have the required feature, the test is marked to be skipped.
705
706 Args:
707 item: The pytest test item.
708
709 Returns:
710 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700711 """
Stephen Warren10e50632016-01-15 11:15:24 -0700712
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400713 for options in item.iter_markers('buildconfigspec'):
714 option = options.args[0]
715 if not ubconfig.buildconfig.get('config_' + option.lower(), None):
716 pytest.skip('.config feature "%s" not enabled' % option.lower())
Cristian Ciocaltea6c6c8072019-12-24 17:19:12 +0200717 for options in item.iter_markers('notbuildconfigspec'):
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400718 option = options.args[0]
719 if ubconfig.buildconfig.get('config_' + option.lower(), None):
720 pytest.skip('.config feature "%s" enabled' % option.lower())
Stephen Warren10e50632016-01-15 11:15:24 -0700721
Stephen Warren2079db32017-09-18 11:11:49 -0600722def tool_is_in_path(tool):
723 for path in os.environ["PATH"].split(os.pathsep):
724 fn = os.path.join(path, tool)
725 if os.path.isfile(fn) and os.access(fn, os.X_OK):
726 return True
727 return False
728
729def setup_requiredtool(item):
730 """Process any 'requiredtool' marker for a test.
731
732 Such a marker lists some external tool (binary, executable, application)
733 that the test requires. If tests are being executed on a system that
734 doesn't have the required tool, the test is marked to be skipped.
735
736 Args:
737 item: The pytest test item.
738
739 Returns:
740 Nothing.
741 """
742
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400743 for tools in item.iter_markers('requiredtool'):
744 tool = tools.args[0]
Stephen Warren2079db32017-09-18 11:11:49 -0600745 if not tool_is_in_path(tool):
746 pytest.skip('tool "%s" not in $PATH' % tool)
747
Simon Glass54ef2ca2022-08-06 17:51:47 -0600748def setup_singlethread(item):
749 """Process any 'singlethread' marker for a test.
750
751 Skip this test if running in parallel.
752
753 Args:
754 item: The pytest test item.
755
756 Returns:
757 Nothing.
758 """
759 for single in item.iter_markers('singlethread'):
760 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
761 if worker_id and worker_id != 'master':
762 pytest.skip('must run single-threaded')
763
Simon Glass4619fc72025-03-15 14:25:51 +0000764def setup_role(item):
765 """Process any 'role' marker for a test.
766
767 Skip this test if the role does not match.
768
769 Args:
770 item (pytest.Item): The pytest test item
771 """
772 required_roles = []
773 for roles in item.iter_markers('role'):
774 role = roles.args[0]
775 if role.startswith('!'):
776 if ubconfig.role == role[1:]:
777 pytest.skip(f'role "{ubconfig.role}" not supported')
778 return
779 else:
780 required_roles.append(role)
781 if required_roles and ubconfig.role not in required_roles:
782 pytest.skip(f'board "{ubconfig.role}" not supported')
783
Stephen Warren3e3d1432016-10-17 17:25:52 -0600784def start_test_section(item):
785 anchors[item.name] = log.start_section(item.name)
786
Stephen Warren10e50632016-01-15 11:15:24 -0700787def pytest_runtest_setup(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700788 """pytest hook: Configure (set up) a test item.
Stephen Warren10e50632016-01-15 11:15:24 -0700789
790 Called once for each test to perform any custom configuration. This hook
791 is used to skip the test if certain conditions apply.
792
793 Args:
794 item: The pytest test item.
795
796 Returns:
797 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700798 """
Stephen Warren10e50632016-01-15 11:15:24 -0700799
Stephen Warren3e3d1432016-10-17 17:25:52 -0600800 start_test_section(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700801 setup_boardspec(item)
802 setup_buildconfigspec(item)
Stephen Warren2079db32017-09-18 11:11:49 -0600803 setup_requiredtool(item)
Simon Glass54ef2ca2022-08-06 17:51:47 -0600804 setup_singlethread(item)
Simon Glass4619fc72025-03-15 14:25:51 +0000805 setup_role(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700806
807def pytest_runtest_protocol(item, nextitem):
Stephen Warren75e731e2016-01-26 13:41:30 -0700808 """pytest hook: Called to execute a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700809
810 This hook wraps the standard pytest runtestprotocol() function in order
811 to acquire visibility into, and record, each test function's result.
812
813 Args:
814 item: The pytest test item to execute.
815 nextitem: The pytest test item that will be executed after this one.
816
817 Returns:
818 A list of pytest reports (test result data).
Stephen Warren75e731e2016-01-26 13:41:30 -0700819 """
Stephen Warren10e50632016-01-15 11:15:24 -0700820
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700821 log.get_and_reset_warning()
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700822 ihook = item.ihook
823 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
Simon Glass1dffd532025-01-27 07:52:54 -0700824 start = time.monotonic()
Stephen Warren10e50632016-01-15 11:15:24 -0700825 reports = runtestprotocol(item, nextitem=nextitem)
Simon Glass1dffd532025-01-27 07:52:54 -0700826 duration = round((time.monotonic() - start) * 1000, 1)
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700827 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700828 was_warning = log.get_and_reset_warning()
Stephen Warren25b05242016-01-27 23:57:51 -0700829
Stephen Warren3e3d1432016-10-17 17:25:52 -0600830 # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
831 # the test is skipped. That call is required to create the test's section
832 # in the log file. The call to log.end_section() requires that the log
833 # contain a section for this test. Create a section for the test if it
834 # doesn't already exist.
835 if not item.name in anchors:
836 start_test_section(item)
837
Stephen Warren25b05242016-01-27 23:57:51 -0700838 failure_cleanup = False
Simon Glass1dffd532025-01-27 07:52:54 -0700839 record_duration = True
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700840 if not was_warning:
841 test_list = tests_passed
842 msg = 'OK'
843 msg_log = log.status_pass
844 else:
845 test_list = tests_warning
846 msg = 'OK (with warning)'
847 msg_log = log.status_warning
Stephen Warren10e50632016-01-15 11:15:24 -0700848 for report in reports:
849 if report.outcome == 'failed':
Stephen Warren25b05242016-01-27 23:57:51 -0700850 if hasattr(report, 'wasxfail'):
851 test_list = tests_xpassed
852 msg = 'XPASSED'
853 msg_log = log.status_xpass
854 else:
855 failure_cleanup = True
856 test_list = tests_failed
857 msg = 'FAILED:\n' + str(report.longrepr)
858 msg_log = log.status_fail
Stephen Warren10e50632016-01-15 11:15:24 -0700859 break
860 if report.outcome == 'skipped':
Stephen Warren25b05242016-01-27 23:57:51 -0700861 if hasattr(report, 'wasxfail'):
862 failure_cleanup = True
863 test_list = tests_xfailed
864 msg = 'XFAILED:\n' + str(report.longrepr)
865 msg_log = log.status_xfail
866 break
867 test_list = tests_skipped
868 msg = 'SKIPPED:\n' + str(report.longrepr)
869 msg_log = log.status_skipped
Simon Glass1dffd532025-01-27 07:52:54 -0700870 record_duration = False
871
872 msg += f' {duration} ms'
873 if record_duration:
874 test_durations[item.name] = duration
Stephen Warren10e50632016-01-15 11:15:24 -0700875
Stephen Warren25b05242016-01-27 23:57:51 -0700876 if failure_cleanup:
Simon Glassfb916372025-02-09 09:07:15 -0700877 ubman_fix.drain_console()
Stephen Warren25b05242016-01-27 23:57:51 -0700878
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700879 test_list.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700880 tests_not_run.remove(item.name)
881
882 try:
Stephen Warren25b05242016-01-27 23:57:51 -0700883 msg_log(msg)
Stephen Warren10e50632016-01-15 11:15:24 -0700884 except:
885 # If something went wrong with logging, it's better to let the test
886 # process continue, which may report other exceptions that triggered
Simon Glassfb916372025-02-09 09:07:15 -0700887 # the logging issue (e.g. ubman_fix.log wasn't created). Hence, just
Stephen Warren10e50632016-01-15 11:15:24 -0700888 # squash the exception. If the test setup failed due to e.g. syntax
889 # error somewhere else, this won't be seen. However, once that issue
890 # is fixed, if this exception still exists, it will then be logged as
891 # part of the test's stdout.
892 import traceback
Paul Burton00f2d202017-09-14 14:34:43 -0700893 print('Exception occurred while logging runtest status:')
Stephen Warren10e50632016-01-15 11:15:24 -0700894 traceback.print_exc()
895 # FIXME: Can we force a test failure here?
896
897 log.end_section(item.name)
898
Stephen Warren25b05242016-01-27 23:57:51 -0700899 if failure_cleanup:
Simon Glassfb916372025-02-09 09:07:15 -0700900 ubman_fix.cleanup_spawn()
Stephen Warren10e50632016-01-15 11:15:24 -0700901
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700902 return True