blob: 6b7ed0586e2bbeebe0eb67195aff53623ebe9b4c [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 Glassf6dbc362024-11-12 07:13:18 -0700164 proc = subprocess.run(cmd, capture_output=True, encoding='utf-8',
165 env=env)
166 if proc.returncode:
167 raise ValueError(proc.stderr)
168 # For debugging
169 # print('conftest: lab:', proc.stdout)
170 vals = {}
171 for line in proc.stdout.splitlines():
172 item, value = line.split(' ', maxsplit=1)
173 k = item.split(':')[-1]
174 vals[k] = value
175 # For debugging
176 # print('conftest: lab info:', vals)
Simon Glass5a63a4b2024-11-12 07:13:24 -0700177
178 # Read the build directories here, in case none were provided in the
179 # command-line arguments
180 (board_type, board_type_extra, default_build_dir,
Simon Glass068f6a72024-12-11 06:18:58 -0700181 default_build_dir_extra) = (vals['board'],
182 vals['board_extra'], vals['build_dir'], vals['build_dir_extra'])
Simon Glassf6dbc362024-11-12 07:13:18 -0700183 else:
184 board_type = config.getoption('board_type')
Simon Glass5a63a4b2024-11-12 07:13:24 -0700185 board_type_extra = config.getoption('board_type_extra')
Simon Glassf6dbc362024-11-12 07:13:18 -0700186 board_identity = config.getoption('board_identity')
Simon Glass35ad4322024-10-09 18:29:00 -0600187
Simon Glassf6dbc362024-11-12 07:13:18 -0700188 default_build_dir = source_dir + '/build-' + board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700189 default_build_dir_extra = source_dir + '/build-' + board_type_extra
190
191 # Use the provided command-line arguments if present, else fall back to
Simon Glass62b92f82022-08-06 17:51:57 -0600192 if not build_dir:
Simon Glass35ad4322024-10-09 18:29:00 -0600193 build_dir = default_build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700194 if not build_dir_extra:
195 build_dir_extra = default_build_dir_extra
Simon Glass35ad4322024-10-09 18:29:00 -0600196
Simon Glass5a63a4b2024-11-12 07:13:24 -0700197 return (board_type, board_type_extra, board_identity, build_dir,
198 build_dir_extra, source_dir)
Simon Glass35ad4322024-10-09 18:29:00 -0600199
200def pytest_xdist_setupnodes(config, specs):
201 """Clear out any 'done' file from a previous build"""
202 global build_done_file
203
Simon Glass5a63a4b2024-11-12 07:13:24 -0700204 build_dir = get_details(config)[3]
Simon Glass35ad4322024-10-09 18:29:00 -0600205
Simon Glass62b92f82022-08-06 17:51:57 -0600206 build_done_file = Path(build_dir) / 'build.done'
207 if build_done_file.exists():
208 os.remove(build_done_file)
209
Stephen Warren10e50632016-01-15 11:15:24 -0700210def pytest_configure(config):
Stephen Warren75e731e2016-01-26 13:41:30 -0700211 """pytest hook: Perform custom initialization at startup time.
Stephen Warren10e50632016-01-15 11:15:24 -0700212
213 Args:
214 config: The pytest configuration.
215
216 Returns:
217 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700218 """
Simon Glassde8e25b2019-12-01 19:34:18 -0700219 def parse_config(conf_file):
220 """Parse a config file, loading it into the ubconfig container
221
222 Args:
223 conf_file: Filename to load (within build_dir)
224
225 Raises
226 Exception if the file does not exist
227 """
228 dot_config = build_dir + '/' + conf_file
229 if not os.path.exists(dot_config):
230 raise Exception(conf_file + ' does not exist; ' +
231 'try passing --build option?')
232
233 with open(dot_config, 'rt') as f:
234 ini_str = '[root]\n' + f.read()
235 ini_sio = io.StringIO(ini_str)
236 parser = configparser.RawConfigParser()
237 parser.read_file(ini_sio)
238 ubconfig.buildconfig.update(parser.items('root'))
Stephen Warren10e50632016-01-15 11:15:24 -0700239
240 global log
241 global console
242 global ubconfig
243
Simon Glass5a63a4b2024-11-12 07:13:24 -0700244 (board_type, board_type_extra, board_identity, build_dir, build_dir_extra,
245 source_dir) = get_details(config)
Stephen Warren10e50632016-01-15 11:15:24 -0700246
Stephen Warren10e50632016-01-15 11:15:24 -0700247 board_type_filename = board_type.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700248 board_identity_filename = board_identity.replace('-', '_')
Stephen Warren10e50632016-01-15 11:15:24 -0700249 mkdir_p(build_dir)
250
251 result_dir = config.getoption('result_dir')
252 if not result_dir:
253 result_dir = build_dir
254 mkdir_p(result_dir)
255
256 persistent_data_dir = config.getoption('persistent_data_dir')
257 if not persistent_data_dir:
258 persistent_data_dir = build_dir + '/persistent-data'
259 mkdir_p(persistent_data_dir)
260
Stephen Warren33db1ee2016-02-04 16:11:50 -0700261 gdbserver = config.getoption('gdbserver')
Igor Opaniukea5f17d2019-02-12 16:18:14 +0200262 if gdbserver and not board_type.startswith('sandbox'):
263 raise Exception('--gdbserver only supported with sandbox targets')
Stephen Warren33db1ee2016-02-04 16:11:50 -0700264
Stephen Warren10e50632016-01-15 11:15:24 -0700265 import multiplexed_log
266 log = multiplexed_log.Logfile(result_dir + '/test-log.html')
267
268 if config.getoption('build'):
Simon Glass62b92f82022-08-06 17:51:57 -0600269 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
270 with filelock.FileLock(os.path.join(build_dir, 'build.lock')):
271 build_done_file = Path(build_dir) / 'build.done'
272 if (not worker_id or worker_id == 'master' or
273 not build_done_file.exists()):
274 run_build(config, source_dir, build_dir, board_type, log)
275 build_done_file.touch()
Stephen Warren10e50632016-01-15 11:15:24 -0700276
277 class ArbitraryAttributeContainer(object):
278 pass
279
280 ubconfig = ArbitraryAttributeContainer()
281 ubconfig.brd = dict()
282 ubconfig.env = dict()
283
284 modules = [
285 (ubconfig.brd, 'u_boot_board_' + board_type_filename),
286 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
287 (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
288 board_identity_filename),
289 ]
290 for (dict_to_fill, module_name) in modules:
291 try:
292 module = __import__(module_name)
293 except ImportError:
294 continue
295 dict_to_fill.update(module.__dict__)
296
297 ubconfig.buildconfig = dict()
298
Simon Glassde8e25b2019-12-01 19:34:18 -0700299 # buildman -k puts autoconf.mk in the rootdir, so handle this as well
300 # as the standard U-Boot build which leaves it in include/autoconf.mk
301 parse_config('.config')
302 if os.path.exists(build_dir + '/' + 'autoconf.mk'):
303 parse_config('autoconf.mk')
304 else:
305 parse_config('include/autoconf.mk')
Stephen Warren10e50632016-01-15 11:15:24 -0700306
Simon Glass62b92f82022-08-06 17:51:57 -0600307 ubconfig.test_py_dir = TEST_PY_DIR
Stephen Warren10e50632016-01-15 11:15:24 -0700308 ubconfig.source_dir = source_dir
309 ubconfig.build_dir = build_dir
Simon Glass5a63a4b2024-11-12 07:13:24 -0700310 ubconfig.build_dir_extra = build_dir_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700311 ubconfig.result_dir = result_dir
312 ubconfig.persistent_data_dir = persistent_data_dir
313 ubconfig.board_type = board_type
Simon Glass5a63a4b2024-11-12 07:13:24 -0700314 ubconfig.board_type_extra = board_type_extra
Stephen Warren10e50632016-01-15 11:15:24 -0700315 ubconfig.board_identity = board_identity
Stephen Warren33db1ee2016-02-04 16:11:50 -0700316 ubconfig.gdbserver = gdbserver
Simon Glassf1b1bb82024-11-12 07:13:17 -0700317 ubconfig.use_running_system = config.getoption('use_running_system')
Simon Glass3b097872016-07-03 09:40:36 -0600318 ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
Simon Glassd834d9a2024-10-09 18:29:03 -0600319 ubconfig.connection_ok = True
Stephen Warren10e50632016-01-15 11:15:24 -0700320
321 env_vars = (
322 'board_type',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700323 'board_type_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700324 'board_identity',
325 'source_dir',
326 'test_py_dir',
327 'build_dir',
Simon Glass5a63a4b2024-11-12 07:13:24 -0700328 'build_dir_extra',
Stephen Warren10e50632016-01-15 11:15:24 -0700329 'result_dir',
330 'persistent_data_dir',
331 )
332 for v in env_vars:
333 os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
334
Simon Glass13f422e2016-07-04 11:58:37 -0600335 if board_type.startswith('sandbox'):
Stephen Warren10e50632016-01-15 11:15:24 -0700336 import u_boot_console_sandbox
337 console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
338 else:
339 import u_boot_console_exec_attach
340 console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
341
Simon Glassb15512c2025-01-20 14:25:32 -0700342
Simon Glassed298be2020-10-25 20:38:31 -0600343def generate_ut_subtest(metafunc, fixture_name, sym_path):
Stephen Warren770fe172016-02-08 14:44:16 -0700344 """Provide parametrization for a ut_subtest fixture.
345
346 Determines the set of unit tests built into a U-Boot binary by parsing the
347 list of symbols generated by the build process. Provides this information
348 to test functions by parameterizing their ut_subtest fixture parameter.
349
350 Args:
351 metafunc: The pytest test function.
352 fixture_name: The fixture name to test.
Simon Glassed298be2020-10-25 20:38:31 -0600353 sym_path: Relative path to the symbol file with preceding '/'
354 (e.g. '/u-boot.sym')
Stephen Warren770fe172016-02-08 14:44:16 -0700355
356 Returns:
357 Nothing.
358 """
Simon Glassed298be2020-10-25 20:38:31 -0600359 fn = console.config.build_dir + sym_path
Stephen Warren770fe172016-02-08 14:44:16 -0700360 try:
361 with open(fn, 'rt') as f:
362 lines = f.readlines()
363 except:
364 lines = []
365 lines.sort()
366
367 vals = []
368 for l in lines:
Simon Glassb15512c2025-01-20 14:25:32 -0700369 m = RE_UT_TEST_LIST.search(l)
Stephen Warren770fe172016-02-08 14:44:16 -0700370 if not m:
371 continue
Simon Glass1f1614b2022-10-20 18:22:50 -0600372 suite, name = m.groups()
373
374 # Tests marked with _norun should only be run manually using 'ut -f'
375 if name.endswith('_norun'):
376 continue
377
378 vals.append(f'{suite} {name}')
Stephen Warren770fe172016-02-08 14:44:16 -0700379
380 ids = ['ut_' + s.replace(' ', '_') for s in vals]
381 metafunc.parametrize(fixture_name, vals, ids=ids)
382
383def generate_config(metafunc, fixture_name):
384 """Provide parametrization for {env,brd}__ fixtures.
Stephen Warren10e50632016-01-15 11:15:24 -0700385
386 If a test function takes parameter(s) (fixture names) of the form brd__xxx
387 or env__xxx, the brd and env configuration dictionaries are consulted to
388 find the list of values to use for those parameters, and the test is
389 parametrized so that it runs once for each combination of values.
390
391 Args:
392 metafunc: The pytest test function.
Stephen Warren770fe172016-02-08 14:44:16 -0700393 fixture_name: The fixture name to test.
Stephen Warren10e50632016-01-15 11:15:24 -0700394
395 Returns:
396 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700397 """
Stephen Warren10e50632016-01-15 11:15:24 -0700398
399 subconfigs = {
400 'brd': console.config.brd,
401 'env': console.config.env,
402 }
Stephen Warren770fe172016-02-08 14:44:16 -0700403 parts = fixture_name.split('__')
404 if len(parts) < 2:
405 return
406 if parts[0] not in subconfigs:
407 return
408 subconfig = subconfigs[parts[0]]
409 vals = []
410 val = subconfig.get(fixture_name, [])
411 # If that exact name is a key in the data source:
412 if val:
413 # ... use the dict value as a single parameter value.
414 vals = (val, )
415 else:
416 # ... otherwise, see if there's a key that contains a list of
417 # values to use instead.
418 vals = subconfig.get(fixture_name+ 's', [])
419 def fixture_id(index, val):
420 try:
421 return val['fixture_id']
422 except:
423 return fixture_name + str(index)
424 ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
425 metafunc.parametrize(fixture_name, vals, ids=ids)
426
427def pytest_generate_tests(metafunc):
428 """pytest hook: parameterize test functions based on custom rules.
429
430 Check each test function parameter (fixture name) to see if it is one of
431 our custom names, and if so, provide the correct parametrization for that
432 parameter.
433
434 Args:
435 metafunc: The pytest test function.
436
437 Returns:
438 Nothing.
439 """
Stephen Warren10e50632016-01-15 11:15:24 -0700440 for fn in metafunc.fixturenames:
Stephen Warren770fe172016-02-08 14:44:16 -0700441 if fn == 'ut_subtest':
Simon Glassed298be2020-10-25 20:38:31 -0600442 generate_ut_subtest(metafunc, fn, '/u-boot.sym')
443 continue
Simon Glassb6c665f2022-04-30 00:56:55 -0600444 m_subtest = re.match('ut_(.)pl_subtest', fn)
445 if m_subtest:
446 spl_name = m_subtest.group(1)
447 generate_ut_subtest(
448 metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
Stephen Warren10e50632016-01-15 11:15:24 -0700449 continue
Stephen Warren770fe172016-02-08 14:44:16 -0700450 generate_config(metafunc, fn)
Stephen Warren10e50632016-01-15 11:15:24 -0700451
Stefan Brüns364ea872016-11-05 17:45:32 +0100452@pytest.fixture(scope='session')
453def u_boot_log(request):
454 """Generate the value of a test's log fixture.
455
456 Args:
457 request: The pytest request.
458
459 Returns:
460 The fixture value.
461 """
462
463 return console.log
464
465@pytest.fixture(scope='session')
466def u_boot_config(request):
467 """Generate the value of a test's u_boot_config fixture.
468
469 Args:
470 request: The pytest request.
471
472 Returns:
473 The fixture value.
474 """
475
476 return console.config
477
Stephen Warrene1d24d02016-01-22 12:30:08 -0700478@pytest.fixture(scope='function')
Stephen Warren10e50632016-01-15 11:15:24 -0700479def u_boot_console(request):
Stephen Warren75e731e2016-01-26 13:41:30 -0700480 """Generate the value of a test's u_boot_console fixture.
Stephen Warren10e50632016-01-15 11:15:24 -0700481
482 Args:
483 request: The pytest request.
484
485 Returns:
486 The fixture value.
Stephen Warren75e731e2016-01-26 13:41:30 -0700487 """
Simon Glassd834d9a2024-10-09 18:29:03 -0600488 if not ubconfig.connection_ok:
489 pytest.skip('Cannot get target connection')
490 return None
491 try:
492 console.ensure_spawned()
493 except OSError as err:
494 handle_exception(ubconfig, console, log, err, 'Lab failure', True)
495 except Timeout as err:
496 handle_exception(ubconfig, console, log, err, 'Lab timeout', True)
497 except BootFail as err:
498 handle_exception(ubconfig, console, log, err, 'Boot fail', True,
499 console.get_spawn_output())
500 except Unexpected:
501 handle_exception(ubconfig, console, log, err, 'Unexpected test output',
502 False)
Stephen Warren10e50632016-01-15 11:15:24 -0700503 return console
504
Stephen Warrene3f2a502016-02-03 16:46:34 -0700505anchors = {}
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700506tests_not_run = []
507tests_failed = []
508tests_xpassed = []
509tests_xfailed = []
510tests_skipped = []
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700511tests_warning = []
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700512tests_passed = []
Stephen Warren10e50632016-01-15 11:15:24 -0700513
514def pytest_itemcollected(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700515 """pytest hook: Called once for each test found during collection.
Stephen Warren10e50632016-01-15 11:15:24 -0700516
517 This enables our custom result analysis code to see the list of all tests
518 that should eventually be run.
519
520 Args:
521 item: The item that was collected.
522
523 Returns:
524 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700525 """
Stephen Warren10e50632016-01-15 11:15:24 -0700526
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700527 tests_not_run.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700528
529def cleanup():
Stephen Warren75e731e2016-01-26 13:41:30 -0700530 """Clean up all global state.
Stephen Warren10e50632016-01-15 11:15:24 -0700531
532 Executed (via atexit) once the entire test process is complete. This
533 includes logging the status of all tests, and the identity of any failed
534 or skipped tests.
535
536 Args:
537 None.
538
539 Returns:
540 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700541 """
Stephen Warren10e50632016-01-15 11:15:24 -0700542
543 if console:
544 console.close()
545 if log:
Stephen Warrene3f2a502016-02-03 16:46:34 -0700546 with log.section('Status Report', 'status_report'):
547 log.status_pass('%d passed' % len(tests_passed))
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700548 if tests_warning:
549 log.status_warning('%d passed with warning' % len(tests_warning))
550 for test in tests_warning:
551 anchor = anchors.get(test, None)
552 log.status_warning('... ' + test, anchor)
Stephen Warrene3f2a502016-02-03 16:46:34 -0700553 if tests_skipped:
554 log.status_skipped('%d skipped' % len(tests_skipped))
555 for test in tests_skipped:
556 anchor = anchors.get(test, None)
557 log.status_skipped('... ' + test, anchor)
558 if tests_xpassed:
559 log.status_xpass('%d xpass' % len(tests_xpassed))
560 for test in tests_xpassed:
561 anchor = anchors.get(test, None)
562 log.status_xpass('... ' + test, anchor)
563 if tests_xfailed:
564 log.status_xfail('%d xfail' % len(tests_xfailed))
565 for test in tests_xfailed:
566 anchor = anchors.get(test, None)
567 log.status_xfail('... ' + test, anchor)
568 if tests_failed:
569 log.status_fail('%d failed' % len(tests_failed))
570 for test in tests_failed:
571 anchor = anchors.get(test, None)
572 log.status_fail('... ' + test, anchor)
573 if tests_not_run:
574 log.status_fail('%d not run' % len(tests_not_run))
575 for test in tests_not_run:
576 anchor = anchors.get(test, None)
577 log.status_fail('... ' + test, anchor)
Stephen Warren10e50632016-01-15 11:15:24 -0700578 log.close()
579atexit.register(cleanup)
580
581def setup_boardspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700582 """Process any 'boardspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700583
584 Such a marker lists the set of board types that a test does/doesn't
585 support. If tests are being executed on an unsupported board, the test is
586 marked to be skipped.
587
588 Args:
589 item: The pytest test item.
590
591 Returns:
592 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700593 """
Stephen Warren10e50632016-01-15 11:15:24 -0700594
Stephen Warren10e50632016-01-15 11:15:24 -0700595 required_boards = []
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400596 for boards in item.iter_markers('boardspec'):
597 board = boards.args[0]
Stephen Warren10e50632016-01-15 11:15:24 -0700598 if board.startswith('!'):
599 if ubconfig.board_type == board[1:]:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600600 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700601 return
602 else:
603 required_boards.append(board)
604 if required_boards and ubconfig.board_type not in required_boards:
Stephen Warren0f0eeac2017-09-18 11:11:48 -0600605 pytest.skip('board "%s" not supported' % ubconfig.board_type)
Stephen Warren10e50632016-01-15 11:15:24 -0700606
607def setup_buildconfigspec(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700608 """Process any 'buildconfigspec' marker for a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700609
610 Such a marker lists some U-Boot configuration feature that the test
611 requires. If tests are being executed on an U-Boot build that doesn't
612 have the required feature, the test is marked to be skipped.
613
614 Args:
615 item: The pytest test item.
616
617 Returns:
618 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700619 """
Stephen Warren10e50632016-01-15 11:15:24 -0700620
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400621 for options in item.iter_markers('buildconfigspec'):
622 option = options.args[0]
623 if not ubconfig.buildconfig.get('config_' + option.lower(), None):
624 pytest.skip('.config feature "%s" not enabled' % option.lower())
Cristian Ciocaltea6c6c8072019-12-24 17:19:12 +0200625 for options in item.iter_markers('notbuildconfigspec'):
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400626 option = options.args[0]
627 if ubconfig.buildconfig.get('config_' + option.lower(), None):
628 pytest.skip('.config feature "%s" enabled' % option.lower())
Stephen Warren10e50632016-01-15 11:15:24 -0700629
Stephen Warren2079db32017-09-18 11:11:49 -0600630def tool_is_in_path(tool):
631 for path in os.environ["PATH"].split(os.pathsep):
632 fn = os.path.join(path, tool)
633 if os.path.isfile(fn) and os.access(fn, os.X_OK):
634 return True
635 return False
636
637def setup_requiredtool(item):
638 """Process any 'requiredtool' marker for a test.
639
640 Such a marker lists some external tool (binary, executable, application)
641 that the test requires. If tests are being executed on a system that
642 doesn't have the required tool, the test is marked to be skipped.
643
644 Args:
645 item: The pytest test item.
646
647 Returns:
648 Nothing.
649 """
650
Marek Vasut9dfdf6e2019-10-24 11:59:19 -0400651 for tools in item.iter_markers('requiredtool'):
652 tool = tools.args[0]
Stephen Warren2079db32017-09-18 11:11:49 -0600653 if not tool_is_in_path(tool):
654 pytest.skip('tool "%s" not in $PATH' % tool)
655
Simon Glass54ef2ca2022-08-06 17:51:47 -0600656def setup_singlethread(item):
657 """Process any 'singlethread' marker for a test.
658
659 Skip this test if running in parallel.
660
661 Args:
662 item: The pytest test item.
663
664 Returns:
665 Nothing.
666 """
667 for single in item.iter_markers('singlethread'):
668 worker_id = os.environ.get("PYTEST_XDIST_WORKER")
669 if worker_id and worker_id != 'master':
670 pytest.skip('must run single-threaded')
671
Stephen Warren3e3d1432016-10-17 17:25:52 -0600672def start_test_section(item):
673 anchors[item.name] = log.start_section(item.name)
674
Stephen Warren10e50632016-01-15 11:15:24 -0700675def pytest_runtest_setup(item):
Stephen Warren75e731e2016-01-26 13:41:30 -0700676 """pytest hook: Configure (set up) a test item.
Stephen Warren10e50632016-01-15 11:15:24 -0700677
678 Called once for each test to perform any custom configuration. This hook
679 is used to skip the test if certain conditions apply.
680
681 Args:
682 item: The pytest test item.
683
684 Returns:
685 Nothing.
Stephen Warren75e731e2016-01-26 13:41:30 -0700686 """
Stephen Warren10e50632016-01-15 11:15:24 -0700687
Stephen Warren3e3d1432016-10-17 17:25:52 -0600688 start_test_section(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700689 setup_boardspec(item)
690 setup_buildconfigspec(item)
Stephen Warren2079db32017-09-18 11:11:49 -0600691 setup_requiredtool(item)
Simon Glass54ef2ca2022-08-06 17:51:47 -0600692 setup_singlethread(item)
Stephen Warren10e50632016-01-15 11:15:24 -0700693
694def pytest_runtest_protocol(item, nextitem):
Stephen Warren75e731e2016-01-26 13:41:30 -0700695 """pytest hook: Called to execute a test.
Stephen Warren10e50632016-01-15 11:15:24 -0700696
697 This hook wraps the standard pytest runtestprotocol() function in order
698 to acquire visibility into, and record, each test function's result.
699
700 Args:
701 item: The pytest test item to execute.
702 nextitem: The pytest test item that will be executed after this one.
703
704 Returns:
705 A list of pytest reports (test result data).
Stephen Warren75e731e2016-01-26 13:41:30 -0700706 """
Stephen Warren10e50632016-01-15 11:15:24 -0700707
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700708 log.get_and_reset_warning()
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700709 ihook = item.ihook
710 ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
Stephen Warren10e50632016-01-15 11:15:24 -0700711 reports = runtestprotocol(item, nextitem=nextitem)
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700712 ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700713 was_warning = log.get_and_reset_warning()
Stephen Warren25b05242016-01-27 23:57:51 -0700714
Stephen Warren3e3d1432016-10-17 17:25:52 -0600715 # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
716 # the test is skipped. That call is required to create the test's section
717 # in the log file. The call to log.end_section() requires that the log
718 # contain a section for this test. Create a section for the test if it
719 # doesn't already exist.
720 if not item.name in anchors:
721 start_test_section(item)
722
Stephen Warren25b05242016-01-27 23:57:51 -0700723 failure_cleanup = False
Stephen Warrene27a6ae2018-02-20 12:51:55 -0700724 if not was_warning:
725 test_list = tests_passed
726 msg = 'OK'
727 msg_log = log.status_pass
728 else:
729 test_list = tests_warning
730 msg = 'OK (with warning)'
731 msg_log = log.status_warning
Stephen Warren10e50632016-01-15 11:15:24 -0700732 for report in reports:
733 if report.outcome == 'failed':
Stephen Warren25b05242016-01-27 23:57:51 -0700734 if hasattr(report, 'wasxfail'):
735 test_list = tests_xpassed
736 msg = 'XPASSED'
737 msg_log = log.status_xpass
738 else:
739 failure_cleanup = True
740 test_list = tests_failed
741 msg = 'FAILED:\n' + str(report.longrepr)
742 msg_log = log.status_fail
Stephen Warren10e50632016-01-15 11:15:24 -0700743 break
744 if report.outcome == 'skipped':
Stephen Warren25b05242016-01-27 23:57:51 -0700745 if hasattr(report, 'wasxfail'):
746 failure_cleanup = True
747 test_list = tests_xfailed
748 msg = 'XFAILED:\n' + str(report.longrepr)
749 msg_log = log.status_xfail
750 break
751 test_list = tests_skipped
752 msg = 'SKIPPED:\n' + str(report.longrepr)
753 msg_log = log.status_skipped
Stephen Warren10e50632016-01-15 11:15:24 -0700754
Stephen Warren25b05242016-01-27 23:57:51 -0700755 if failure_cleanup:
Stephen Warren97a54662016-01-22 12:30:09 -0700756 console.drain_console()
Stephen Warren25b05242016-01-27 23:57:51 -0700757
Stephen Warrenaaf4e912016-02-10 13:47:37 -0700758 test_list.append(item.name)
Stephen Warren10e50632016-01-15 11:15:24 -0700759 tests_not_run.remove(item.name)
760
761 try:
Stephen Warren25b05242016-01-27 23:57:51 -0700762 msg_log(msg)
Stephen Warren10e50632016-01-15 11:15:24 -0700763 except:
764 # If something went wrong with logging, it's better to let the test
765 # process continue, which may report other exceptions that triggered
766 # the logging issue (e.g. console.log wasn't created). Hence, just
767 # squash the exception. If the test setup failed due to e.g. syntax
768 # error somewhere else, this won't be seen. However, once that issue
769 # is fixed, if this exception still exists, it will then be logged as
770 # part of the test's stdout.
771 import traceback
Paul Burton00f2d202017-09-14 14:34:43 -0700772 print('Exception occurred while logging runtest status:')
Stephen Warren10e50632016-01-15 11:15:24 -0700773 traceback.print_exc()
774 # FIXME: Can we force a test failure here?
775
776 log.end_section(item.name)
777
Stephen Warren25b05242016-01-27 23:57:51 -0700778 if failure_cleanup:
Stephen Warren10e50632016-01-15 11:15:24 -0700779 console.cleanup_spawn()
780
Stephen Warren76e6a9e2021-01-30 20:12:18 -0700781 return True