conftest.py 12 KB

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