conftest.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  1. # SPDX-License-Identifier: GPL-2.0
  2. # Copyright (c) 2015 Stephen Warren
  3. # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
  4. # Implementation of pytest run-time hook functions. These are invoked by
  5. # pytest at certain points during operation, e.g. startup, for each executed
  6. # test, at shutdown etc. These hooks perform functions such as:
  7. # - Parsing custom command-line options.
  8. # - Pullilng in user-specified board configuration.
  9. # - Creating the U-Boot console test fixture.
  10. # - Creating the HTML log file.
  11. # - Monitoring each test's results.
  12. # - Implementing custom pytest markers.
  13. import atexit
  14. import configparser
  15. import errno
  16. import filelock
  17. import io
  18. import os
  19. import os.path
  20. from pathlib import Path
  21. import pytest
  22. import re
  23. from _pytest.runner import runtestprotocol
  24. import sys
  25. # Globals: The HTML log file, and the connection to the U-Boot console.
  26. log = None
  27. console = None
  28. TEST_PY_DIR = os.path.dirname(os.path.abspath(__file__))
  29. def mkdir_p(path):
  30. """Create a directory path.
  31. This includes creating any intermediate/parent directories. Any errors
  32. caused due to already extant directories are ignored.
  33. Args:
  34. path: The directory path to create.
  35. Returns:
  36. Nothing.
  37. """
  38. try:
  39. os.makedirs(path)
  40. except OSError as exc:
  41. if exc.errno == errno.EEXIST and os.path.isdir(path):
  42. pass
  43. else:
  44. raise
  45. def pytest_addoption(parser):
  46. """pytest hook: Add custom command-line options to the cmdline parser.
  47. Args:
  48. parser: The pytest command-line parser.
  49. Returns:
  50. Nothing.
  51. """
  52. parser.addoption('--build-dir', default=None,
  53. help='U-Boot build directory (O=)')
  54. parser.addoption('--result-dir', default=None,
  55. help='U-Boot test result/tmp directory')
  56. parser.addoption('--persistent-data-dir', default=None,
  57. help='U-Boot test persistent generated data directory')
  58. parser.addoption('--board-type', '--bd', '-B', default='sandbox',
  59. help='U-Boot board type')
  60. parser.addoption('--board-identity', '--id', default='na',
  61. help='U-Boot board identity/instance')
  62. parser.addoption('--build', default=False, action='store_true',
  63. help='Compile U-Boot before running tests')
  64. parser.addoption('--buildman', default=False, action='store_true',
  65. help='Use buildman to build U-Boot (assuming --build is given)')
  66. parser.addoption('--gdbserver', default=None,
  67. help='Run sandbox under gdbserver. The argument is the channel '+
  68. 'over which gdbserver should communicate, e.g. localhost:1234')
  69. def run_build(config, source_dir, build_dir, board_type, log):
  70. """run_build: Build U-Boot
  71. Args:
  72. config: The pytest configuration.
  73. soruce_dir (str): Directory containing source code
  74. build_dir (str): Directory to build in
  75. board_type (str): board_type parameter (e.g. 'sandbox')
  76. log (Logfile): Log file to use
  77. """
  78. if config.getoption('buildman'):
  79. if build_dir != source_dir:
  80. dest_args = ['-o', build_dir, '-w']
  81. else:
  82. dest_args = ['-i']
  83. cmds = (['buildman', '--board', board_type] + dest_args,)
  84. name = 'buildman'
  85. else:
  86. if build_dir != source_dir:
  87. o_opt = 'O=%s' % build_dir
  88. else:
  89. o_opt = ''
  90. cmds = (
  91. ['make', o_opt, '-s', board_type + '_defconfig'],
  92. ['make', o_opt, '-s', '-j{}'.format(os.cpu_count())],
  93. )
  94. name = 'make'
  95. with log.section(name):
  96. runner = log.get_runner(name, sys.stdout)
  97. for cmd in cmds:
  98. runner.run(cmd, cwd=source_dir)
  99. runner.close()
  100. log.status_pass('OK')
  101. def pytest_xdist_setupnodes(config, specs):
  102. """Clear out any 'done' file from a previous build"""
  103. global build_done_file
  104. build_dir = config.getoption('build_dir')
  105. board_type = config.getoption('board_type')
  106. source_dir = os.path.dirname(os.path.dirname(TEST_PY_DIR))
  107. if not build_dir:
  108. build_dir = source_dir + '/build-' + board_type
  109. build_done_file = Path(build_dir) / 'build.done'
  110. if build_done_file.exists():
  111. os.remove(build_done_file)
  112. def pytest_configure(config):
  113. """pytest hook: Perform custom initialization at startup time.
  114. Args:
  115. config: The pytest configuration.
  116. Returns:
  117. Nothing.
  118. """
  119. def parse_config(conf_file):
  120. """Parse a config file, loading it into the ubconfig container
  121. Args:
  122. conf_file: Filename to load (within build_dir)
  123. Raises
  124. Exception if the file does not exist
  125. """
  126. dot_config = build_dir + '/' + conf_file
  127. if not os.path.exists(dot_config):
  128. raise Exception(conf_file + ' does not exist; ' +
  129. 'try passing --build option?')
  130. with open(dot_config, 'rt') as f:
  131. ini_str = '[root]\n' + f.read()
  132. ini_sio = io.StringIO(ini_str)
  133. parser = configparser.RawConfigParser()
  134. parser.read_file(ini_sio)
  135. ubconfig.buildconfig.update(parser.items('root'))
  136. global log
  137. global console
  138. global ubconfig
  139. source_dir = os.path.dirname(os.path.dirname(TEST_PY_DIR))
  140. board_type = config.getoption('board_type')
  141. board_type_filename = board_type.replace('-', '_')
  142. board_identity = config.getoption('board_identity')
  143. board_identity_filename = board_identity.replace('-', '_')
  144. build_dir = config.getoption('build_dir')
  145. if not build_dir:
  146. build_dir = source_dir + '/build-' + board_type
  147. mkdir_p(build_dir)
  148. result_dir = config.getoption('result_dir')
  149. if not result_dir:
  150. result_dir = build_dir
  151. mkdir_p(result_dir)
  152. persistent_data_dir = config.getoption('persistent_data_dir')
  153. if not persistent_data_dir:
  154. persistent_data_dir = build_dir + '/persistent-data'
  155. mkdir_p(persistent_data_dir)
  156. gdbserver = config.getoption('gdbserver')
  157. if gdbserver and not board_type.startswith('sandbox'):
  158. raise Exception('--gdbserver only supported with sandbox targets')
  159. import multiplexed_log
  160. log = multiplexed_log.Logfile(result_dir + '/test-log.html')
  161. if config.getoption('build'):
  162. worker_id = os.environ.get("PYTEST_XDIST_WORKER")
  163. with filelock.FileLock(os.path.join(build_dir, 'build.lock')):
  164. build_done_file = Path(build_dir) / 'build.done'
  165. if (not worker_id or worker_id == 'master' or
  166. not build_done_file.exists()):
  167. run_build(config, source_dir, build_dir, board_type, log)
  168. build_done_file.touch()
  169. class ArbitraryAttributeContainer(object):
  170. pass
  171. ubconfig = ArbitraryAttributeContainer()
  172. ubconfig.brd = dict()
  173. ubconfig.env = dict()
  174. modules = [
  175. (ubconfig.brd, 'u_boot_board_' + board_type_filename),
  176. (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
  177. (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
  178. board_identity_filename),
  179. ]
  180. for (dict_to_fill, module_name) in modules:
  181. try:
  182. module = __import__(module_name)
  183. except ImportError:
  184. continue
  185. dict_to_fill.update(module.__dict__)
  186. ubconfig.buildconfig = dict()
  187. # buildman -k puts autoconf.mk in the rootdir, so handle this as well
  188. # as the standard U-Boot build which leaves it in include/autoconf.mk
  189. parse_config('.config')
  190. if os.path.exists(build_dir + '/' + 'autoconf.mk'):
  191. parse_config('autoconf.mk')
  192. else:
  193. parse_config('include/autoconf.mk')
  194. ubconfig.test_py_dir = TEST_PY_DIR
  195. ubconfig.source_dir = source_dir
  196. ubconfig.build_dir = build_dir
  197. ubconfig.result_dir = result_dir
  198. ubconfig.persistent_data_dir = persistent_data_dir
  199. ubconfig.board_type = board_type
  200. ubconfig.board_identity = board_identity
  201. ubconfig.gdbserver = gdbserver
  202. ubconfig.dtb = build_dir + '/arch/sandbox/dts/test.dtb'
  203. env_vars = (
  204. 'board_type',
  205. 'board_identity',
  206. 'source_dir',
  207. 'test_py_dir',
  208. 'build_dir',
  209. 'result_dir',
  210. 'persistent_data_dir',
  211. )
  212. for v in env_vars:
  213. os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
  214. if board_type.startswith('sandbox'):
  215. import u_boot_console_sandbox
  216. console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
  217. else:
  218. import u_boot_console_exec_attach
  219. console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
  220. re_ut_test_list = re.compile(r'[^a-zA-Z0-9_]_u_boot_list_2_ut_(.*)_test_2_(.*)\s*$')
  221. def generate_ut_subtest(metafunc, fixture_name, sym_path):
  222. """Provide parametrization for a ut_subtest fixture.
  223. Determines the set of unit tests built into a U-Boot binary by parsing the
  224. list of symbols generated by the build process. Provides this information
  225. to test functions by parameterizing their ut_subtest fixture parameter.
  226. Args:
  227. metafunc: The pytest test function.
  228. fixture_name: The fixture name to test.
  229. sym_path: Relative path to the symbol file with preceding '/'
  230. (e.g. '/u-boot.sym')
  231. Returns:
  232. Nothing.
  233. """
  234. fn = console.config.build_dir + sym_path
  235. try:
  236. with open(fn, 'rt') as f:
  237. lines = f.readlines()
  238. except:
  239. lines = []
  240. lines.sort()
  241. vals = []
  242. for l in lines:
  243. m = re_ut_test_list.search(l)
  244. if not m:
  245. continue
  246. suite, name = m.groups()
  247. # Tests marked with _norun should only be run manually using 'ut -f'
  248. if name.endswith('_norun'):
  249. continue
  250. vals.append(f'{suite} {name}')
  251. ids = ['ut_' + s.replace(' ', '_') for s in vals]
  252. metafunc.parametrize(fixture_name, vals, ids=ids)
  253. def generate_config(metafunc, fixture_name):
  254. """Provide parametrization for {env,brd}__ fixtures.
  255. If a test function takes parameter(s) (fixture names) of the form brd__xxx
  256. or env__xxx, the brd and env configuration dictionaries are consulted to
  257. find the list of values to use for those parameters, and the test is
  258. parametrized so that it runs once for each combination of values.
  259. Args:
  260. metafunc: The pytest test function.
  261. fixture_name: The fixture name to test.
  262. Returns:
  263. Nothing.
  264. """
  265. subconfigs = {
  266. 'brd': console.config.brd,
  267. 'env': console.config.env,
  268. }
  269. parts = fixture_name.split('__')
  270. if len(parts) < 2:
  271. return
  272. if parts[0] not in subconfigs:
  273. return
  274. subconfig = subconfigs[parts[0]]
  275. vals = []
  276. val = subconfig.get(fixture_name, [])
  277. # If that exact name is a key in the data source:
  278. if val:
  279. # ... use the dict value as a single parameter value.
  280. vals = (val, )
  281. else:
  282. # ... otherwise, see if there's a key that contains a list of
  283. # values to use instead.
  284. vals = subconfig.get(fixture_name+ 's', [])
  285. def fixture_id(index, val):
  286. try:
  287. return val['fixture_id']
  288. except:
  289. return fixture_name + str(index)
  290. ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
  291. metafunc.parametrize(fixture_name, vals, ids=ids)
  292. def pytest_generate_tests(metafunc):
  293. """pytest hook: parameterize test functions based on custom rules.
  294. Check each test function parameter (fixture name) to see if it is one of
  295. our custom names, and if so, provide the correct parametrization for that
  296. parameter.
  297. Args:
  298. metafunc: The pytest test function.
  299. Returns:
  300. Nothing.
  301. """
  302. for fn in metafunc.fixturenames:
  303. if fn == 'ut_subtest':
  304. generate_ut_subtest(metafunc, fn, '/u-boot.sym')
  305. continue
  306. m_subtest = re.match('ut_(.)pl_subtest', fn)
  307. if m_subtest:
  308. spl_name = m_subtest.group(1)
  309. generate_ut_subtest(
  310. metafunc, fn, f'/{spl_name}pl/u-boot-{spl_name}pl.sym')
  311. continue
  312. generate_config(metafunc, fn)
  313. @pytest.fixture(scope='session')
  314. def u_boot_log(request):
  315. """Generate the value of a test's log fixture.
  316. Args:
  317. request: The pytest request.
  318. Returns:
  319. The fixture value.
  320. """
  321. return console.log
  322. @pytest.fixture(scope='session')
  323. def u_boot_config(request):
  324. """Generate the value of a test's u_boot_config fixture.
  325. Args:
  326. request: The pytest request.
  327. Returns:
  328. The fixture value.
  329. """
  330. return console.config
  331. @pytest.fixture(scope='function')
  332. def u_boot_console(request):
  333. """Generate the value of a test's u_boot_console fixture.
  334. Args:
  335. request: The pytest request.
  336. Returns:
  337. The fixture value.
  338. """
  339. console.ensure_spawned()
  340. return console
  341. anchors = {}
  342. tests_not_run = []
  343. tests_failed = []
  344. tests_xpassed = []
  345. tests_xfailed = []
  346. tests_skipped = []
  347. tests_warning = []
  348. tests_passed = []
  349. def pytest_itemcollected(item):
  350. """pytest hook: Called once for each test found during collection.
  351. This enables our custom result analysis code to see the list of all tests
  352. that should eventually be run.
  353. Args:
  354. item: The item that was collected.
  355. Returns:
  356. Nothing.
  357. """
  358. tests_not_run.append(item.name)
  359. def cleanup():
  360. """Clean up all global state.
  361. Executed (via atexit) once the entire test process is complete. This
  362. includes logging the status of all tests, and the identity of any failed
  363. or skipped tests.
  364. Args:
  365. None.
  366. Returns:
  367. Nothing.
  368. """
  369. if console:
  370. console.close()
  371. if log:
  372. with log.section('Status Report', 'status_report'):
  373. log.status_pass('%d passed' % len(tests_passed))
  374. if tests_warning:
  375. log.status_warning('%d passed with warning' % len(tests_warning))
  376. for test in tests_warning:
  377. anchor = anchors.get(test, None)
  378. log.status_warning('... ' + test, anchor)
  379. if tests_skipped:
  380. log.status_skipped('%d skipped' % len(tests_skipped))
  381. for test in tests_skipped:
  382. anchor = anchors.get(test, None)
  383. log.status_skipped('... ' + test, anchor)
  384. if tests_xpassed:
  385. log.status_xpass('%d xpass' % len(tests_xpassed))
  386. for test in tests_xpassed:
  387. anchor = anchors.get(test, None)
  388. log.status_xpass('... ' + test, anchor)
  389. if tests_xfailed:
  390. log.status_xfail('%d xfail' % len(tests_xfailed))
  391. for test in tests_xfailed:
  392. anchor = anchors.get(test, None)
  393. log.status_xfail('... ' + test, anchor)
  394. if tests_failed:
  395. log.status_fail('%d failed' % len(tests_failed))
  396. for test in tests_failed:
  397. anchor = anchors.get(test, None)
  398. log.status_fail('... ' + test, anchor)
  399. if tests_not_run:
  400. log.status_fail('%d not run' % len(tests_not_run))
  401. for test in tests_not_run:
  402. anchor = anchors.get(test, None)
  403. log.status_fail('... ' + test, anchor)
  404. log.close()
  405. atexit.register(cleanup)
  406. def setup_boardspec(item):
  407. """Process any 'boardspec' marker for a test.
  408. Such a marker lists the set of board types that a test does/doesn't
  409. support. If tests are being executed on an unsupported board, the test is
  410. marked to be skipped.
  411. Args:
  412. item: The pytest test item.
  413. Returns:
  414. Nothing.
  415. """
  416. required_boards = []
  417. for boards in item.iter_markers('boardspec'):
  418. board = boards.args[0]
  419. if board.startswith('!'):
  420. if ubconfig.board_type == board[1:]:
  421. pytest.skip('board "%s" not supported' % ubconfig.board_type)
  422. return
  423. else:
  424. required_boards.append(board)
  425. if required_boards and ubconfig.board_type not in required_boards:
  426. pytest.skip('board "%s" not supported' % ubconfig.board_type)
  427. def setup_buildconfigspec(item):
  428. """Process any 'buildconfigspec' marker for a test.
  429. Such a marker lists some U-Boot configuration feature that the test
  430. requires. If tests are being executed on an U-Boot build that doesn't
  431. have the required feature, the test is marked to be skipped.
  432. Args:
  433. item: The pytest test item.
  434. Returns:
  435. Nothing.
  436. """
  437. for options in item.iter_markers('buildconfigspec'):
  438. option = options.args[0]
  439. if not ubconfig.buildconfig.get('config_' + option.lower(), None):
  440. pytest.skip('.config feature "%s" not enabled' % option.lower())
  441. for options in item.iter_markers('notbuildconfigspec'):
  442. option = options.args[0]
  443. if ubconfig.buildconfig.get('config_' + option.lower(), None):
  444. pytest.skip('.config feature "%s" enabled' % option.lower())
  445. def tool_is_in_path(tool):
  446. for path in os.environ["PATH"].split(os.pathsep):
  447. fn = os.path.join(path, tool)
  448. if os.path.isfile(fn) and os.access(fn, os.X_OK):
  449. return True
  450. return False
  451. def setup_requiredtool(item):
  452. """Process any 'requiredtool' marker for a test.
  453. Such a marker lists some external tool (binary, executable, application)
  454. that the test requires. If tests are being executed on a system that
  455. doesn't have the required tool, the test is marked to be skipped.
  456. Args:
  457. item: The pytest test item.
  458. Returns:
  459. Nothing.
  460. """
  461. for tools in item.iter_markers('requiredtool'):
  462. tool = tools.args[0]
  463. if not tool_is_in_path(tool):
  464. pytest.skip('tool "%s" not in $PATH' % tool)
  465. def setup_singlethread(item):
  466. """Process any 'singlethread' marker for a test.
  467. Skip this test if running in parallel.
  468. Args:
  469. item: The pytest test item.
  470. Returns:
  471. Nothing.
  472. """
  473. for single in item.iter_markers('singlethread'):
  474. worker_id = os.environ.get("PYTEST_XDIST_WORKER")
  475. if worker_id and worker_id != 'master':
  476. pytest.skip('must run single-threaded')
  477. def start_test_section(item):
  478. anchors[item.name] = log.start_section(item.name)
  479. def pytest_runtest_setup(item):
  480. """pytest hook: Configure (set up) a test item.
  481. Called once for each test to perform any custom configuration. This hook
  482. is used to skip the test if certain conditions apply.
  483. Args:
  484. item: The pytest test item.
  485. Returns:
  486. Nothing.
  487. """
  488. start_test_section(item)
  489. setup_boardspec(item)
  490. setup_buildconfigspec(item)
  491. setup_requiredtool(item)
  492. setup_singlethread(item)
  493. def pytest_runtest_protocol(item, nextitem):
  494. """pytest hook: Called to execute a test.
  495. This hook wraps the standard pytest runtestprotocol() function in order
  496. to acquire visibility into, and record, each test function's result.
  497. Args:
  498. item: The pytest test item to execute.
  499. nextitem: The pytest test item that will be executed after this one.
  500. Returns:
  501. A list of pytest reports (test result data).
  502. """
  503. log.get_and_reset_warning()
  504. ihook = item.ihook
  505. ihook.pytest_runtest_logstart(nodeid=item.nodeid, location=item.location)
  506. reports = runtestprotocol(item, nextitem=nextitem)
  507. ihook.pytest_runtest_logfinish(nodeid=item.nodeid, location=item.location)
  508. was_warning = log.get_and_reset_warning()
  509. # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
  510. # the test is skipped. That call is required to create the test's section
  511. # in the log file. The call to log.end_section() requires that the log
  512. # contain a section for this test. Create a section for the test if it
  513. # doesn't already exist.
  514. if not item.name in anchors:
  515. start_test_section(item)
  516. failure_cleanup = False
  517. if not was_warning:
  518. test_list = tests_passed
  519. msg = 'OK'
  520. msg_log = log.status_pass
  521. else:
  522. test_list = tests_warning
  523. msg = 'OK (with warning)'
  524. msg_log = log.status_warning
  525. for report in reports:
  526. if report.outcome == 'failed':
  527. if hasattr(report, 'wasxfail'):
  528. test_list = tests_xpassed
  529. msg = 'XPASSED'
  530. msg_log = log.status_xpass
  531. else:
  532. failure_cleanup = True
  533. test_list = tests_failed
  534. msg = 'FAILED:\n' + str(report.longrepr)
  535. msg_log = log.status_fail
  536. break
  537. if report.outcome == 'skipped':
  538. if hasattr(report, 'wasxfail'):
  539. failure_cleanup = True
  540. test_list = tests_xfailed
  541. msg = 'XFAILED:\n' + str(report.longrepr)
  542. msg_log = log.status_xfail
  543. break
  544. test_list = tests_skipped
  545. msg = 'SKIPPED:\n' + str(report.longrepr)
  546. msg_log = log.status_skipped
  547. if failure_cleanup:
  548. console.drain_console()
  549. test_list.append(item.name)
  550. tests_not_run.remove(item.name)
  551. try:
  552. msg_log(msg)
  553. except:
  554. # If something went wrong with logging, it's better to let the test
  555. # process continue, which may report other exceptions that triggered
  556. # the logging issue (e.g. console.log wasn't created). Hence, just
  557. # squash the exception. If the test setup failed due to e.g. syntax
  558. # error somewhere else, this won't be seen. However, once that issue
  559. # is fixed, if this exception still exists, it will then be logged as
  560. # part of the test's stdout.
  561. import traceback
  562. print('Exception occurred while logging runtest status:')
  563. traceback.print_exc()
  564. # FIXME: Can we force a test failure here?
  565. log.end_section(item.name)
  566. if failure_cleanup:
  567. console.cleanup_spawn()
  568. return True