blob: 44b22761a8b209f1c1c63a67de8b51e299e726c7 [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
Simon Glassb15512c2025-01-20 14:25:32 -070036# Regex for test-function symbols
37RE_UT_TEST_LIST = re.compile(r'[^a-zA-Z0-9_]_u_boot_list_2_ut_(.*)_2_(.*)\s*$')
38
Stephen Warren10e50632016-01-15 11:15:24 -070039def mkdir_p(path):
Stephen Warren75e731e2016-01-26 13:41:30 -070040 """Create a directory path.
Stephen Warren10e50632016-01-15 11:15:24 -070041
42 This includes creating any intermediate/parent directories. Any errors
43 caused due to already extant directories are ignored.
44
45 Args:
46 path: The directory path to create.
47
48 Returns:
49 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070050 """
Stephen Warren10e50632016-01-15 11:15:24 -070051
52 try:
53 os.makedirs(path)
54 except OSError as exc:
55 if exc.errno == errno.EEXIST and os.path.isdir(path):
56 pass
57 else:
58 raise
59
60def pytest_addoption(parser):
Stephen Warren75e731e2016-01-26 13:41:30 -070061 """pytest hook: Add custom command-line options to the cmdline parser.
Stephen Warren10e50632016-01-15 11:15:24 -070062
63 Args:
64 parser: The pytest command-line parser.
65
66 Returns:
67 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -070068 """
Stephen Warren10e50632016-01-15 11:15:24 -070069
70 parser.addoption('--build-dir', default=None,
71 help='U-Boot build directory (O=)')
Simon Glass5a63a4b2024-11-12 07:13:24 -070072 parser.addoption('--build-dir-extra', default=None,
73 help='U-Boot build directory for extra build (O=)')
Stephen Warren10e50632016-01-15 11:15:24 -070074 parser.addoption('--result-dir', default=None,
75 help='U-Boot test result/tmp directory')
76 parser.addoption('--persistent-data-dir', default=None,
77 help='U-Boot test persistent generated data directory')
78 parser.addoption('--board-type', '--bd', '-B', default='sandbox',
79 help='U-Boot board type')
Simon Glass5a63a4b2024-11-12 07:13:24 -070080 parser.addoption('--board-type-extra', '--bde', default='sandbox',
81 help='U-Boot extra board type')
Stephen Warren10e50632016-01-15 11:15:24 -070082 parser.addoption('--board-identity', '--id', default='na',
83 help='U-Boot board identity/instance')
84 parser.addoption('--build', default=False, action='store_true',
85 help='Compile U-Boot before running tests')
Simon Glass6e094842020-03-18 09:43:01 -060086 parser.addoption('--buildman', default=False, action='store_true',
87 help='Use buildman to build U-Boot (assuming --build is given)')
Stephen Warren33db1ee2016-02-04 16:11:50 -070088 parser.addoption('--gdbserver', default=None,
89 help='Run sandbox under gdbserver. The argument is the channel '+
90 'over which gdbserver should communicate, e.g. localhost:1234')
Simon Glassf6dbc362024-11-12 07:13:18 -070091 parser.addoption('--role', help='U-Boot board role (for Labgrid-sjg)')
Simon Glassf1b1bb82024-11-12 07:13:17 -070092 parser.addoption('--use-running-system', default=False, action='store_true',
93 help="Assume that U-Boot is ready and don't wait for a prompt")
Stephen Warren10e50632016-01-15 11:15:24 -070094
Simon Glass686fad72022-08-06 17:51:56 -060095def run_build(config, source_dir, build_dir, board_type, log):
96 """run_build: Build U-Boot
97
98 Args:
99 config: The pytest configuration.
100 soruce_dir (str): Directory containing source code
101 build_dir (str): Directory to build in
102 board_type (str): board_type parameter (e.g. 'sandbox')
103 log (Logfile): Log file to use
104 """
105 if config.getoption('buildman'):
106 if build_dir != source_dir:
107 dest_args = ['-o', build_dir, '-w']
108 else:
109 dest_args = ['-i']
110 cmds = (['buildman', '--board', board_type] + dest_args,)
111 name = 'buildman'
112 else:
113 if build_dir != source_dir:
114 o_opt = 'O=%s' % build_dir
115 else:
116 o_opt = ''
117 cmds = (
118 ['make', o_opt, '-s', board_type + '_defconfig'],
119 ['make', o_opt, '-s', '-j{}'.format(os.cpu_count())],
120 )
121 name = 'make'
122
123 with log.section(name):
124 runner = log.get_runner(name, sys.stdout)
125 for cmd in cmds:
126 runner.run(cmd, cwd=source_dir)
127 runner.close()
128 log.status_pass('OK')
129
Simon Glass35ad4322024-10-09 18:29:00 -0600130def get_details(config):
131 """Obtain salient details about the board and directories to use
132
133 Args:
134 config (pytest.Config): pytest configuration
135
136 Returns:
137 tuple:
138 str: Board type (U-Boot build name)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700139 str: Extra board type (where two U-Boot builds are needed)
Simon Glass35ad4322024-10-09 18:29:00 -0600140 str: Identity for the lab board
141 str: Build directory
Simon Glass5a63a4b2024-11-12 07:13:24 -0700142 str: Extra build directory (where two U-Boot builds are needed)
Simon Glass35ad4322024-10-09 18:29:00 -0600143 str: Source directory
144 """
Simon Glassf6dbc362024-11-12 07:13:18 -0700145 role = config.getoption('role')
146
147 # Get a few provided parameters
Simon Glass35ad4322024-10-09 18:29:00 -0600148 build_dir = config.getoption('build_dir')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700149 build_dir_extra = config.getoption('build_dir_extra')
Simon Glass068f6a72024-12-11 06:18:58 -0700150
151 # The source tree must be the current directory
152 source_dir = os.path.dirname(os.path.dirname(TEST_PY_DIR))
Simon Glassf6dbc362024-11-12 07:13:18 -0700153 if role:
154 # When using a role, build_dir and build_dir_extra are normally not set,
155 # since they are picked up from Labgrid-sjg via the u-boot-test-getrole
156 # script
157 board_identity = role
158 cmd = ['u-boot-test-getrole', role, '--configure']
159 env = os.environ.copy()
160 if build_dir:
161 env['U_BOOT_BUILD_DIR'] = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700162 if build_dir_extra:
163 env['U_BOOT_BUILD_DIR_EXTRA'] = build_dir_extra
Simon Glass97fb3452024-12-14 11:20:20 -0700164
165 # Make sure the script sees that it is being run from pytest
166 env['U_BOOT_SOURCE_DIR'] = source_dir
167
Simon Glassf6dbc362024-11-12 07:13:18 -0700168 proc = subprocess.run(cmd, capture_output=True, encoding='utf-8',
169 env=env)
170 if proc.returncode:
171 raise ValueError(proc.stderr)
172 # For debugging
173 # print('conftest: lab:', proc.stdout)
174 vals = {}
175 for line in proc.stdout.splitlines():
176 item, value = line.split(' ', maxsplit=1)
177 k = item.split(':')[-1]
178 vals[k] = value
179 # For debugging
180 # print('conftest: lab info:', vals)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700181
182 # Read the build directories here, in case none were provided in the
183 # command-line arguments
184 (board_type, board_type_extra, default_build_dir,
Simon Glass068f6a72024-12-11 06:18:58 -0700185 default_build_dir_extra) = (vals['board'],
186 vals['board_extra'], vals['build_dir'], vals['build_dir_extra'])
Simon Glassf6dbc362024-11-12 07:13:18 -0700187 else:
188 board_type = config.getoption('board_type')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700189 board_type_extra = config.getoption('board_type_extra')
Simon Glassf6dbc362024-11-12 07:13:18 -0700190 board_identity = config.getoption('board_identity')
Simon Glass35ad4322024-10-09 18:29:00 -0600191
Simon Glassf6dbc362024-11-12 07:13:18 -0700192 default_build_dir = source_dir + '/build-' + board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700193 default_build_dir_extra = source_dir + '/build-' + board_type_extra
194
195 # Use the provided command-line arguments if present, else fall back to
Simon Glass62b92f82022-08-06 17:51:57 -0600196 if not build_dir:
Simon Glass35ad4322024-10-09 18:29:00 -0600197 build_dir = default_build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700198 if not build_dir_extra:
199 build_dir_extra = default_build_dir_extra
Simon Glass35ad4322024-10-09 18:29:00 -0600200
Simon Glass5a63a4b2024-11-12 07:13:24 -0700201 return (board_type, board_type_extra, board_identity, build_dir,
202 build_dir_extra, source_dir)
Simon Glass35ad4322024-10-09 18:29:00 -0600203
204def pytest_xdist_setupnodes(config, specs):
205 """Clear out any 'done' file from a previous build"""
206 global build_done_file
207
Simon Glass5a63a4b2024-11-12 07:13:24 -0700208 build_dir = get_details(config)[3]
Simon Glass35ad4322024-10-09 18:29:00 -0600209
Simon Glass62b92f82022-08-06 17:51:57 -0600210 build_done_file = Path(build_dir) / 'build.done'
211 if build_done_file.exists():
212 os.remove(build_done_file)
213
Stephen Warren10e50632016-01-15 11:15:24 -0700214def pytest_configure(config):
Stephen Warren75e731e2016-01-26 13:41:30 -0700215 """pytest hook: Perform custom initialization at startup time.
Stephen Warren10e50632016-01-15 11:15:24 -0700216
217 Args:
218 config: The pytest configuration.
219
220 Returns:
221 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700222 """
Simon Glassde8e25b2019-12-01 19:34:18 -0700223 def parse_config(conf_file):
224 """Parse a config file, loading it into the ubconfig container
225
226 Args:
227 conf_file: Filename to load (within build_dir)
228
229 Raises
230 Exception if the file does not exist
231 """
232 dot_config = build_dir + '/' + conf_file
233 if not os.path.exists(dot_config):
234 raise Exception(conf_file + ' does not exist; ' +
235 'try passing --build option?')
236
237 with open(dot_config, 'rt') as f:
238 ini_str = '[root]\n' + f.read()
239 ini_sio = io.StringIO(ini_str)
240 parser = configparser.RawConfigParser()
241 parser.read_file(ini_sio)
242 ubconfig.buildconfig.update(parser.items('root'))
Stephen Warren10e50632016-01-15 11:15:24 -0700243
244 global log
245 global console
246 global ubconfig
247
Simon Glass5a63a4b2024-11-12 07:13:24 -0700248 (board_type, board_type_extra, board_identity, build_dir, build_dir_extra,
249 source_dir) = get_details(config)
Stephen Warren10e50632016-01-15 11:15:24 -0700250
Stephen Warren10e50632016-01-15 11:15:24 -0700251 board_type_filename = board_type.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700252 board_identity_filename = board_identity.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700253 mkdir_p(build_dir)
254
255 result_dir = config.getoption('result_dir')
256 if not result_dir:
257 result_dir = build_dir
258 mkdir_p(result_dir)
259
260 persistent_data_dir = config.getoption('persistent_data_dir')
261 if not persistent_data_dir:
262 persistent_data_dir = build_dir + '/persistent-data'
263 mkdir_p(persistent_data_dir)
264
Stephen Warren33db1ee2016-02-04 16:11:50 -0700265 gdbserver = config.getoption('gdbserver')
Igor Opaniukea5f17d2019-02-12 16:18:14 +0200266 if gdbserver and not board_type.startswith('sandbox'):
267 raise Exception('--gdbserver only supported with sandbox targets')
Stephen Warren33db1ee2016-02-04 16:11:50 -0700268
Stephen Warren10e50632016-01-15 11:15:24 -0700269 import multiplexed_log
270 log = multiplexed_log.Logfile(result_dir + '/test-log.html')
271
272 if config.getoption('build'):
Simon Glass62b92f82022-08-06 17:51:57 -0600273 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
274 with filelock.FileLock(os.path.join(build_dir, 'build.lock')):
275 build_done_file = Path(build_dir) / 'build.done'
276 if (not worker_id or worker_id == 'master' or
277 not build_done_file.exists()):
278 run_build(config, source_dir, build_dir, board_type, log)
279 build_done_file.touch()
Stephen Warren10e50632016-01-15 11:15:24 -0700280
281 class ArbitraryAttributeContainer(object):
282 pass
283
284 ubconfig = ArbitraryAttributeContainer()
285 ubconfig.brd = dict()
286 ubconfig.env = dict()
287
288 modules = [
289 (ubconfig.brd, 'u_boot_board_' + board_type_filename),
290 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
291 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
292 board_identity_filename),
293 ]
294 for (dict_to_fill, module_name) in modules:
295 try:
296 module = __import__(module_name)
297 except ImportError:
298 continue
299 dict_to_fill.update(module.__dict__)
300
301 ubconfig.buildconfig = dict()
302
Simon Glassde8e25b2019-12-01 19:34:18 -0700303 # buildman -k puts autoconf.mk in the rootdir, so handle this as well
304 # as the standard U-Boot build which leaves it in include/autoconf.mk
305 parse_config('.config')
306 if os.path.exists(build_dir + '/' + 'autoconf.mk'):
307 parse_config('autoconf.mk')
308 else:
309 parse_config('include/autoconf.mk')
Stephen Warren10e50632016-01-15 11:15:24 -0700310
Simon Glass62b92f82022-08-06 17:51:57 -0600311 ubconfig.test_py_dir = TEST_PY_DIR
Stephen Warren10e50632016-01-15 11:15:24 -0700312 ubconfig.source_dir = source_dir
313 ubconfig.build_dir = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700314 ubconfig.build_dir_extra = build_dir_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700315 ubconfig.result_dir = result_dir
316 ubconfig.persistent_data_dir = persistent_data_dir
317 ubconfig.board_type = board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700318 ubconfig.board_type_extra = board_type_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700319 ubconfig.board_identity = board_identity
Stephen Warren33db1ee2016-02-04 16:11:50 -0700320 ubconfig.gdbserver = gdbserver
Simon Glassf1b1bb82024-11-12 07:13:17 -0700321 ubconfig.use_running_system = config.getoption('use_running_system')
Simon Glass3b097872016-07-03 09:40:36 -0600322 ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
Simon Glassd834d9a2024-10-09 18:29:03 -0600323 ubconfig.connection_ok = True
Stephen Warren10e50632016-01-15 11:15:24 -0700324
325 env_vars = (
326 'board_type',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700327 'board_type_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700328 'board_identity',
329 'source_dir',
330 'test_py_dir',
331 'build_dir',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700332 'build_dir_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700333 'result_dir',
334 'persistent_data_dir',
335 )
336 for v in env_vars:
337 os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
338
Simon Glass13f422e2016-07-04 11:58:37 -0600339 if board_type.startswith('sandbox'):
Stephen Warren10e50632016-01-15 11:15:24 -0700340 import u_boot_console_sandbox
341 console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
342 else:
343 import u_boot_console_exec_attach
344 console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
345
Simon Glassb15512c2025-01-20 14:25:32 -0700346
Simon Glassed298be2020-10-25 20:38:31 -0600347def generate_ut_subtest(metafunc, fixture_name, sym_path):
Stephen Warren770fe172016-02-08 14:44:16 -0700348 """Provide parametrization for a ut_subtest fixture.
349
350 Determines the set of unit tests built into a U-Boot binary by parsing the
351 list of symbols generated by the build process. Provides this information
352 to test functions by parameterizing their ut_subtest fixture parameter.
353
354 Args:
355 metafunc: The pytest test function.
356 fixture_name: The fixture name to test.
Simon Glassed298be2020-10-25 20:38:31 -0600357 sym_path: Relative path to the symbol file with preceding '/'
358 (e.g. '/u-boot.sym')
Stephen Warren770fe172016-02-08 14:44:16 -0700359
360 Returns:
361 Nothing.
362 """
Simon Glassed298be2020-10-25 20:38:31 -0600363 fn = console.config.build_dir + sym_path
Stephen Warren770fe172016-02-08 14:44:16 -0700364 try:
365 with open(fn, 'rt') as f:
366 lines = f.readlines()
367 except:
368 lines = []
369 lines.sort()
370
371 vals = []
372 for l in lines:
Simon Glassb15512c2025-01-20 14:25:32 -0700373 m = RE_UT_TEST_LIST.search(l)
Stephen Warren770fe172016-02-08 14:44:16 -0700374 if not m:
375 continue
Simon Glass1f1614b2022-10-20 18:22:50 -0600376 suite, name = m.groups()
377
378 # Tests marked with _norun should only be run manually using 'ut -f'
379 if name.endswith('_norun'):
380 continue
381
382 vals.append(f'{suite} {name}')
Stephen Warren770fe172016-02-08 14:44:16 -0700383
384 ids = ['ut_' + s.replace(' ', '_') for s in vals]
385 metafunc.parametrize(fixture_name, vals, ids=ids)
386
387def generate_config(metafunc, fixture_name):
388 """Provide parametrization for {env,brd}__ fixtures.
Stephen Warren10e50632016-01-15 11:15:24 -0700389
390 If a test function takes parameter(s) (fixture names) of the form brd__xxx
391 or env__xxx, the brd and env configuration dictionaries are consulted to
392 find the list of values to use for those parameters, and the test is
393 parametrized so that it runs once for each combination of values.
394
395 Args:
396 metafunc: The pytest test function.
Stephen Warren770fe172016-02-08 14:44:16 -0700397 fixture_name: The fixture name to test.
Stephen Warren10e50632016-01-15 11:15:24 -0700398
399 Returns:
400 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700401 """
Stephen Warren10e50632016-01-15 11:15:24 -0700402
403 subconfigs = {
404 'brd': console.config.brd,
405 'env': console.config.env,
406 }
Stephen Warren770fe172016-02-08 14:44:16 -0700407 parts = fixture_name.split('__')
408 if len(parts) < 2:
409 return
410 if parts[0] not in subconfigs:
411 return
412 subconfig = subconfigs[parts[0]]
413 vals = []
414 val = subconfig.get(fixture_name, [])
415 # If that exact name is a key in the data source:
416 if val:
417 # ... use the dict value as a single parameter value.
418 vals = (val, )
419 else:
420 # ... otherwise, see if there's a key that contains a list of
421 # values to use instead.
422 vals = subconfig.get(fixture_name+ 's', [])
423 def fixture_id(index, val):
424 try:
425 return val['fixture_id']
426 except:
427 return fixture_name + str(index)
428 ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
429 metafunc.parametrize(fixture_name, vals, ids=ids)
430
431def pytest_generate_tests(metafunc):
432 """pytest hook: parameterize test functions based on custom rules.
433
434 Check each test function parameter (fixture name) to see if it is one of
435 our custom names, and if so, provide the correct parametrization for that
436 parameter.
437
438 Args:
439 metafunc: The pytest test function.
440
441 Returns:
442 Nothing.
443 """
Stephen Warren10e50632016-01-15 11:15:24 -0700444 for fn in metafunc.fixturenames:
Stephen Warren770fe172016-02-08 14:44:16 -0700445 if fn == 'ut_subtest':
Simon Glassed298be2020-10-25 20:38:31 -0600446 generate_ut_subtest(metafunc, fn, '/u-boot.sym')
447 continue
Simon Glassb6c665f2022-04-30 00:56:55 -0600448 m_subtest = re.match('ut_(.)pl_subtest', fn)
449 if m_subtest:
450 spl_name = m_subtest.group(1)
451 generate_ut_subtest(
452 metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
Stephen Warren10e50632016-01-15 11:15:24 -0700453 continue
Stephen Warren770fe172016-02-08 14:44:16 -0700454 generate_config(metafunc, fn)
Stephen Warren10e50632016-01-15 11:15:24 -0700455
Stefan Brüns364ea872016-11-05 17:45:32 +0100456@pytest.fixture(scope='session')
457def u_boot_log(request):
458 """Generate the value of a test's log fixture.
459
460 Args:
461 request: The pytest request.
462
463 Returns:
464 The fixture value.
465 """
466
467 return console.log
468
469@pytest.fixture(scope='session')
470def u_boot_config(request):
471 """Generate the value of a test's u_boot_config fixture.
472
473 Args:
474 request: The pytest request.
475
476 Returns:
477 The fixture value.
478 """
479
480 return console.config
481
Stephen Warrene1d24d02016-01-22 12:30:08 -0700482@pytest.fixture(scope='function')
Stephen Warren10e50632016-01-15 11:15:24 -0700483def u_boot_console(request):
Stephen Warren75e731e2016-01-26 13:41:30 -0700484 """Generate the value of a test's u_boot_console fixture.
Stephen Warren10e50632016-01-15 11:15:24 -0700485
486 Args:
487 request: The pytest request.
488
489 Returns:
490 The fixture value.
Stephen Warren75e731e2016-01-26 13:41:30 -0700491 """
Simon Glassd834d9a2024-10-09 18:29:03 -0600492 if not ubconfig.connection_ok:
493 pytest.skip('Cannot get target connection')
494 return None
495 try:
496 console.ensure_spawned()
497 except OSError as err:
498 handle_exception(ubconfig, console, log, err, 'Lab failure', True)
499 except Timeout as err:
500 handle_exception(ubconfig, console, log, err, 'Lab timeout', True)
501 except BootFail as err:
502 handle_exception(ubconfig, console, log, err, 'Boot fail', True,
503 console.get_spawn_output())
504 except Unexpected:
505 handle_exception(ubconfig, console, log, err, 'Unexpected test output',
506 False)
Stephen Warren10e50632016-01-15 11:15:24 -0700507 return console
508
Stephen Warrene3f2a502016-02-03 16:46:34 -0700509anchors = {}
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700510tests_not_run = []
511tests_failed = []
512tests_xpassed = []
513tests_xfailed = []
514tests_skipped = []
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700515tests_warning = []
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700516tests_passed = []
Stephen Warren10e50632016-01-15 11:15:24 -0700517
518def pytest_itemcollected(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700519 """pytest hook: Called once for each test found during collection.
Stephen Warren10e50632016-01-15 11:15:24 -0700520
521 This enables our custom result analysis code to see the list of all tests
522 that should eventually be run.
523
524 Args:
525 item: The item that was collected.
526
527 Returns:
528 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700529 """
Stephen Warren10e50632016-01-15 11:15:24 -0700530
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700531 tests_not_run.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700532
533def cleanup():
Stephen Warren75e731e2016-01-26 13:41:30 -0700534 """Clean up all global state.
Stephen Warren10e50632016-01-15 11:15:24 -0700535
536 Executed (via atexit) once the entire test process is complete. This
537 includes logging the status of all tests, and the identity of any failed
538 or skipped tests.
539
540 Args:
541 None.
542
543 Returns:
544 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700545 """
Stephen Warren10e50632016-01-15 11:15:24 -0700546
547 if console:
548 console.close()
549 if log:
Stephen Warrene3f2a502016-02-03 16:46:34 -0700550 with log.section('Status Report', 'status_report'):
551 log.status_pass('%d passed' % len(tests_passed))
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700552 if tests_warning:
553 log.status_warning('%d passed with warning' % len(tests_warning))
554 for test in tests_warning:
555 anchor = anchors.get(test, None)
556 log.status_warning('... ' + test, anchor)
Stephen Warrene3f2a502016-02-03 16:46:34 -0700557 if tests_skipped:
558 log.status_skipped('%d skipped' % len(tests_skipped))
559 for test in tests_skipped:
560 anchor = anchors.get(test, None)
561 log.status_skipped('... ' + test, anchor)
562 if tests_xpassed:
563 log.status_xpass('%d xpass' % len(tests_xpassed))
564 for test in tests_xpassed:
565 anchor = anchors.get(test, None)
566 log.status_xpass('... ' + test, anchor)
567 if tests_xfailed:
568 log.status_xfail('%d xfail' % len(tests_xfailed))
569 for test in tests_xfailed:
570 anchor = anchors.get(test, None)
571 log.status_xfail('... ' + test, anchor)
572 if tests_failed:
573 log.status_fail('%d failed' % len(tests_failed))
574 for test in tests_failed:
575 anchor = anchors.get(test, None)
576 log.status_fail('... ' + test, anchor)
577 if tests_not_run:
578 log.status_fail('%d not run' % len(tests_not_run))
579 for test in tests_not_run:
580 anchor = anchors.get(test, None)
581 log.status_fail('... ' + test, anchor)
Stephen Warren10e50632016-01-15 11:15:24 -0700582 log.close()
583atexit.register(cleanup)
584
585def setup_boardspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700586 """Process any 'boardspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700587
588 Such a marker lists the set of board types that a test does/doesn't
589 support. If tests are being executed on an unsupported board, the test is
590 marked to be skipped.
591
592 Args:
593 item: The pytest test item.
594
595 Returns:
596 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700597 """
Stephen Warren10e50632016-01-15 11:15:24 -0700598
Stephen Warren10e50632016-01-15 11:15:24 -0700599 required_boards = []
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400600 for boards in item.iter_markers('boardspec'):
601 board = boards.args[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700602 if board.startswith('!'):
603 if ubconfig.board_type == board[1:]:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600604 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700605 return
606 else:
607 required_boards.append(board)
608 if required_boards and ubconfig.board_type not in required_boards:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600609 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700610
611def setup_buildconfigspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700612 """Process any 'buildconfigspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700613
614 Such a marker lists some U-Boot configuration feature that the test
615 requires. If tests are being executed on an U-Boot build that doesn't
616 have the required feature, the test is marked to be skipped.
617
618 Args:
619 item: The pytest test item.
620
621 Returns:
622 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700623 """
Stephen Warren10e50632016-01-15 11:15:24 -0700624
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400625 for options in item.iter_markers('buildconfigspec'):
626 option = options.args[0]
627 if not ubconfig.buildconfig.get('config_' + option.lower(), None):
628 pytest.skip('.config feature "%s" not enabled' % option.lower())
Cristian Ciocaltea6c6c8072019-12-24 17:19:12 +0200629 for options in item.iter_markers('notbuildconfigspec'):
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400630 option = options.args[0]
631 if ubconfig.buildconfig.get('config_' + option.lower(), None):
632 pytest.skip('.config feature "%s" enabled' % option.lower())
Stephen Warren10e50632016-01-15 11:15:24 -0700633
Stephen Warren2079db32017-09-18 11:11:49 -0600634def tool_is_in_path(tool):
635 for path in os.environ["PATH"].split(os.pathsep):
636 fn = os.path.join(path, tool)
637 if os.path.isfile(fn) and os.access(fn, os.X_OK):
638 return True
639 return False
640
641def setup_requiredtool(item):
642 """Process any 'requiredtool' marker for a test.
643
644 Such a marker lists some external tool (binary, executable, application)
645 that the test requires. If tests are being executed on a system that
646 doesn't have the required tool, the test is marked to be skipped.
647
648 Args:
649 item: The pytest test item.
650
651 Returns:
652 Nothing.
653 """
654
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400655 for tools in item.iter_markers('requiredtool'):
656 tool = tools.args[0]
Stephen Warren2079db32017-09-18 11:11:49 -0600657 if not tool_is_in_path(tool):
658 pytest.skip('tool "%s" not in $PATH' % tool)
659
Simon Glass54ef2ca2022-08-06 17:51:47 -0600660def setup_singlethread(item):
661 """Process any 'singlethread' marker for a test.
662
663 Skip this test if running in parallel.
664
665 Args:
666 item: The pytest test item.
667
668 Returns:
669 Nothing.
670 """
671 for single in item.iter_markers('singlethread'):
672 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
673 if worker_id and worker_id != 'master':
674 pytest.skip('must run single-threaded')
675
Stephen Warren3e3d1432016-10-17 17:25:52 -0600676def start_test_section(item):
677 anchors[item.name] = log.start_section(item.name)
678
Stephen Warren10e50632016-01-15 11:15:24 -0700679def pytest_runtest_setup(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700680 """pytest hook: Configure (set up) a test item.
Stephen Warren10e50632016-01-15 11:15:24 -0700681
682 Called once for each test to perform any custom configuration. This hook
683 is used to skip the test if certain conditions apply.
684
685 Args:
686 item: The pytest test item.
687
688 Returns:
689 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700690 """
Stephen Warren10e50632016-01-15 11:15:24 -0700691
Stephen Warren3e3d1432016-10-17 17:25:52 -0600692 start_test_section(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700693 setup_boardspec(item)
694 setup_buildconfigspec(item)
Stephen Warren2079db32017-09-18 11:11:49 -0600695 setup_requiredtool(item)
Simon Glass54ef2ca2022-08-06 17:51:47 -0600696 setup_singlethread(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700697
698def pytest_runtest_protocol(item, nextitem):
Stephen Warren75e731e2016-01-26 13:41:30 -0700699 """pytest hook: Called to execute a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700700
701 This hook wraps the standard pytest runtestprotocol() function in order
702 to acquire visibility into, and record, each test function's result.
703
704 Args:
705 item: The pytest test item to execute.
706 nextitem: The pytest test item that will be executed after this one.
707
708 Returns:
709 A list of pytest reports (test result data).
Stephen Warren75e731e2016-01-26 13:41:30 -0700710 """
Stephen Warren10e50632016-01-15 11:15:24 -0700711
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700712 log.get_and_reset_warning()
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700713 ihook = item.ihook
714 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
Stephen Warren10e50632016-01-15 11:15:24 -0700715 reports = runtestprotocol(item, nextitem=nextitem)
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700716 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700717 was_warning = log.get_and_reset_warning()
Stephen Warren25b05242016-01-27 23:57:51 -0700718
Stephen Warren3e3d1432016-10-17 17:25:52 -0600719 # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
720 # the test is skipped. That call is required to create the test's section
721 # in the log file. The call to log.end_section() requires that the log
722 # contain a section for this test. Create a section for the test if it
723 # doesn't already exist.
724 if not item.name in anchors:
725 start_test_section(item)
726
Stephen Warren25b05242016-01-27 23:57:51 -0700727 failure_cleanup = False
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700728 if not was_warning:
729 test_list = tests_passed
730 msg = 'OK'
731 msg_log = log.status_pass
732 else:
733 test_list = tests_warning
734 msg = 'OK (with warning)'
735 msg_log = log.status_warning
Stephen Warren10e50632016-01-15 11:15:24 -0700736 for report in reports:
737 if report.outcome == 'failed':
Stephen Warren25b05242016-01-27 23:57:51 -0700738 if hasattr(report, 'wasxfail'):
739 test_list = tests_xpassed
740 msg = 'XPASSED'
741 msg_log = log.status_xpass
742 else:
743 failure_cleanup = True
744 test_list = tests_failed
745 msg = 'FAILED:\n' + str(report.longrepr)
746 msg_log = log.status_fail
Stephen Warren10e50632016-01-15 11:15:24 -0700747 break
748 if report.outcome == 'skipped':
Stephen Warren25b05242016-01-27 23:57:51 -0700749 if hasattr(report, 'wasxfail'):
750 failure_cleanup = True
751 test_list = tests_xfailed
752 msg = 'XFAILED:\n' + str(report.longrepr)
753 msg_log = log.status_xfail
754 break
755 test_list = tests_skipped
756 msg = 'SKIPPED:\n' + str(report.longrepr)
757 msg_log = log.status_skipped
Stephen Warren10e50632016-01-15 11:15:24 -0700758
Stephen Warren25b05242016-01-27 23:57:51 -0700759 if failure_cleanup:
Stephen Warren97a54662016-01-22 12:30:09 -0700760 console.drain_console()
Stephen Warren25b05242016-01-27 23:57:51 -0700761
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700762 test_list.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700763 tests_not_run.remove(item.name)
764
765 try:
Stephen Warren25b05242016-01-27 23:57:51 -0700766 msg_log(msg)
Stephen Warren10e50632016-01-15 11:15:24 -0700767 except:
768 # If something went wrong with logging, it's better to let the test
769 # process continue, which may report other exceptions that triggered
770 # the logging issue (e.g. console.log wasn't created). Hence, just
771 # squash the exception. If the test setup failed due to e.g. syntax
772 # error somewhere else, this won't be seen. However, once that issue
773 # is fixed, if this exception still exists, it will then be logged as
774 # part of the test's stdout.
775 import traceback
Paul Burton00f2d202017-09-14 14:34:43 -0700776 print('Exception occurred while logging runtest status:')
Stephen Warren10e50632016-01-15 11:15:24 -0700777 traceback.print_exc()
778 # FIXME: Can we force a test failure here?
779
780 log.end_section(item.name)
781
Stephen Warren25b05242016-01-27 23:57:51 -0700782 if failure_cleanup:
Stephen Warren10e50632016-01-15 11:15:24 -0700783 console.cleanup_spawn()
784
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700785 return True