conftest.py 20 KB

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