conftest.py 18 KB

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