conftest.py 17 KB

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