conftest.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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'_u_boot_list_2_(.*)_test_2_\1_test_(.*)\s*$')
  192. def generate_ut_subtest(metafunc, fixture_name):
  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. Returns:
  201. Nothing.
  202. """
  203. fn = console.config.build_dir + '/u-boot.sym'
  204. try:
  205. with open(fn, 'rt') as f:
  206. lines = f.readlines()
  207. except:
  208. lines = []
  209. lines.sort()
  210. vals = []
  211. for l in lines:
  212. m = re_ut_test_list.search(l)
  213. if not m:
  214. continue
  215. vals.append(m.group(1) + ' ' + m.group(2))
  216. ids = ['ut_' + s.replace(' ', '_') for s in vals]
  217. metafunc.parametrize(fixture_name, vals, ids=ids)
  218. def generate_config(metafunc, fixture_name):
  219. """Provide parametrization for {env,brd}__ fixtures.
  220. If a test function takes parameter(s) (fixture names) of the form brd__xxx
  221. or env__xxx, the brd and env configuration dictionaries are consulted to
  222. find the list of values to use for those parameters, and the test is
  223. parametrized so that it runs once for each combination of values.
  224. Args:
  225. metafunc: The pytest test function.
  226. fixture_name: The fixture name to test.
  227. Returns:
  228. Nothing.
  229. """
  230. subconfigs = {
  231. 'brd': console.config.brd,
  232. 'env': console.config.env,
  233. }
  234. parts = fixture_name.split('__')
  235. if len(parts) < 2:
  236. return
  237. if parts[0] not in subconfigs:
  238. return
  239. subconfig = subconfigs[parts[0]]
  240. vals = []
  241. val = subconfig.get(fixture_name, [])
  242. # If that exact name is a key in the data source:
  243. if val:
  244. # ... use the dict value as a single parameter value.
  245. vals = (val, )
  246. else:
  247. # ... otherwise, see if there's a key that contains a list of
  248. # values to use instead.
  249. vals = subconfig.get(fixture_name+ 's', [])
  250. def fixture_id(index, val):
  251. try:
  252. return val['fixture_id']
  253. except:
  254. return fixture_name + str(index)
  255. ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
  256. metafunc.parametrize(fixture_name, vals, ids=ids)
  257. def pytest_generate_tests(metafunc):
  258. """pytest hook: parameterize test functions based on custom rules.
  259. Check each test function parameter (fixture name) to see if it is one of
  260. our custom names, and if so, provide the correct parametrization for that
  261. parameter.
  262. Args:
  263. metafunc: The pytest test function.
  264. Returns:
  265. Nothing.
  266. """
  267. for fn in metafunc.fixturenames:
  268. if fn == 'ut_subtest':
  269. generate_ut_subtest(metafunc, fn)
  270. continue
  271. generate_config(metafunc, fn)
  272. @pytest.fixture(scope='session')
  273. def u_boot_log(request):
  274. """Generate the value of a test's log fixture.
  275. Args:
  276. request: The pytest request.
  277. Returns:
  278. The fixture value.
  279. """
  280. return console.log
  281. @pytest.fixture(scope='session')
  282. def u_boot_config(request):
  283. """Generate the value of a test's u_boot_config fixture.
  284. Args:
  285. request: The pytest request.
  286. Returns:
  287. The fixture value.
  288. """
  289. return console.config
  290. @pytest.fixture(scope='function')
  291. def u_boot_console(request):
  292. """Generate the value of a test's u_boot_console fixture.
  293. Args:
  294. request: The pytest request.
  295. Returns:
  296. The fixture value.
  297. """
  298. console.ensure_spawned()
  299. return console
  300. anchors = {}
  301. tests_not_run = []
  302. tests_failed = []
  303. tests_xpassed = []
  304. tests_xfailed = []
  305. tests_skipped = []
  306. tests_warning = []
  307. tests_passed = []
  308. def pytest_itemcollected(item):
  309. """pytest hook: Called once for each test found during collection.
  310. This enables our custom result analysis code to see the list of all tests
  311. that should eventually be run.
  312. Args:
  313. item: The item that was collected.
  314. Returns:
  315. Nothing.
  316. """
  317. tests_not_run.append(item.name)
  318. def cleanup():
  319. """Clean up all global state.
  320. Executed (via atexit) once the entire test process is complete. This
  321. includes logging the status of all tests, and the identity of any failed
  322. or skipped tests.
  323. Args:
  324. None.
  325. Returns:
  326. Nothing.
  327. """
  328. if console:
  329. console.close()
  330. if log:
  331. with log.section('Status Report', 'status_report'):
  332. log.status_pass('%d passed' % len(tests_passed))
  333. if tests_warning:
  334. log.status_warning('%d passed with warning' % len(tests_warning))
  335. for test in tests_warning:
  336. anchor = anchors.get(test, None)
  337. log.status_warning('... ' + test, anchor)
  338. if tests_skipped:
  339. log.status_skipped('%d skipped' % len(tests_skipped))
  340. for test in tests_skipped:
  341. anchor = anchors.get(test, None)
  342. log.status_skipped('... ' + test, anchor)
  343. if tests_xpassed:
  344. log.status_xpass('%d xpass' % len(tests_xpassed))
  345. for test in tests_xpassed:
  346. anchor = anchors.get(test, None)
  347. log.status_xpass('... ' + test, anchor)
  348. if tests_xfailed:
  349. log.status_xfail('%d xfail' % len(tests_xfailed))
  350. for test in tests_xfailed:
  351. anchor = anchors.get(test, None)
  352. log.status_xfail('... ' + test, anchor)
  353. if tests_failed:
  354. log.status_fail('%d failed' % len(tests_failed))
  355. for test in tests_failed:
  356. anchor = anchors.get(test, None)
  357. log.status_fail('... ' + test, anchor)
  358. if tests_not_run:
  359. log.status_fail('%d not run' % len(tests_not_run))
  360. for test in tests_not_run:
  361. anchor = anchors.get(test, None)
  362. log.status_fail('... ' + test, anchor)
  363. log.close()
  364. atexit.register(cleanup)
  365. def setup_boardspec(item):
  366. """Process any 'boardspec' marker for a test.
  367. Such a marker lists the set of board types that a test does/doesn't
  368. support. If tests are being executed on an unsupported board, the test is
  369. marked to be skipped.
  370. Args:
  371. item: The pytest test item.
  372. Returns:
  373. Nothing.
  374. """
  375. required_boards = []
  376. for boards in item.iter_markers('boardspec'):
  377. board = boards.args[0]
  378. if board.startswith('!'):
  379. if ubconfig.board_type == board[1:]:
  380. pytest.skip('board "%s" not supported' % ubconfig.board_type)
  381. return
  382. else:
  383. required_boards.append(board)
  384. if required_boards and ubconfig.board_type not in required_boards:
  385. pytest.skip('board "%s" not supported' % ubconfig.board_type)
  386. def setup_buildconfigspec(item):
  387. """Process any 'buildconfigspec' marker for a test.
  388. Such a marker lists some U-Boot configuration feature that the test
  389. requires. If tests are being executed on an U-Boot build that doesn't
  390. have the required feature, the test is marked to be skipped.
  391. Args:
  392. item: The pytest test item.
  393. Returns:
  394. Nothing.
  395. """
  396. for options in item.iter_markers('buildconfigspec'):
  397. option = options.args[0]
  398. if not ubconfig.buildconfig.get('config_' + option.lower(), None):
  399. pytest.skip('.config feature "%s" not enabled' % option.lower())
  400. for options in item.iter_markers('notbuildconfigspec'):
  401. option = options.args[0]
  402. if ubconfig.buildconfig.get('config_' + option.lower(), None):
  403. pytest.skip('.config feature "%s" enabled' % option.lower())
  404. def tool_is_in_path(tool):
  405. for path in os.environ["PATH"].split(os.pathsep):
  406. fn = os.path.join(path, tool)
  407. if os.path.isfile(fn) and os.access(fn, os.X_OK):
  408. return True
  409. return False
  410. def setup_requiredtool(item):
  411. """Process any 'requiredtool' marker for a test.
  412. Such a marker lists some external tool (binary, executable, application)
  413. that the test requires. If tests are being executed on a system that
  414. doesn't have the required tool, the test is marked to be skipped.
  415. Args:
  416. item: The pytest test item.
  417. Returns:
  418. Nothing.
  419. """
  420. for tools in item.iter_markers('requiredtool'):
  421. tool = tools.args[0]
  422. if not tool_is_in_path(tool):
  423. pytest.skip('tool "%s" not in $PATH' % tool)
  424. def start_test_section(item):
  425. anchors[item.name] = log.start_section(item.name)
  426. def pytest_runtest_setup(item):
  427. """pytest hook: Configure (set up) a test item.
  428. Called once for each test to perform any custom configuration. This hook
  429. is used to skip the test if certain conditions apply.
  430. Args:
  431. item: The pytest test item.
  432. Returns:
  433. Nothing.
  434. """
  435. start_test_section(item)
  436. setup_boardspec(item)
  437. setup_buildconfigspec(item)
  438. setup_requiredtool(item)
  439. def pytest_runtest_protocol(item, nextitem):
  440. """pytest hook: Called to execute a test.
  441. This hook wraps the standard pytest runtestprotocol() function in order
  442. to acquire visibility into, and record, each test function's result.
  443. Args:
  444. item: The pytest test item to execute.
  445. nextitem: The pytest test item that will be executed after this one.
  446. Returns:
  447. A list of pytest reports (test result data).
  448. """
  449. log.get_and_reset_warning()
  450. reports = runtestprotocol(item, nextitem=nextitem)
  451. was_warning = log.get_and_reset_warning()
  452. # In pytest 3, runtestprotocol() may not call pytest_runtest_setup() if
  453. # the test is skipped. That call is required to create the test's section
  454. # in the log file. The call to log.end_section() requires that the log
  455. # contain a section for this test. Create a section for the test if it
  456. # doesn't already exist.
  457. if not item.name in anchors:
  458. start_test_section(item)
  459. failure_cleanup = False
  460. if not was_warning:
  461. test_list = tests_passed
  462. msg = 'OK'
  463. msg_log = log.status_pass
  464. else:
  465. test_list = tests_warning
  466. msg = 'OK (with warning)'
  467. msg_log = log.status_warning
  468. for report in reports:
  469. if report.outcome == 'failed':
  470. if hasattr(report, 'wasxfail'):
  471. test_list = tests_xpassed
  472. msg = 'XPASSED'
  473. msg_log = log.status_xpass
  474. else:
  475. failure_cleanup = True
  476. test_list = tests_failed
  477. msg = 'FAILED:\n' + str(report.longrepr)
  478. msg_log = log.status_fail
  479. break
  480. if report.outcome == 'skipped':
  481. if hasattr(report, 'wasxfail'):
  482. failure_cleanup = True
  483. test_list = tests_xfailed
  484. msg = 'XFAILED:\n' + str(report.longrepr)
  485. msg_log = log.status_xfail
  486. break
  487. test_list = tests_skipped
  488. msg = 'SKIPPED:\n' + str(report.longrepr)
  489. msg_log = log.status_skipped
  490. if failure_cleanup:
  491. console.drain_console()
  492. test_list.append(item.name)
  493. tests_not_run.remove(item.name)
  494. try:
  495. msg_log(msg)
  496. except:
  497. # If something went wrong with logging, it's better to let the test
  498. # process continue, which may report other exceptions that triggered
  499. # the logging issue (e.g. console.log wasn't created). Hence, just
  500. # squash the exception. If the test setup failed due to e.g. syntax
  501. # error somewhere else, this won't be seen. However, once that issue
  502. # is fixed, if this exception still exists, it will then be logged as
  503. # part of the test's stdout.
  504. import traceback
  505. print('Exception occurred while logging runtest status:')
  506. traceback.print_exc()
  507. # FIXME: Can we force a test failure here?
  508. log.end_section(item.name)
  509. if failure_cleanup:
  510. console.cleanup_spawn()
  511. return reports