blob: 509d19b449d6d9f7424cce3ff53922cbe33bb681 [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 Glass068f6a72024-12-11 06:18:58 -0700147
148 # The source tree must be the current directory
149 source_dir = os.path.dirname(os.path.dirname(TEST_PY_DIR))
Simon Glassf6dbc362024-11-12 07:13:18 -0700150 if role:
151 # When using a role, build_dir and build_dir_extra are normally not set,
152 # since they are picked up from Labgrid-sjg via the u-boot-test-getrole
153 # script
154 board_identity = role
155 cmd = ['u-boot-test-getrole', role, '--configure']
156 env = os.environ.copy()
157 if build_dir:
158 env['U_BOOT_BUILD_DIR'] = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700159 if build_dir_extra:
160 env['U_BOOT_BUILD_DIR_EXTRA'] = build_dir_extra
Simon Glassf6dbc362024-11-12 07:13:18 -0700161 proc = subprocess.run(cmd, capture_output=True, encoding='utf-8',
162 env=env)
163 if proc.returncode:
164 raise ValueError(proc.stderr)
165 # For debugging
166 # print('conftest: lab:', proc.stdout)
167 vals = {}
168 for line in proc.stdout.splitlines():
169 item, value = line.split(' ', maxsplit=1)
170 k = item.split(':')[-1]
171 vals[k] = value
172 # For debugging
173 # print('conftest: lab info:', vals)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700174
175 # Read the build directories here, in case none were provided in the
176 # command-line arguments
177 (board_type, board_type_extra, default_build_dir,
Simon Glass068f6a72024-12-11 06:18:58 -0700178 default_build_dir_extra) = (vals['board'],
179 vals['board_extra'], vals['build_dir'], vals['build_dir_extra'])
Simon Glassf6dbc362024-11-12 07:13:18 -0700180 else:
181 board_type = config.getoption('board_type')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700182 board_type_extra = config.getoption('board_type_extra')
Simon Glassf6dbc362024-11-12 07:13:18 -0700183 board_identity = config.getoption('board_identity')
Simon Glass35ad4322024-10-09 18:29:00 -0600184
Simon Glassf6dbc362024-11-12 07:13:18 -0700185 default_build_dir = source_dir + '/build-' + board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700186 default_build_dir_extra = source_dir + '/build-' + board_type_extra
187
188 # Use the provided command-line arguments if present, else fall back to
Simon Glass62b92f82022-08-06 17:51:57 -0600189 if not build_dir:
Simon Glass35ad4322024-10-09 18:29:00 -0600190 build_dir = default_build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700191 if not build_dir_extra:
192 build_dir_extra = default_build_dir_extra
Simon Glass35ad4322024-10-09 18:29:00 -0600193
Simon Glass5a63a4b2024-11-12 07:13:24 -0700194 return (board_type, board_type_extra, board_identity, build_dir,
195 build_dir_extra, source_dir)
Simon Glass35ad4322024-10-09 18:29:00 -0600196
197def pytest_xdist_setupnodes(config, specs):
198 """Clear out any 'done' file from a previous build"""
199 global build_done_file
200
Simon Glass5a63a4b2024-11-12 07:13:24 -0700201 build_dir = get_details(config)[3]
Simon Glass35ad4322024-10-09 18:29:00 -0600202
Simon Glass62b92f82022-08-06 17:51:57 -0600203 build_done_file = Path(build_dir) / 'build.done'
204 if build_done_file.exists():
205 os.remove(build_done_file)
206
Stephen Warren10e50632016-01-15 11:15:24 -0700207def pytest_configure(config):
Stephen Warren75e731e2016-01-26 13:41:30 -0700208 """pytest hook: Perform custom initialization at startup time.
Stephen Warren10e50632016-01-15 11:15:24 -0700209
210 Args:
211 config: The pytest configuration.
212
213 Returns:
214 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700215 """
Simon Glassde8e25b2019-12-01 19:34:18 -0700216 def parse_config(conf_file):
217 """Parse a config file, loading it into the ubconfig container
218
219 Args:
220 conf_file: Filename to load (within build_dir)
221
222 Raises
223 Exception if the file does not exist
224 """
225 dot_config = build_dir + '/' + conf_file
226 if not os.path.exists(dot_config):
227 raise Exception(conf_file + ' does not exist; ' +
228 'try passing --build option?')
229
230 with open(dot_config, 'rt') as f:
231 ini_str = '[root]\n' + f.read()
232 ini_sio = io.StringIO(ini_str)
233 parser = configparser.RawConfigParser()
234 parser.read_file(ini_sio)
235 ubconfig.buildconfig.update(parser.items('root'))
Stephen Warren10e50632016-01-15 11:15:24 -0700236
237 global log
238 global console
239 global ubconfig
240
Simon Glass5a63a4b2024-11-12 07:13:24 -0700241 (board_type, board_type_extra, board_identity, build_dir, build_dir_extra,
242 source_dir) = get_details(config)
Stephen Warren10e50632016-01-15 11:15:24 -0700243
Stephen Warren10e50632016-01-15 11:15:24 -0700244 board_type_filename = board_type.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700245 board_identity_filename = board_identity.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700246 mkdir_p(build_dir)
247
248 result_dir = config.getoption('result_dir')
249 if not result_dir:
250 result_dir = build_dir
251 mkdir_p(result_dir)
252
253 persistent_data_dir = config.getoption('persistent_data_dir')
254 if not persistent_data_dir:
255 persistent_data_dir = build_dir + '/persistent-data'
256 mkdir_p(persistent_data_dir)
257
Stephen Warren33db1ee2016-02-04 16:11:50 -0700258 gdbserver = config.getoption('gdbserver')
Igor Opaniukea5f17d2019-02-12 16:18:14 +0200259 if gdbserver and not board_type.startswith('sandbox'):
260 raise Exception('--gdbserver only supported with sandbox targets')
Stephen Warren33db1ee2016-02-04 16:11:50 -0700261
Stephen Warren10e50632016-01-15 11:15:24 -0700262 import multiplexed_log
263 log = multiplexed_log.Logfile(result_dir + '/test-log.html')
264
265 if config.getoption('build'):
Simon Glass62b92f82022-08-06 17:51:57 -0600266 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
267 with filelock.FileLock(os.path.join(build_dir, 'build.lock')):
268 build_done_file = Path(build_dir) / 'build.done'
269 if (not worker_id or worker_id == 'master' or
270 not build_done_file.exists()):
271 run_build(config, source_dir, build_dir, board_type, log)
272 build_done_file.touch()
Stephen Warren10e50632016-01-15 11:15:24 -0700273
274 class ArbitraryAttributeContainer(object):
275 pass
276
277 ubconfig = ArbitraryAttributeContainer()
278 ubconfig.brd = dict()
279 ubconfig.env = dict()
280
281 modules = [
282 (ubconfig.brd, 'u_boot_board_' + board_type_filename),
283 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
284 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
285 board_identity_filename),
286 ]
287 for (dict_to_fill, module_name) in modules:
288 try:
289 module = __import__(module_name)
290 except ImportError:
291 continue
292 dict_to_fill.update(module.__dict__)
293
294 ubconfig.buildconfig = dict()
295
Simon Glassde8e25b2019-12-01 19:34:18 -0700296 # buildman -k puts autoconf.mk in the rootdir, so handle this as well
297 # as the standard U-Boot build which leaves it in include/autoconf.mk
298 parse_config('.config')
299 if os.path.exists(build_dir + '/' + 'autoconf.mk'):
300 parse_config('autoconf.mk')
301 else:
302 parse_config('include/autoconf.mk')
Stephen Warren10e50632016-01-15 11:15:24 -0700303
Simon Glass62b92f82022-08-06 17:51:57 -0600304 ubconfig.test_py_dir = TEST_PY_DIR
Stephen Warren10e50632016-01-15 11:15:24 -0700305 ubconfig.source_dir = source_dir
306 ubconfig.build_dir = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700307 ubconfig.build_dir_extra = build_dir_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700308 ubconfig.result_dir = result_dir
309 ubconfig.persistent_data_dir = persistent_data_dir
310 ubconfig.board_type = board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700311 ubconfig.board_type_extra = board_type_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700312 ubconfig.board_identity = board_identity
Stephen Warren33db1ee2016-02-04 16:11:50 -0700313 ubconfig.gdbserver = gdbserver
Simon Glassf1b1bb82024-11-12 07:13:17 -0700314 ubconfig.use_running_system = config.getoption('use_running_system')
Simon Glass3b097872016-07-03 09:40:36 -0600315 ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
Simon Glassd834d9a2024-10-09 18:29:03 -0600316 ubconfig.connection_ok = True
Stephen Warren10e50632016-01-15 11:15:24 -0700317
318 env_vars = (
319 'board_type',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700320 'board_type_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700321 'board_identity',
322 'source_dir',
323 'test_py_dir',
324 'build_dir',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700325 'build_dir_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700326 'result_dir',
327 'persistent_data_dir',
328 )
329 for v in env_vars:
330 os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
331
Simon Glass13f422e2016-07-04 11:58:37 -0600332 if board_type.startswith('sandbox'):
Stephen Warren10e50632016-01-15 11:15:24 -0700333 import u_boot_console_sandbox
334 console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
335 else:
336 import u_boot_console_exec_attach
337 console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
338
Simon Glass23300b42021-10-23 17:26:11 -0600339re_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 -0600340def generate_ut_subtest(metafunc, fixture_name, sym_path):
Stephen Warren770fe172016-02-08 14:44:16 -0700341 """Provide parametrization for a ut_subtest fixture.
342
343 Determines the set of unit tests built into a U-Boot binary by parsing the
344 list of symbols generated by the build process. Provides this information
345 to test functions by parameterizing their ut_subtest fixture parameter.
346
347 Args:
348 metafunc: The pytest test function.
349 fixture_name: The fixture name to test.
Simon Glassed298be2020-10-25 20:38:31 -0600350 sym_path: Relative path to the symbol file with preceding '/'
351 (e.g. '/u-boot.sym')
Stephen Warren770fe172016-02-08 14:44:16 -0700352
353 Returns:
354 Nothing.
355 """
Simon Glassed298be2020-10-25 20:38:31 -0600356 fn = console.config.build_dir + sym_path
Stephen Warren770fe172016-02-08 14:44:16 -0700357 try:
358 with open(fn, 'rt') as f:
359 lines = f.readlines()
360 except:
361 lines = []
362 lines.sort()
363
364 vals = []
365 for l in lines:
366 m = re_ut_test_list.search(l)
367 if not m:
368 continue
Simon Glass1f1614b2022-10-20 18:22:50 -0600369 suite, name = m.groups()
370
371 # Tests marked with _norun should only be run manually using 'ut -f'
372 if name.endswith('_norun'):
373 continue
374
375 vals.append(f'{suite} {name}')
Stephen Warren770fe172016-02-08 14:44:16 -0700376
377 ids = ['ut_' + s.replace(' ', '_') for s in vals]
378 metafunc.parametrize(fixture_name, vals, ids=ids)
379
380def generate_config(metafunc, fixture_name):
381 """Provide parametrization for {env,brd}__ fixtures.
Stephen Warren10e50632016-01-15 11:15:24 -0700382
383 If a test function takes parameter(s) (fixture names) of the form brd__xxx
384 or env__xxx, the brd and env configuration dictionaries are consulted to
385 find the list of values to use for those parameters, and the test is
386 parametrized so that it runs once for each combination of values.
387
388 Args:
389 metafunc: The pytest test function.
Stephen Warren770fe172016-02-08 14:44:16 -0700390 fixture_name: The fixture name to test.
Stephen Warren10e50632016-01-15 11:15:24 -0700391
392 Returns:
393 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700394 """
Stephen Warren10e50632016-01-15 11:15:24 -0700395
396 subconfigs = {
397 'brd': console.config.brd,
398 'env': console.config.env,
399 }
Stephen Warren770fe172016-02-08 14:44:16 -0700400 parts = fixture_name.split('__')
401 if len(parts) < 2:
402 return
403 if parts[0] not in subconfigs:
404 return
405 subconfig = subconfigs[parts[0]]
406 vals = []
407 val = subconfig.get(fixture_name, [])
408 # If that exact name is a key in the data source:
409 if val:
410 # ... use the dict value as a single parameter value.
411 vals = (val, )
412 else:
413 # ... otherwise, see if there's a key that contains a list of
414 # values to use instead.
415 vals = subconfig.get(fixture_name+ 's', [])
416 def fixture_id(index, val):
417 try:
418 return val['fixture_id']
419 except:
420 return fixture_name + str(index)
421 ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
422 metafunc.parametrize(fixture_name, vals, ids=ids)
423
424def pytest_generate_tests(metafunc):
425 """pytest hook: parameterize test functions based on custom rules.
426
427 Check each test function parameter (fixture name) to see if it is one of
428 our custom names, and if so, provide the correct parametrization for that
429 parameter.
430
431 Args:
432 metafunc: The pytest test function.
433
434 Returns:
435 Nothing.
436 """
Stephen Warren10e50632016-01-15 11:15:24 -0700437 for fn in metafunc.fixturenames:
Stephen Warren770fe172016-02-08 14:44:16 -0700438 if fn == 'ut_subtest':
Simon Glassed298be2020-10-25 20:38:31 -0600439 generate_ut_subtest(metafunc, fn, '/u-boot.sym')
440 continue
Simon Glassb6c665f2022-04-30 00:56:55 -0600441 m_subtest = re.match('ut_(.)pl_subtest', fn)
442 if m_subtest:
443 spl_name = m_subtest.group(1)
444 generate_ut_subtest(
445 metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
Stephen Warren10e50632016-01-15 11:15:24 -0700446 continue
Stephen Warren770fe172016-02-08 14:44:16 -0700447 generate_config(metafunc, fn)
Stephen Warren10e50632016-01-15 11:15:24 -0700448
Stefan Brüns364ea872016-11-05 17:45:32 +0100449@pytest.fixture(scope='session')
450def u_boot_log(request):
451 """Generate the value of a test's log fixture.
452
453 Args:
454 request: The pytest request.
455
456 Returns:
457 The fixture value.
458 """
459
460 return console.log
461
462@pytest.fixture(scope='session')
463def u_boot_config(request):
464 """Generate the value of a test's u_boot_config fixture.
465
466 Args:
467 request: The pytest request.
468
469 Returns:
470 The fixture value.
471 """
472
473 return console.config
474
Stephen Warrene1d24d02016-01-22 12:30:08 -0700475@pytest.fixture(scope='function')
Stephen Warren10e50632016-01-15 11:15:24 -0700476def u_boot_console(request):
Stephen Warren75e731e2016-01-26 13:41:30 -0700477 """Generate the value of a test's u_boot_console fixture.
Stephen Warren10e50632016-01-15 11:15:24 -0700478
479 Args:
480 request: The pytest request.
481
482 Returns:
483 The fixture value.
Stephen Warren75e731e2016-01-26 13:41:30 -0700484 """
Simon Glassd834d9a2024-10-09 18:29:03 -0600485 if not ubconfig.connection_ok:
486 pytest.skip('Cannot get target connection')
487 return None
488 try:
489 console.ensure_spawned()
490 except OSError as err:
491 handle_exception(ubconfig, console, log, err, 'Lab failure', True)
492 except Timeout as err:
493 handle_exception(ubconfig, console, log, err, 'Lab timeout', True)
494 except BootFail as err:
495 handle_exception(ubconfig, console, log, err, 'Boot fail', True,
496 console.get_spawn_output())
497 except Unexpected:
498 handle_exception(ubconfig, console, log, err, 'Unexpected test output',
499 False)
Stephen Warren10e50632016-01-15 11:15:24 -0700500 return console
501
Stephen Warrene3f2a502016-02-03 16:46:34 -0700502anchors = {}
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700503tests_not_run = []
504tests_failed = []
505tests_xpassed = []
506tests_xfailed = []
507tests_skipped = []
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700508tests_warning = []
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700509tests_passed = []
Stephen Warren10e50632016-01-15 11:15:24 -0700510
511def pytest_itemcollected(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700512 """pytest hook: Called once for each test found during collection.
Stephen Warren10e50632016-01-15 11:15:24 -0700513
514 This enables our custom result analysis code to see the list of all tests
515 that should eventually be run.
516
517 Args:
518 item: The item that was collected.
519
520 Returns:
521 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700522 """
Stephen Warren10e50632016-01-15 11:15:24 -0700523
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700524 tests_not_run.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700525
526def cleanup():
Stephen Warren75e731e2016-01-26 13:41:30 -0700527 """Clean up all global state.
Stephen Warren10e50632016-01-15 11:15:24 -0700528
529 Executed (via atexit) once the entire test process is complete. This
530 includes logging the status of all tests, and the identity of any failed
531 or skipped tests.
532
533 Args:
534 None.
535
536 Returns:
537 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700538 """
Stephen Warren10e50632016-01-15 11:15:24 -0700539
540 if console:
541 console.close()
542 if log:
Stephen Warrene3f2a502016-02-03 16:46:34 -0700543 with log.section('Status Report', 'status_report'):
544 log.status_pass('%d passed' % len(tests_passed))
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700545 if tests_warning:
546 log.status_warning('%d passed with warning' % len(tests_warning))
547 for test in tests_warning:
548 anchor = anchors.get(test, None)
549 log.status_warning('... ' + test, anchor)
Stephen Warrene3f2a502016-02-03 16:46:34 -0700550 if tests_skipped:
551 log.status_skipped('%d skipped' % len(tests_skipped))
552 for test in tests_skipped:
553 anchor = anchors.get(test, None)
554 log.status_skipped('... ' + test, anchor)
555 if tests_xpassed:
556 log.status_xpass('%d xpass' % len(tests_xpassed))
557 for test in tests_xpassed:
558 anchor = anchors.get(test, None)
559 log.status_xpass('... ' + test, anchor)
560 if tests_xfailed:
561 log.status_xfail('%d xfail' % len(tests_xfailed))
562 for test in tests_xfailed:
563 anchor = anchors.get(test, None)
564 log.status_xfail('... ' + test, anchor)
565 if tests_failed:
566 log.status_fail('%d failed' % len(tests_failed))
567 for test in tests_failed:
568 anchor = anchors.get(test, None)
569 log.status_fail('... ' + test, anchor)
570 if tests_not_run:
571 log.status_fail('%d not run' % len(tests_not_run))
572 for test in tests_not_run:
573 anchor = anchors.get(test, None)
574 log.status_fail('... ' + test, anchor)
Stephen Warren10e50632016-01-15 11:15:24 -0700575 log.close()
576atexit.register(cleanup)
577
578def setup_boardspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700579 """Process any 'boardspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700580
581 Such a marker lists the set of board types that a test does/doesn't
582 support. If tests are being executed on an unsupported board, the test is
583 marked to be skipped.
584
585 Args:
586 item: The pytest test item.
587
588 Returns:
589 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700590 """
Stephen Warren10e50632016-01-15 11:15:24 -0700591
Stephen Warren10e50632016-01-15 11:15:24 -0700592 required_boards = []
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400593 for boards in item.iter_markers('boardspec'):
594 board = boards.args[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700595 if board.startswith('!'):
596 if ubconfig.board_type == board[1:]:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600597 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700598 return
599 else:
600 required_boards.append(board)
601 if required_boards and ubconfig.board_type not in required_boards:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600602 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700603
604def setup_buildconfigspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700605 """Process any 'buildconfigspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700606
607 Such a marker lists some U-Boot configuration feature that the test
608 requires. If tests are being executed on an U-Boot build that doesn't
609 have the required feature, the test is marked to be skipped.
610
611 Args:
612 item: The pytest test item.
613
614 Returns:
615 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700616 """
Stephen Warren10e50632016-01-15 11:15:24 -0700617
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400618 for options in item.iter_markers('buildconfigspec'):
619 option = options.args[0]
620 if not ubconfig.buildconfig.get('config_' + option.lower(), None):
621 pytest.skip('.config feature "%s" not enabled' % option.lower())
Cristian Ciocaltea6c6c8072019-12-24 17:19:12 +0200622 for options in item.iter_markers('notbuildconfigspec'):
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400623 option = options.args[0]
624 if ubconfig.buildconfig.get('config_' + option.lower(), None):
625 pytest.skip('.config feature "%s" enabled' % option.lower())
Stephen Warren10e50632016-01-15 11:15:24 -0700626
Stephen Warren2079db32017-09-18 11:11:49 -0600627def tool_is_in_path(tool):
628 for path in os.environ["PATH"].split(os.pathsep):
629 fn = os.path.join(path, tool)
630 if os.path.isfile(fn) and os.access(fn, os.X_OK):
631 return True
632 return False
633
634def setup_requiredtool(item):
635 """Process any 'requiredtool' marker for a test.
636
637 Such a marker lists some external tool (binary, executable, application)
638 that the test requires. If tests are being executed on a system that
639 doesn't have the required tool, the test is marked to be skipped.
640
641 Args:
642 item: The pytest test item.
643
644 Returns:
645 Nothing.
646 """
647
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400648 for tools in item.iter_markers('requiredtool'):
649 tool = tools.args[0]
Stephen Warren2079db32017-09-18 11:11:49 -0600650 if not tool_is_in_path(tool):
651 pytest.skip('tool "%s" not in $PATH' % tool)
652
Simon Glass54ef2ca2022-08-06 17:51:47 -0600653def setup_singlethread(item):
654 """Process any 'singlethread' marker for a test.
655
656 Skip this test if running in parallel.
657
658 Args:
659 item: The pytest test item.
660
661 Returns:
662 Nothing.
663 """
664 for single in item.iter_markers('singlethread'):
665 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
666 if worker_id and worker_id != 'master':
667 pytest.skip('must run single-threaded')
668
Stephen Warren3e3d1432016-10-17 17:25:52 -0600669def start_test_section(item):
670 anchors[item.name] = log.start_section(item.name)
671
Stephen Warren10e50632016-01-15 11:15:24 -0700672def pytest_runtest_setup(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700673 """pytest hook: Configure (set up) a test item.
Stephen Warren10e50632016-01-15 11:15:24 -0700674
675 Called once for each test to perform any custom configuration. This hook
676 is used to skip the test if certain conditions apply.
677
678 Args:
679 item: The pytest test item.
680
681 Returns:
682 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700683 """
Stephen Warren10e50632016-01-15 11:15:24 -0700684
Stephen Warren3e3d1432016-10-17 17:25:52 -0600685 start_test_section(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700686 setup_boardspec(item)
687 setup_buildconfigspec(item)
Stephen Warren2079db32017-09-18 11:11:49 -0600688 setup_requiredtool(item)
Simon Glass54ef2ca2022-08-06 17:51:47 -0600689 setup_singlethread(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700690
691def pytest_runtest_protocol(item, nextitem):
Stephen Warren75e731e2016-01-26 13:41:30 -0700692 """pytest hook: Called to execute a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700693
694 This hook wraps the standard pytest runtestprotocol() function in order
695 to acquire visibility into, and record, each test function's result.
696
697 Args:
698 item: The pytest test item to execute.
699 nextitem: The pytest test item that will be executed after this one.
700
701 Returns:
702 A list of pytest reports (test result data).
Stephen Warren75e731e2016-01-26 13:41:30 -0700703 """
Stephen Warren10e50632016-01-15 11:15:24 -0700704
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700705 log.get_and_reset_warning()
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700706 ihook = item.ihook
707 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
Stephen Warren10e50632016-01-15 11:15:24 -0700708 reports = runtestprotocol(item, nextitem=nextitem)
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700709 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700710 was_warning = log.get_and_reset_warning()
Stephen Warren25b05242016-01-27 23:57:51 -0700711
Stephen Warren3e3d1432016-10-17 17:25:52 -0600712 # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
713 # the test is skipped. That call is required to create the test's section
714 # in the log file. The call to log.end_section() requires that the log
715 # contain a section for this test. Create a section for the test if it
716 # doesn't already exist.
717 if not item.name in anchors:
718 start_test_section(item)
719
Stephen Warren25b05242016-01-27 23:57:51 -0700720 failure_cleanup = False
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700721 if not was_warning:
722 test_list = tests_passed
723 msg = 'OK'
724 msg_log = log.status_pass
725 else:
726 test_list = tests_warning
727 msg = 'OK (with warning)'
728 msg_log = log.status_warning
Stephen Warren10e50632016-01-15 11:15:24 -0700729 for report in reports:
730 if report.outcome == 'failed':
Stephen Warren25b05242016-01-27 23:57:51 -0700731 if hasattr(report, 'wasxfail'):
732 test_list = tests_xpassed
733 msg = 'XPASSED'
734 msg_log = log.status_xpass
735 else:
736 failure_cleanup = True
737 test_list = tests_failed
738 msg = 'FAILED:\n' + str(report.longrepr)
739 msg_log = log.status_fail
Stephen Warren10e50632016-01-15 11:15:24 -0700740 break
741 if report.outcome == 'skipped':
Stephen Warren25b05242016-01-27 23:57:51 -0700742 if hasattr(report, 'wasxfail'):
743 failure_cleanup = True
744 test_list = tests_xfailed
745 msg = 'XFAILED:\n' + str(report.longrepr)
746 msg_log = log.status_xfail
747 break
748 test_list = tests_skipped
749 msg = 'SKIPPED:\n' + str(report.longrepr)
750 msg_log = log.status_skipped
Stephen Warren10e50632016-01-15 11:15:24 -0700751
Stephen Warren25b05242016-01-27 23:57:51 -0700752 if failure_cleanup:
Stephen Warren97a54662016-01-22 12:30:09 -0700753 console.drain_console()
Stephen Warren25b05242016-01-27 23:57:51 -0700754
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700755 test_list.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700756 tests_not_run.remove(item.name)
757
758 try:
Stephen Warren25b05242016-01-27 23:57:51 -0700759 msg_log(msg)
Stephen Warren10e50632016-01-15 11:15:24 -0700760 except:
761 # If something went wrong with logging, it's better to let the test
762 # process continue, which may report other exceptions that triggered
763 # the logging issue (e.g. console.log wasn't created). Hence, just
764 # squash the exception. If the test setup failed due to e.g. syntax
765 # error somewhere else, this won't be seen. However, once that issue
766 # is fixed, if this exception still exists, it will then be logged as
767 # part of the test's stdout.
768 import traceback
Paul Burton00f2d202017-09-14 14:34:43 -0700769 print('Exception occurred while logging runtest status:')
Stephen Warren10e50632016-01-15 11:15:24 -0700770 traceback.print_exc()
771 # FIXME: Can we force a test failure here?
772
773 log.end_section(item.name)
774
Stephen Warren25b05242016-01-27 23:57:51 -0700775 if failure_cleanup:
Stephen Warren10e50632016-01-15 11:15:24 -0700776 console.cleanup_spawn()
777
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700778 return True