blob: d9f074f3817a8330212d0afafa8f7de43a9fc5ff [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.
10# - Creating the U-Boot console test fixture.
11# - 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 Glassd834d9a2024-10-09 18:29:03 -060028from u_boot_spawn import BootFail, Timeout, Unexpected, handle_exception
Stephen Warren10e50632016-01-15 11:15:24 -070029
30# Globals: The HTML log file, and the connection to the U-Boot console.
31log = None
32console = None
33
Simon Glass62b92f82022-08-06 17:51:57 -060034TEST_PY_DIR = os.path.dirname(os.path.abspath(__file__))
35
Stephen Warren10e50632016-01-15 11:15:24 -070036def mkdir_p(path):
Stephen Warren75e731e2016-01-26 13:41:30 -070037 """Create a directory path.
Stephen Warren10e50632016-01-15 11:15:24 -070038
39 This includes creating any intermediate/parent directories. Any errors
40 caused due to already extant directories are ignored.
41
42 Args:
43 path: The directory path to create.
44
45 Returns:
46 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070047 """
Stephen Warren10e50632016-01-15 11:15:24 -070048
49 try:
50 os.makedirs(path)
51 except OSError as exc:
52 if exc.errno == errno.EEXIST and os.path.isdir(path):
53 pass
54 else:
55 raise
56
57def pytest_addoption(parser):
Stephen Warren75e731e2016-01-26 13:41:30 -070058 """pytest hook: Add custom command-line options to the cmdline parser.
Stephen Warren10e50632016-01-15 11:15:24 -070059
60 Args:
61 parser: The pytest command-line parser.
62
63 Returns:
64 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070065 """
Stephen Warren10e50632016-01-15 11:15:24 -070066
67 parser.addoption('--build-dir', default=None,
68 help='U-Boot build directory (O=)')
Simon Glass5a63a4b2024-11-12 07:13:24 -070069 parser.addoption('--build-dir-extra', default=None,
70 help='U-Boot build directory for extra build (O=)')
Stephen Warren10e50632016-01-15 11:15:24 -070071 parser.addoption('--result-dir', default=None,
72 help='U-Boot test result/tmp directory')
73 parser.addoption('--persistent-data-dir', default=None,
74 help='U-Boot test persistent generated data directory')
75 parser.addoption('--board-type', '--bd', '-B', default='sandbox',
76 help='U-Boot board type')
Simon Glass5a63a4b2024-11-12 07:13:24 -070077 parser.addoption('--board-type-extra', '--bde', default='sandbox',
78 help='U-Boot extra board type')
Stephen Warren10e50632016-01-15 11:15:24 -070079 parser.addoption('--board-identity', '--id', default='na',
80 help='U-Boot board identity/instance')
81 parser.addoption('--build', default=False, action='store_true',
82 help='Compile U-Boot before running tests')
Simon Glass6e094842020-03-18 09:43:01 -060083 parser.addoption('--buildman', default=False, action='store_true',
84 help='Use buildman to build U-Boot (assuming --build is given)')
Stephen Warren33db1ee2016-02-04 16:11:50 -070085 parser.addoption('--gdbserver', default=None,
86 help='Run sandbox under gdbserver. The argument is the channel '+
87 'over which gdbserver should communicate, e.g. localhost:1234')
Simon Glassf6dbc362024-11-12 07:13:18 -070088 parser.addoption('--role', help='U-Boot board role (for Labgrid-sjg)')
Simon Glassf1b1bb82024-11-12 07:13:17 -070089 parser.addoption('--use-running-system', default=False, action='store_true',
90 help="Assume that U-Boot is ready and don't wait for a prompt")
Stephen Warren10e50632016-01-15 11:15:24 -070091
Simon Glass686fad72022-08-06 17:51:56 -060092def run_build(config, source_dir, build_dir, board_type, log):
93 """run_build: Build U-Boot
94
95 Args:
96 config: The pytest configuration.
97 soruce_dir (str): Directory containing source code
98 build_dir (str): Directory to build in
99 board_type (str): board_type parameter (e.g. 'sandbox')
100 log (Logfile): Log file to use
101 """
102 if config.getoption('buildman'):
103 if build_dir != source_dir:
104 dest_args = ['-o', build_dir, '-w']
105 else:
106 dest_args = ['-i']
107 cmds = (['buildman', '--board', board_type] + dest_args,)
108 name = 'buildman'
109 else:
110 if build_dir != source_dir:
111 o_opt = 'O=%s' % build_dir
112 else:
113 o_opt = ''
114 cmds = (
115 ['make', o_opt, '-s', board_type + '_defconfig'],
116 ['make', o_opt, '-s', '-j{}'.format(os.cpu_count())],
117 )
118 name = 'make'
119
120 with log.section(name):
121 runner = log.get_runner(name, sys.stdout)
122 for cmd in cmds:
123 runner.run(cmd, cwd=source_dir)
124 runner.close()
125 log.status_pass('OK')
126
Simon Glass35ad4322024-10-09 18:29:00 -0600127def get_details(config):
128 """Obtain salient details about the board and directories to use
129
130 Args:
131 config (pytest.Config): pytest configuration
132
133 Returns:
134 tuple:
135 str: Board type (U-Boot build name)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700136 str: Extra board type (where two U-Boot builds are needed)
Simon Glass35ad4322024-10-09 18:29:00 -0600137 str: Identity for the lab board
138 str: Build directory
Simon Glass5a63a4b2024-11-12 07:13:24 -0700139 str: Extra build directory (where two U-Boot builds are needed)
Simon Glass35ad4322024-10-09 18:29:00 -0600140 str: Source directory
141 """
Simon Glassf6dbc362024-11-12 07:13:18 -0700142 role = config.getoption('role')
143
144 # Get a few provided parameters
Simon Glass35ad4322024-10-09 18:29:00 -0600145 build_dir = config.getoption('build_dir')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700146 build_dir_extra = config.getoption('build_dir_extra')
Simon Glassf6dbc362024-11-12 07:13:18 -0700147 if role:
148 # When using a role, build_dir and build_dir_extra are normally not set,
149 # since they are picked up from Labgrid-sjg via the u-boot-test-getrole
150 # script
151 board_identity = role
152 cmd = ['u-boot-test-getrole', role, '--configure']
153 env = os.environ.copy()
154 if build_dir:
155 env['U_BOOT_BUILD_DIR'] = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700156 if build_dir_extra:
157 env['U_BOOT_BUILD_DIR_EXTRA'] = build_dir_extra
Simon Glassf6dbc362024-11-12 07:13:18 -0700158 proc = subprocess.run(cmd, capture_output=True, encoding='utf-8',
159 env=env)
160 if proc.returncode:
161 raise ValueError(proc.stderr)
162 # For debugging
163 # print('conftest: lab:', proc.stdout)
164 vals = {}
165 for line in proc.stdout.splitlines():
166 item, value = line.split(' ', maxsplit=1)
167 k = item.split(':')[-1]
168 vals[k] = value
169 # For debugging
170 # print('conftest: lab info:', vals)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700171
172 # Read the build directories here, in case none were provided in the
173 # command-line arguments
174 (board_type, board_type_extra, default_build_dir,
175 default_build_dir_extra, source_dir) = (vals['board'],
176 vals['board_extra'], vals['build_dir'], vals['build_dir_extra'],
177 vals['source_dir'])
Simon Glassf6dbc362024-11-12 07:13:18 -0700178 else:
179 board_type = config.getoption('board_type')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700180 board_type_extra = config.getoption('board_type_extra')
Simon Glassf6dbc362024-11-12 07:13:18 -0700181 board_identity = config.getoption('board_identity')
Simon Glass35ad4322024-10-09 18:29:00 -0600182
Simon Glassf6dbc362024-11-12 07:13:18 -0700183 source_dir = os.path.dirname(os.path.dirname(TEST_PY_DIR))
184 default_build_dir = source_dir + '/build-' + board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700185 default_build_dir_extra = source_dir + '/build-' + board_type_extra
186
187 # Use the provided command-line arguments if present, else fall back to
Simon Glass62b92f82022-08-06 17:51:57 -0600188 if not build_dir:
Simon Glass35ad4322024-10-09 18:29:00 -0600189 build_dir = default_build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700190 if not build_dir_extra:
191 build_dir_extra = default_build_dir_extra
Simon Glass35ad4322024-10-09 18:29:00 -0600192
Simon Glass5a63a4b2024-11-12 07:13:24 -0700193 return (board_type, board_type_extra, board_identity, build_dir,
194 build_dir_extra, source_dir)
Simon Glass35ad4322024-10-09 18:29:00 -0600195
196def pytest_xdist_setupnodes(config, specs):
197 """Clear out any 'done' file from a previous build"""
198 global build_done_file
199
Simon Glass5a63a4b2024-11-12 07:13:24 -0700200 build_dir = get_details(config)[3]
Simon Glass35ad4322024-10-09 18:29:00 -0600201
Simon Glass62b92f82022-08-06 17:51:57 -0600202 build_done_file = Path(build_dir) / 'build.done'
203 if build_done_file.exists():
204 os.remove(build_done_file)
205
Stephen Warren10e50632016-01-15 11:15:24 -0700206def pytest_configure(config):
Stephen Warren75e731e2016-01-26 13:41:30 -0700207 """pytest hook: Perform custom initialization at startup time.
Stephen Warren10e50632016-01-15 11:15:24 -0700208
209 Args:
210 config: The pytest configuration.
211
212 Returns:
213 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700214 """
Simon Glassde8e25b2019-12-01 19:34:18 -0700215 def parse_config(conf_file):
216 """Parse a config file, loading it into the ubconfig container
217
218 Args:
219 conf_file: Filename to load (within build_dir)
220
221 Raises
222 Exception if the file does not exist
223 """
224 dot_config = build_dir + '/' + conf_file
225 if not os.path.exists(dot_config):
226 raise Exception(conf_file + ' does not exist; ' +
227 'try passing --build option?')
228
229 with open(dot_config, 'rt') as f:
230 ini_str = '[root]\n' + f.read()
231 ini_sio = io.StringIO(ini_str)
232 parser = configparser.RawConfigParser()
233 parser.read_file(ini_sio)
234 ubconfig.buildconfig.update(parser.items('root'))
Stephen Warren10e50632016-01-15 11:15:24 -0700235
236 global log
237 global console
238 global ubconfig
239
Simon Glass5a63a4b2024-11-12 07:13:24 -0700240 (board_type, board_type_extra, board_identity, build_dir, build_dir_extra,
241 source_dir) = get_details(config)
Stephen Warren10e50632016-01-15 11:15:24 -0700242
Stephen Warren10e50632016-01-15 11:15:24 -0700243 board_type_filename = board_type.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700244 board_identity_filename = board_identity.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700245 mkdir_p(build_dir)
246
247 result_dir = config.getoption('result_dir')
248 if not result_dir:
249 result_dir = build_dir
250 mkdir_p(result_dir)
251
252 persistent_data_dir = config.getoption('persistent_data_dir')
253 if not persistent_data_dir:
254 persistent_data_dir = build_dir + '/persistent-data'
255 mkdir_p(persistent_data_dir)
256
Stephen Warren33db1ee2016-02-04 16:11:50 -0700257 gdbserver = config.getoption('gdbserver')
Igor Opaniukea5f17d2019-02-12 16:18:14 +0200258 if gdbserver and not board_type.startswith('sandbox'):
259 raise Exception('--gdbserver only supported with sandbox targets')
Stephen Warren33db1ee2016-02-04 16:11:50 -0700260
Stephen Warren10e50632016-01-15 11:15:24 -0700261 import multiplexed_log
262 log = multiplexed_log.Logfile(result_dir + '/test-log.html')
263
264 if config.getoption('build'):
Simon Glass62b92f82022-08-06 17:51:57 -0600265 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
266 with filelock.FileLock(os.path.join(build_dir, 'build.lock')):
267 build_done_file = Path(build_dir) / 'build.done'
268 if (not worker_id or worker_id == 'master' or
269 not build_done_file.exists()):
270 run_build(config, source_dir, build_dir, board_type, log)
271 build_done_file.touch()
Stephen Warren10e50632016-01-15 11:15:24 -0700272
273 class ArbitraryAttributeContainer(object):
274 pass
275
276 ubconfig = ArbitraryAttributeContainer()
277 ubconfig.brd = dict()
278 ubconfig.env = dict()
279
280 modules = [
281 (ubconfig.brd, 'u_boot_board_' + board_type_filename),
282 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
283 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
284 board_identity_filename),
285 ]
286 for (dict_to_fill, module_name) in modules:
287 try:
288 module = __import__(module_name)
289 except ImportError:
290 continue
291 dict_to_fill.update(module.__dict__)
292
293 ubconfig.buildconfig = dict()
294
Simon Glassde8e25b2019-12-01 19:34:18 -0700295 # buildman -k puts autoconf.mk in the rootdir, so handle this as well
296 # as the standard U-Boot build which leaves it in include/autoconf.mk
297 parse_config('.config')
298 if os.path.exists(build_dir + '/' + 'autoconf.mk'):
299 parse_config('autoconf.mk')
300 else:
301 parse_config('include/autoconf.mk')
Stephen Warren10e50632016-01-15 11:15:24 -0700302
Simon Glass62b92f82022-08-06 17:51:57 -0600303 ubconfig.test_py_dir = TEST_PY_DIR
Stephen Warren10e50632016-01-15 11:15:24 -0700304 ubconfig.source_dir = source_dir
305 ubconfig.build_dir = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700306 ubconfig.build_dir_extra = build_dir_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700307 ubconfig.result_dir = result_dir
308 ubconfig.persistent_data_dir = persistent_data_dir
309 ubconfig.board_type = board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700310 ubconfig.board_type_extra = board_type_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700311 ubconfig.board_identity = board_identity
Stephen Warren33db1ee2016-02-04 16:11:50 -0700312 ubconfig.gdbserver = gdbserver
Simon Glassf1b1bb82024-11-12 07:13:17 -0700313 ubconfig.use_running_system = config.getoption('use_running_system')
Simon Glass3b097872016-07-03 09:40:36 -0600314 ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
Simon Glassd834d9a2024-10-09 18:29:03 -0600315 ubconfig.connection_ok = True
Stephen Warren10e50632016-01-15 11:15:24 -0700316
317 env_vars = (
318 'board_type',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700319 'board_type_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700320 'board_identity',
321 'source_dir',
322 'test_py_dir',
323 'build_dir',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700324 'build_dir_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700325 'result_dir',
326 'persistent_data_dir',
327 )
328 for v in env_vars:
329 os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
330
Simon Glass13f422e2016-07-04 11:58:37 -0600331 if board_type.startswith('sandbox'):
Stephen Warren10e50632016-01-15 11:15:24 -0700332 import u_boot_console_sandbox
333 console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
334 else:
335 import u_boot_console_exec_attach
336 console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
337
Simon Glass23300b42021-10-23 17:26:11 -0600338re_ut_test_list = re.compile(r'[^a-zA-Z0-9_]_u_boot_list_2_ut_(.*)_test_2_(.*)\s*$')
Simon Glassed298be2020-10-25 20:38:31 -0600339def generate_ut_subtest(metafunc, fixture_name, sym_path):
Stephen Warren770fe172016-02-08 14:44:16 -0700340 """Provide parametrization for a ut_subtest fixture.
341
342 Determines the set of unit tests built into a U-Boot binary by parsing the
343 list of symbols generated by the build process. Provides this information
344 to test functions by parameterizing their ut_subtest fixture parameter.
345
346 Args:
347 metafunc: The pytest test function.
348 fixture_name: The fixture name to test.
Simon Glassed298be2020-10-25 20:38:31 -0600349 sym_path: Relative path to the symbol file with preceding '/'
350 (e.g. '/u-boot.sym')
Stephen Warren770fe172016-02-08 14:44:16 -0700351
352 Returns:
353 Nothing.
354 """
Simon Glassed298be2020-10-25 20:38:31 -0600355 fn = console.config.build_dir + sym_path
Stephen Warren770fe172016-02-08 14:44:16 -0700356 try:
357 with open(fn, 'rt') as f:
358 lines = f.readlines()
359 except:
360 lines = []
361 lines.sort()
362
363 vals = []
364 for l in lines:
365 m = re_ut_test_list.search(l)
366 if not m:
367 continue
Simon Glass1f1614b2022-10-20 18:22:50 -0600368 suite, name = m.groups()
369
370 # Tests marked with _norun should only be run manually using 'ut -f'
371 if name.endswith('_norun'):
372 continue
373
374 vals.append(f'{suite} {name}')
Stephen Warren770fe172016-02-08 14:44:16 -0700375
376 ids = ['ut_' + s.replace(' ', '_') for s in vals]
377 metafunc.parametrize(fixture_name, vals, ids=ids)
378
379def generate_config(metafunc, fixture_name):
380 """Provide parametrization for {env,brd}__ fixtures.
Stephen Warren10e50632016-01-15 11:15:24 -0700381
382 If a test function takes parameter(s) (fixture names) of the form brd__xxx
383 or env__xxx, the brd and env configuration dictionaries are consulted to
384 find the list of values to use for those parameters, and the test is
385 parametrized so that it runs once for each combination of values.
386
387 Args:
388 metafunc: The pytest test function.
Stephen Warren770fe172016-02-08 14:44:16 -0700389 fixture_name: The fixture name to test.
Stephen Warren10e50632016-01-15 11:15:24 -0700390
391 Returns:
392 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700393 """
Stephen Warren10e50632016-01-15 11:15:24 -0700394
395 subconfigs = {
396 'brd': console.config.brd,
397 'env': console.config.env,
398 }
Stephen Warren770fe172016-02-08 14:44:16 -0700399 parts = fixture_name.split('__')
400 if len(parts) < 2:
401 return
402 if parts[0] not in subconfigs:
403 return
404 subconfig = subconfigs[parts[0]]
405 vals = []
406 val = subconfig.get(fixture_name, [])
407 # If that exact name is a key in the data source:
408 if val:
409 # ... use the dict value as a single parameter value.
410 vals = (val, )
411 else:
412 # ... otherwise, see if there's a key that contains a list of
413 # values to use instead.
414 vals = subconfig.get(fixture_name+ 's', [])
415 def fixture_id(index, val):
416 try:
417 return val['fixture_id']
418 except:
419 return fixture_name + str(index)
420 ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
421 metafunc.parametrize(fixture_name, vals, ids=ids)
422
423def pytest_generate_tests(metafunc):
424 """pytest hook: parameterize test functions based on custom rules.
425
426 Check each test function parameter (fixture name) to see if it is one of
427 our custom names, and if so, provide the correct parametrization for that
428 parameter.
429
430 Args:
431 metafunc: The pytest test function.
432
433 Returns:
434 Nothing.
435 """
Stephen Warren10e50632016-01-15 11:15:24 -0700436 for fn in metafunc.fixturenames:
Stephen Warren770fe172016-02-08 14:44:16 -0700437 if fn == 'ut_subtest':
Simon Glassed298be2020-10-25 20:38:31 -0600438 generate_ut_subtest(metafunc, fn, '/u-boot.sym')
439 continue
Simon Glassb6c665f2022-04-30 00:56:55 -0600440 m_subtest = re.match('ut_(.)pl_subtest', fn)
441 if m_subtest:
442 spl_name = m_subtest.group(1)
443 generate_ut_subtest(
444 metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
Stephen Warren10e50632016-01-15 11:15:24 -0700445 continue
Stephen Warren770fe172016-02-08 14:44:16 -0700446 generate_config(metafunc, fn)
Stephen Warren10e50632016-01-15 11:15:24 -0700447
Stefan Brüns364ea872016-11-05 17:45:32 +0100448@pytest.fixture(scope='session')
449def u_boot_log(request):
450 """Generate the value of a test's log fixture.
451
452 Args:
453 request: The pytest request.
454
455 Returns:
456 The fixture value.
457 """
458
459 return console.log
460
461@pytest.fixture(scope='session')
462def u_boot_config(request):
463 """Generate the value of a test's u_boot_config fixture.
464
465 Args:
466 request: The pytest request.
467
468 Returns:
469 The fixture value.
470 """
471
472 return console.config
473
Stephen Warrene1d24d02016-01-22 12:30:08 -0700474@pytest.fixture(scope='function')
Stephen Warren10e50632016-01-15 11:15:24 -0700475def u_boot_console(request):
Stephen Warren75e731e2016-01-26 13:41:30 -0700476 """Generate the value of a test's u_boot_console fixture.
Stephen Warren10e50632016-01-15 11:15:24 -0700477
478 Args:
479 request: The pytest request.
480
481 Returns:
482 The fixture value.
Stephen Warren75e731e2016-01-26 13:41:30 -0700483 """
Simon Glassd834d9a2024-10-09 18:29:03 -0600484 if not ubconfig.connection_ok:
485 pytest.skip('Cannot get target connection')
486 return None
487 try:
488 console.ensure_spawned()
489 except OSError as err:
490 handle_exception(ubconfig, console, log, err, 'Lab failure', True)
491 except Timeout as err:
492 handle_exception(ubconfig, console, log, err, 'Lab timeout', True)
493 except BootFail as err:
494 handle_exception(ubconfig, console, log, err, 'Boot fail', True,
495 console.get_spawn_output())
496 except Unexpected:
497 handle_exception(ubconfig, console, log, err, 'Unexpected test output',
498 False)
Stephen Warren10e50632016-01-15 11:15:24 -0700499 return console
500
Stephen Warrene3f2a502016-02-03 16:46:34 -0700501anchors = {}
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700502tests_not_run = []
503tests_failed = []
504tests_xpassed = []
505tests_xfailed = []
506tests_skipped = []
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700507tests_warning = []
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700508tests_passed = []
Stephen Warren10e50632016-01-15 11:15:24 -0700509
510def pytest_itemcollected(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700511 """pytest hook: Called once for each test found during collection.
Stephen Warren10e50632016-01-15 11:15:24 -0700512
513 This enables our custom result analysis code to see the list of all tests
514 that should eventually be run.
515
516 Args:
517 item: The item that was collected.
518
519 Returns:
520 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700521 """
Stephen Warren10e50632016-01-15 11:15:24 -0700522
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700523 tests_not_run.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700524
525def cleanup():
Stephen Warren75e731e2016-01-26 13:41:30 -0700526 """Clean up all global state.
Stephen Warren10e50632016-01-15 11:15:24 -0700527
528 Executed (via atexit) once the entire test process is complete. This
529 includes logging the status of all tests, and the identity of any failed
530 or skipped tests.
531
532 Args:
533 None.
534
535 Returns:
536 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700537 """
Stephen Warren10e50632016-01-15 11:15:24 -0700538
539 if console:
540 console.close()
541 if log:
Stephen Warrene3f2a502016-02-03 16:46:34 -0700542 with log.section('Status Report', 'status_report'):
543 log.status_pass('%d passed' % len(tests_passed))
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700544 if tests_warning:
545 log.status_warning('%d passed with warning' % len(tests_warning))
546 for test in tests_warning:
547 anchor = anchors.get(test, None)
548 log.status_warning('... ' + test, anchor)
Stephen Warrene3f2a502016-02-03 16:46:34 -0700549 if tests_skipped:
550 log.status_skipped('%d skipped' % len(tests_skipped))
551 for test in tests_skipped:
552 anchor = anchors.get(test, None)
553 log.status_skipped('... ' + test, anchor)
554 if tests_xpassed:
555 log.status_xpass('%d xpass' % len(tests_xpassed))
556 for test in tests_xpassed:
557 anchor = anchors.get(test, None)
558 log.status_xpass('... ' + test, anchor)
559 if tests_xfailed:
560 log.status_xfail('%d xfail' % len(tests_xfailed))
561 for test in tests_xfailed:
562 anchor = anchors.get(test, None)
563 log.status_xfail('... ' + test, anchor)
564 if tests_failed:
565 log.status_fail('%d failed' % len(tests_failed))
566 for test in tests_failed:
567 anchor = anchors.get(test, None)
568 log.status_fail('... ' + test, anchor)
569 if tests_not_run:
570 log.status_fail('%d not run' % len(tests_not_run))
571 for test in tests_not_run:
572 anchor = anchors.get(test, None)
573 log.status_fail('... ' + test, anchor)
Stephen Warren10e50632016-01-15 11:15:24 -0700574 log.close()
575atexit.register(cleanup)
576
577def setup_boardspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700578 """Process any 'boardspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700579
580 Such a marker lists the set of board types that a test does/doesn't
581 support. If tests are being executed on an unsupported board, the test is
582 marked to be skipped.
583
584 Args:
585 item: The pytest test item.
586
587 Returns:
588 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700589 """
Stephen Warren10e50632016-01-15 11:15:24 -0700590
Stephen Warren10e50632016-01-15 11:15:24 -0700591 required_boards = []
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400592 for boards in item.iter_markers('boardspec'):
593 board = boards.args[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700594 if board.startswith('!'):
595 if ubconfig.board_type == board[1:]:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600596 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700597 return
598 else:
599 required_boards.append(board)
600 if required_boards and ubconfig.board_type not in required_boards:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600601 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700602
603def setup_buildconfigspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700604 """Process any 'buildconfigspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700605
606 Such a marker lists some U-Boot configuration feature that the test
607 requires. If tests are being executed on an U-Boot build that doesn't
608 have the required feature, the test is marked to be skipped.
609
610 Args:
611 item: The pytest test item.
612
613 Returns:
614 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700615 """
Stephen Warren10e50632016-01-15 11:15:24 -0700616
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400617 for options in item.iter_markers('buildconfigspec'):
618 option = options.args[0]
619 if not ubconfig.buildconfig.get('config_' + option.lower(), None):
620 pytest.skip('.config feature "%s" not enabled' % option.lower())
Cristian Ciocaltea6c6c8072019-12-24 17:19:12 +0200621 for options in item.iter_markers('notbuildconfigspec'):
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400622 option = options.args[0]
623 if ubconfig.buildconfig.get('config_' + option.lower(), None):
624 pytest.skip('.config feature "%s" enabled' % option.lower())
Stephen Warren10e50632016-01-15 11:15:24 -0700625
Stephen Warren2079db32017-09-18 11:11:49 -0600626def tool_is_in_path(tool):
627 for path in os.environ["PATH"].split(os.pathsep):
628 fn = os.path.join(path, tool)
629 if os.path.isfile(fn) and os.access(fn, os.X_OK):
630 return True
631 return False
632
633def setup_requiredtool(item):
634 """Process any 'requiredtool' marker for a test.
635
636 Such a marker lists some external tool (binary, executable, application)
637 that the test requires. If tests are being executed on a system that
638 doesn't have the required tool, the test is marked to be skipped.
639
640 Args:
641 item: The pytest test item.
642
643 Returns:
644 Nothing.
645 """
646
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400647 for tools in item.iter_markers('requiredtool'):
648 tool = tools.args[0]
Stephen Warren2079db32017-09-18 11:11:49 -0600649 if not tool_is_in_path(tool):
650 pytest.skip('tool "%s" not in $PATH' % tool)
651
Simon Glass54ef2ca2022-08-06 17:51:47 -0600652def setup_singlethread(item):
653 """Process any 'singlethread' marker for a test.
654
655 Skip this test if running in parallel.
656
657 Args:
658 item: The pytest test item.
659
660 Returns:
661 Nothing.
662 """
663 for single in item.iter_markers('singlethread'):
664 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
665 if worker_id and worker_id != 'master':
666 pytest.skip('must run single-threaded')
667
Stephen Warren3e3d1432016-10-17 17:25:52 -0600668def start_test_section(item):
669 anchors[item.name] = log.start_section(item.name)
670
Stephen Warren10e50632016-01-15 11:15:24 -0700671def pytest_runtest_setup(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700672 """pytest hook: Configure (set up) a test item.
Stephen Warren10e50632016-01-15 11:15:24 -0700673
674 Called once for each test to perform any custom configuration. This hook
675 is used to skip the test if certain conditions apply.
676
677 Args:
678 item: The pytest test item.
679
680 Returns:
681 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700682 """
Stephen Warren10e50632016-01-15 11:15:24 -0700683
Stephen Warren3e3d1432016-10-17 17:25:52 -0600684 start_test_section(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700685 setup_boardspec(item)
686 setup_buildconfigspec(item)
Stephen Warren2079db32017-09-18 11:11:49 -0600687 setup_requiredtool(item)
Simon Glass54ef2ca2022-08-06 17:51:47 -0600688 setup_singlethread(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700689
690def pytest_runtest_protocol(item, nextitem):
Stephen Warren75e731e2016-01-26 13:41:30 -0700691 """pytest hook: Called to execute a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700692
693 This hook wraps the standard pytest runtestprotocol() function in order
694 to acquire visibility into, and record, each test function's result.
695
696 Args:
697 item: The pytest test item to execute.
698 nextitem: The pytest test item that will be executed after this one.
699
700 Returns:
701 A list of pytest reports (test result data).
Stephen Warren75e731e2016-01-26 13:41:30 -0700702 """
Stephen Warren10e50632016-01-15 11:15:24 -0700703
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700704 log.get_and_reset_warning()
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700705 ihook = item.ihook
706 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
Stephen Warren10e50632016-01-15 11:15:24 -0700707 reports = runtestprotocol(item, nextitem=nextitem)
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700708 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700709 was_warning = log.get_and_reset_warning()
Stephen Warren25b05242016-01-27 23:57:51 -0700710
Stephen Warren3e3d1432016-10-17 17:25:52 -0600711 # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
712 # the test is skipped. That call is required to create the test's section
713 # in the log file. The call to log.end_section() requires that the log
714 # contain a section for this test. Create a section for the test if it
715 # doesn't already exist.
716 if not item.name in anchors:
717 start_test_section(item)
718
Stephen Warren25b05242016-01-27 23:57:51 -0700719 failure_cleanup = False
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700720 if not was_warning:
721 test_list = tests_passed
722 msg = 'OK'
723 msg_log = log.status_pass
724 else:
725 test_list = tests_warning
726 msg = 'OK (with warning)'
727 msg_log = log.status_warning
Stephen Warren10e50632016-01-15 11:15:24 -0700728 for report in reports:
729 if report.outcome == 'failed':
Stephen Warren25b05242016-01-27 23:57:51 -0700730 if hasattr(report, 'wasxfail'):
731 test_list = tests_xpassed
732 msg = 'XPASSED'
733 msg_log = log.status_xpass
734 else:
735 failure_cleanup = True
736 test_list = tests_failed
737 msg = 'FAILED:\n' + str(report.longrepr)
738 msg_log = log.status_fail
Stephen Warren10e50632016-01-15 11:15:24 -0700739 break
740 if report.outcome == 'skipped':
Stephen Warren25b05242016-01-27 23:57:51 -0700741 if hasattr(report, 'wasxfail'):
742 failure_cleanup = True
743 test_list = tests_xfailed
744 msg = 'XFAILED:\n' + str(report.longrepr)
745 msg_log = log.status_xfail
746 break
747 test_list = tests_skipped
748 msg = 'SKIPPED:\n' + str(report.longrepr)
749 msg_log = log.status_skipped
Stephen Warren10e50632016-01-15 11:15:24 -0700750
Stephen Warren25b05242016-01-27 23:57:51 -0700751 if failure_cleanup:
Stephen Warren97a54662016-01-22 12:30:09 -0700752 console.drain_console()
Stephen Warren25b05242016-01-27 23:57:51 -0700753
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700754 test_list.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700755 tests_not_run.remove(item.name)
756
757 try:
Stephen Warren25b05242016-01-27 23:57:51 -0700758 msg_log(msg)
Stephen Warren10e50632016-01-15 11:15:24 -0700759 except:
760 # If something went wrong with logging, it's better to let the test
761 # process continue, which may report other exceptions that triggered
762 # the logging issue (e.g. console.log wasn't created). Hence, just
763 # squash the exception. If the test setup failed due to e.g. syntax
764 # error somewhere else, this won't be seen. However, once that issue
765 # is fixed, if this exception still exists, it will then be logged as
766 # part of the test's stdout.
767 import traceback
Paul Burton00f2d202017-09-14 14:34:43 -0700768 print('Exception occurred while logging runtest status:')
Stephen Warren10e50632016-01-15 11:15:24 -0700769 traceback.print_exc()
770 # FIXME: Can we force a test failure here?
771
772 log.end_section(item.name)
773
Stephen Warren25b05242016-01-27 23:57:51 -0700774 if failure_cleanup:
Stephen Warren10e50632016-01-15 11:15:24 -0700775 console.cleanup_spawn()
776
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700777 return True