conftest.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 pexpect
  19. import pytest
  20. from _pytest.runner import runtestprotocol
  21. import ConfigParser
  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. runner = log.get_runner('make', sys.stdout)
  108. for cmd in cmds:
  109. runner.run(cmd, cwd=source_dir)
  110. runner.close()
  111. class ArbitraryAttributeContainer(object):
  112. pass
  113. ubconfig = ArbitraryAttributeContainer()
  114. ubconfig.brd = dict()
  115. ubconfig.env = dict()
  116. modules = [
  117. (ubconfig.brd, 'u_boot_board_' + board_type_filename),
  118. (ubconfig.env, 'u_boot_boardenv_' + board_type_filename),
  119. (ubconfig.env, 'u_boot_boardenv_' + board_type_filename + '_' +
  120. board_identity_filename),
  121. ]
  122. for (dict_to_fill, module_name) in modules:
  123. try:
  124. module = __import__(module_name)
  125. except ImportError:
  126. continue
  127. dict_to_fill.update(module.__dict__)
  128. ubconfig.buildconfig = dict()
  129. for conf_file in ('.config', 'include/autoconf.mk'):
  130. dot_config = build_dir + '/' + conf_file
  131. if not os.path.exists(dot_config):
  132. raise Exception(conf_file + ' does not exist; ' +
  133. 'try passing --build option?')
  134. with open(dot_config, 'rt') as f:
  135. ini_str = '[root]\n' + f.read()
  136. ini_sio = StringIO.StringIO(ini_str)
  137. parser = ConfigParser.RawConfigParser()
  138. parser.readfp(ini_sio)
  139. ubconfig.buildconfig.update(parser.items('root'))
  140. ubconfig.test_py_dir = test_py_dir
  141. ubconfig.source_dir = source_dir
  142. ubconfig.build_dir = build_dir
  143. ubconfig.result_dir = result_dir
  144. ubconfig.persistent_data_dir = persistent_data_dir
  145. ubconfig.board_type = board_type
  146. ubconfig.board_identity = board_identity
  147. ubconfig.gdbserver = gdbserver
  148. env_vars = (
  149. 'board_type',
  150. 'board_identity',
  151. 'source_dir',
  152. 'test_py_dir',
  153. 'build_dir',
  154. 'result_dir',
  155. 'persistent_data_dir',
  156. )
  157. for v in env_vars:
  158. os.environ['U_BOOT_' + v.upper()] = getattr(ubconfig, v)
  159. if board_type == 'sandbox':
  160. import u_boot_console_sandbox
  161. console = u_boot_console_sandbox.ConsoleSandbox(log, ubconfig)
  162. else:
  163. import u_boot_console_exec_attach
  164. console = u_boot_console_exec_attach.ConsoleExecAttach(log, ubconfig)
  165. def pytest_generate_tests(metafunc):
  166. """pytest hook: parameterize test functions based on custom rules.
  167. If a test function takes parameter(s) (fixture names) of the form brd__xxx
  168. or env__xxx, the brd and env configuration dictionaries are consulted to
  169. find the list of values to use for those parameters, and the test is
  170. parametrized so that it runs once for each combination of values.
  171. Args:
  172. metafunc: The pytest test function.
  173. Returns:
  174. Nothing.
  175. """
  176. subconfigs = {
  177. 'brd': console.config.brd,
  178. 'env': console.config.env,
  179. }
  180. for fn in metafunc.fixturenames:
  181. parts = fn.split('__')
  182. if len(parts) < 2:
  183. continue
  184. if parts[0] not in subconfigs:
  185. continue
  186. subconfig = subconfigs[parts[0]]
  187. vals = []
  188. val = subconfig.get(fn, [])
  189. # If that exact name is a key in the data source:
  190. if val:
  191. # ... use the dict value as a single parameter value.
  192. vals = (val, )
  193. else:
  194. # ... otherwise, see if there's a key that contains a list of
  195. # values to use instead.
  196. vals = subconfig.get(fn + 's', [])
  197. def fixture_id(index, val):
  198. try:
  199. return val["fixture_id"]
  200. except:
  201. return fn + str(index)
  202. ids = [fixture_id(index, val) for (index, val) in enumerate(vals)]
  203. metafunc.parametrize(fn, vals, ids=ids)
  204. @pytest.fixture(scope='function')
  205. def u_boot_console(request):
  206. """Generate the value of a test's u_boot_console fixture.
  207. Args:
  208. request: The pytest request.
  209. Returns:
  210. The fixture value.
  211. """
  212. console.ensure_spawned()
  213. return console
  214. tests_not_run = set()
  215. tests_failed = set()
  216. tests_xpassed = set()
  217. tests_xfailed = set()
  218. tests_skipped = set()
  219. tests_passed = set()
  220. def pytest_itemcollected(item):
  221. """pytest hook: Called once for each test found during collection.
  222. This enables our custom result analysis code to see the list of all tests
  223. that should eventually be run.
  224. Args:
  225. item: The item that was collected.
  226. Returns:
  227. Nothing.
  228. """
  229. tests_not_run.add(item.name)
  230. def cleanup():
  231. """Clean up all global state.
  232. Executed (via atexit) once the entire test process is complete. This
  233. includes logging the status of all tests, and the identity of any failed
  234. or skipped tests.
  235. Args:
  236. None.
  237. Returns:
  238. Nothing.
  239. """
  240. if console:
  241. console.close()
  242. if log:
  243. log.status_pass('%d passed' % len(tests_passed))
  244. if tests_skipped:
  245. log.status_skipped('%d skipped' % len(tests_skipped))
  246. for test in tests_skipped:
  247. log.status_skipped('... ' + test)
  248. if tests_xpassed:
  249. log.status_xpass('%d xpass' % len(tests_xpassed))
  250. for test in tests_xpassed:
  251. log.status_xpass('... ' + test)
  252. if tests_xfailed:
  253. log.status_xfail('%d xfail' % len(tests_xfailed))
  254. for test in tests_xfailed:
  255. log.status_xfail('... ' + test)
  256. if tests_failed:
  257. log.status_fail('%d failed' % len(tests_failed))
  258. for test in tests_failed:
  259. log.status_fail('... ' + test)
  260. if tests_not_run:
  261. log.status_fail('%d not run' % len(tests_not_run))
  262. for test in tests_not_run:
  263. log.status_fail('... ' + test)
  264. log.close()
  265. atexit.register(cleanup)
  266. def setup_boardspec(item):
  267. """Process any 'boardspec' marker for a test.
  268. Such a marker lists the set of board types that a test does/doesn't
  269. support. If tests are being executed on an unsupported board, the test is
  270. marked to be skipped.
  271. Args:
  272. item: The pytest test item.
  273. Returns:
  274. Nothing.
  275. """
  276. mark = item.get_marker('boardspec')
  277. if not mark:
  278. return
  279. required_boards = []
  280. for board in mark.args:
  281. if board.startswith('!'):
  282. if ubconfig.board_type == board[1:]:
  283. pytest.skip('board not supported')
  284. return
  285. else:
  286. required_boards.append(board)
  287. if required_boards and ubconfig.board_type not in required_boards:
  288. pytest.skip('board not supported')
  289. def setup_buildconfigspec(item):
  290. """Process any 'buildconfigspec' marker for a test.
  291. Such a marker lists some U-Boot configuration feature that the test
  292. requires. If tests are being executed on an U-Boot build that doesn't
  293. have the required feature, the test is marked to be skipped.
  294. Args:
  295. item: The pytest test item.
  296. Returns:
  297. Nothing.
  298. """
  299. mark = item.get_marker('buildconfigspec')
  300. if not mark:
  301. return
  302. for option in mark.args:
  303. if not ubconfig.buildconfig.get('config_' + option.lower(), None):
  304. pytest.skip('.config feature not enabled')
  305. def pytest_runtest_setup(item):
  306. """pytest hook: Configure (set up) a test item.
  307. Called once for each test to perform any custom configuration. This hook
  308. is used to skip the test if certain conditions apply.
  309. Args:
  310. item: The pytest test item.
  311. Returns:
  312. Nothing.
  313. """
  314. log.start_section(item.name)
  315. setup_boardspec(item)
  316. setup_buildconfigspec(item)
  317. def pytest_runtest_protocol(item, nextitem):
  318. """pytest hook: Called to execute a test.
  319. This hook wraps the standard pytest runtestprotocol() function in order
  320. to acquire visibility into, and record, each test function's result.
  321. Args:
  322. item: The pytest test item to execute.
  323. nextitem: The pytest test item that will be executed after this one.
  324. Returns:
  325. A list of pytest reports (test result data).
  326. """
  327. reports = runtestprotocol(item, nextitem=nextitem)
  328. failure_cleanup = False
  329. test_list = tests_passed
  330. msg = 'OK'
  331. msg_log = log.status_pass
  332. for report in reports:
  333. if report.outcome == 'failed':
  334. if hasattr(report, 'wasxfail'):
  335. test_list = tests_xpassed
  336. msg = 'XPASSED'
  337. msg_log = log.status_xpass
  338. else:
  339. failure_cleanup = True
  340. test_list = tests_failed
  341. msg = 'FAILED:\n' + str(report.longrepr)
  342. msg_log = log.status_fail
  343. break
  344. if report.outcome == 'skipped':
  345. if hasattr(report, 'wasxfail'):
  346. failure_cleanup = True
  347. test_list = tests_xfailed
  348. msg = 'XFAILED:\n' + str(report.longrepr)
  349. msg_log = log.status_xfail
  350. break
  351. test_list = tests_skipped
  352. msg = 'SKIPPED:\n' + str(report.longrepr)
  353. msg_log = log.status_skipped
  354. if failure_cleanup:
  355. console.drain_console()
  356. test_list.add(item.name)
  357. tests_not_run.remove(item.name)
  358. try:
  359. msg_log(msg)
  360. except:
  361. # If something went wrong with logging, it's better to let the test
  362. # process continue, which may report other exceptions that triggered
  363. # the logging issue (e.g. console.log wasn't created). Hence, just
  364. # squash the exception. If the test setup failed due to e.g. syntax
  365. # error somewhere else, this won't be seen. However, once that issue
  366. # is fixed, if this exception still exists, it will then be logged as
  367. # part of the test's stdout.
  368. import traceback
  369. print 'Exception occurred while logging runtest status:'
  370. traceback.print_exc()
  371. # FIXME: Can we force a test failure here?
  372. log.end_section(item.name)
  373. if failure_cleanup:
  374. console.cleanup_spawn()
  375. return reports