kunit_tool_test.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. #!/usr/bin/env python3
  2. # SPDX-License-Identifier: GPL-2.0
  3. #
  4. # A collection of tests for tools/testing/kunit/kunit.py
  5. #
  6. # Copyright (C) 2019, Google LLC.
  7. # Author: Brendan Higgins <brendanhiggins@google.com>
  8. import unittest
  9. from unittest import mock
  10. import tempfile, shutil # Handling test_tmpdir
  11. import itertools
  12. import json
  13. import os
  14. import signal
  15. import subprocess
  16. from typing import Iterable
  17. import kunit_config
  18. import kunit_parser
  19. import kunit_kernel
  20. import kunit_json
  21. import kunit
  22. test_tmpdir = ''
  23. abs_test_data_dir = ''
  24. def setUpModule():
  25. global test_tmpdir, abs_test_data_dir
  26. test_tmpdir = tempfile.mkdtemp()
  27. abs_test_data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'test_data'))
  28. def tearDownModule():
  29. shutil.rmtree(test_tmpdir)
  30. def test_data_path(path):
  31. return os.path.join(abs_test_data_dir, path)
  32. class KconfigTest(unittest.TestCase):
  33. def test_is_subset_of(self):
  34. kconfig0 = kunit_config.Kconfig()
  35. self.assertTrue(kconfig0.is_subset_of(kconfig0))
  36. kconfig1 = kunit_config.Kconfig()
  37. kconfig1.add_entry('TEST', 'y')
  38. self.assertTrue(kconfig1.is_subset_of(kconfig1))
  39. self.assertTrue(kconfig0.is_subset_of(kconfig1))
  40. self.assertFalse(kconfig1.is_subset_of(kconfig0))
  41. def test_read_from_file(self):
  42. kconfig_path = test_data_path('test_read_from_file.kconfig')
  43. kconfig = kunit_config.parse_file(kconfig_path)
  44. expected_kconfig = kunit_config.Kconfig()
  45. expected_kconfig.add_entry('UML', 'y')
  46. expected_kconfig.add_entry('MMU', 'y')
  47. expected_kconfig.add_entry('TEST', 'y')
  48. expected_kconfig.add_entry('EXAMPLE_TEST', 'y')
  49. expected_kconfig.add_entry('MK8', 'n')
  50. self.assertEqual(kconfig, expected_kconfig)
  51. def test_write_to_file(self):
  52. kconfig_path = os.path.join(test_tmpdir, '.config')
  53. expected_kconfig = kunit_config.Kconfig()
  54. expected_kconfig.add_entry('UML', 'y')
  55. expected_kconfig.add_entry('MMU', 'y')
  56. expected_kconfig.add_entry('TEST', 'y')
  57. expected_kconfig.add_entry('EXAMPLE_TEST', 'y')
  58. expected_kconfig.add_entry('MK8', 'n')
  59. expected_kconfig.write_to_file(kconfig_path)
  60. actual_kconfig = kunit_config.parse_file(kconfig_path)
  61. self.assertEqual(actual_kconfig, expected_kconfig)
  62. class KUnitParserTest(unittest.TestCase):
  63. def setUp(self):
  64. self.print_mock = mock.patch('kunit_printer.Printer.print').start()
  65. self.addCleanup(mock.patch.stopall)
  66. def noPrintCallContains(self, substr: str):
  67. for call in self.print_mock.mock_calls:
  68. self.assertNotIn(substr, call.args[0])
  69. def assertContains(self, needle: str, haystack: kunit_parser.LineStream):
  70. # Clone the iterator so we can print the contents on failure.
  71. copy, backup = itertools.tee(haystack)
  72. for line in copy:
  73. if needle in line:
  74. return
  75. raise AssertionError(f'"{needle}" not found in {list(backup)}!')
  76. def test_output_isolated_correctly(self):
  77. log_path = test_data_path('test_output_isolated_correctly.log')
  78. with open(log_path) as file:
  79. result = kunit_parser.extract_tap_lines(file.readlines())
  80. self.assertContains('TAP version 14', result)
  81. self.assertContains('# Subtest: example', result)
  82. self.assertContains('1..2', result)
  83. self.assertContains('ok 1 - example_simple_test', result)
  84. self.assertContains('ok 2 - example_mock_test', result)
  85. self.assertContains('ok 1 - example', result)
  86. def test_output_with_prefix_isolated_correctly(self):
  87. log_path = test_data_path('test_pound_sign.log')
  88. with open(log_path) as file:
  89. result = kunit_parser.extract_tap_lines(file.readlines())
  90. self.assertContains('TAP version 14', result)
  91. self.assertContains('# Subtest: kunit-resource-test', result)
  92. self.assertContains('1..5', result)
  93. self.assertContains('ok 1 - kunit_resource_test_init_resources', result)
  94. self.assertContains('ok 2 - kunit_resource_test_alloc_resource', result)
  95. self.assertContains('ok 3 - kunit_resource_test_destroy_resource', result)
  96. self.assertContains('foo bar #', result)
  97. self.assertContains('ok 4 - kunit_resource_test_cleanup_resources', result)
  98. self.assertContains('ok 5 - kunit_resource_test_proper_free_ordering', result)
  99. self.assertContains('ok 1 - kunit-resource-test', result)
  100. self.assertContains('foo bar # non-kunit output', result)
  101. self.assertContains('# Subtest: kunit-try-catch-test', result)
  102. self.assertContains('1..2', result)
  103. self.assertContains('ok 1 - kunit_test_try_catch_successful_try_no_catch',
  104. result)
  105. self.assertContains('ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch',
  106. result)
  107. self.assertContains('ok 2 - kunit-try-catch-test', result)
  108. self.assertContains('# Subtest: string-stream-test', result)
  109. self.assertContains('1..3', result)
  110. self.assertContains('ok 1 - string_stream_test_empty_on_creation', result)
  111. self.assertContains('ok 2 - string_stream_test_not_empty_after_add', result)
  112. self.assertContains('ok 3 - string_stream_test_get_string', result)
  113. self.assertContains('ok 3 - string-stream-test', result)
  114. def test_parse_successful_test_log(self):
  115. all_passed_log = test_data_path('test_is_test_passed-all_passed.log')
  116. with open(all_passed_log) as file:
  117. result = kunit_parser.parse_run_tests(file.readlines())
  118. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  119. self.assertEqual(result.counts.errors, 0)
  120. def test_parse_successful_nested_tests_log(self):
  121. all_passed_log = test_data_path('test_is_test_passed-all_passed_nested.log')
  122. with open(all_passed_log) as file:
  123. result = kunit_parser.parse_run_tests(file.readlines())
  124. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  125. self.assertEqual(result.counts.errors, 0)
  126. def test_kselftest_nested(self):
  127. kselftest_log = test_data_path('test_is_test_passed-kselftest.log')
  128. with open(kselftest_log) as file:
  129. result = kunit_parser.parse_run_tests(file.readlines())
  130. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  131. self.assertEqual(result.counts.errors, 0)
  132. def test_parse_failed_test_log(self):
  133. failed_log = test_data_path('test_is_test_passed-failure.log')
  134. with open(failed_log) as file:
  135. result = kunit_parser.parse_run_tests(file.readlines())
  136. self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
  137. self.assertEqual(result.counts.errors, 0)
  138. def test_no_header(self):
  139. empty_log = test_data_path('test_is_test_passed-no_tests_run_no_header.log')
  140. with open(empty_log) as file:
  141. result = kunit_parser.parse_run_tests(
  142. kunit_parser.extract_tap_lines(file.readlines()))
  143. self.assertEqual(0, len(result.subtests))
  144. self.assertEqual(kunit_parser.TestStatus.FAILURE_TO_PARSE_TESTS, result.status)
  145. self.assertEqual(result.counts.errors, 1)
  146. def test_missing_test_plan(self):
  147. missing_plan_log = test_data_path('test_is_test_passed-'
  148. 'missing_plan.log')
  149. with open(missing_plan_log) as file:
  150. result = kunit_parser.parse_run_tests(
  151. kunit_parser.extract_tap_lines(
  152. file.readlines()))
  153. # A missing test plan is not an error.
  154. self.assertEqual(result.counts, kunit_parser.TestCounts(passed=10, errors=0))
  155. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  156. def test_no_tests(self):
  157. header_log = test_data_path('test_is_test_passed-no_tests_run_with_header.log')
  158. with open(header_log) as file:
  159. result = kunit_parser.parse_run_tests(
  160. kunit_parser.extract_tap_lines(file.readlines()))
  161. self.assertEqual(0, len(result.subtests))
  162. self.assertEqual(kunit_parser.TestStatus.NO_TESTS, result.status)
  163. self.assertEqual(result.counts.errors, 1)
  164. def test_no_tests_no_plan(self):
  165. no_plan_log = test_data_path('test_is_test_passed-no_tests_no_plan.log')
  166. with open(no_plan_log) as file:
  167. result = kunit_parser.parse_run_tests(
  168. kunit_parser.extract_tap_lines(file.readlines()))
  169. self.assertEqual(0, len(result.subtests[0].subtests[0].subtests))
  170. self.assertEqual(
  171. kunit_parser.TestStatus.NO_TESTS,
  172. result.subtests[0].subtests[0].status)
  173. self.assertEqual(result.counts, kunit_parser.TestCounts(passed=1, errors=1))
  174. def test_no_kunit_output(self):
  175. crash_log = test_data_path('test_insufficient_memory.log')
  176. print_mock = mock.patch('kunit_printer.Printer.print').start()
  177. with open(crash_log) as file:
  178. result = kunit_parser.parse_run_tests(
  179. kunit_parser.extract_tap_lines(file.readlines()))
  180. print_mock.assert_any_call(StrContains('Could not find any KTAP output.'))
  181. print_mock.stop()
  182. self.assertEqual(0, len(result.subtests))
  183. self.assertEqual(result.counts.errors, 1)
  184. def test_skipped_test(self):
  185. skipped_log = test_data_path('test_skip_tests.log')
  186. with open(skipped_log) as file:
  187. result = kunit_parser.parse_run_tests(file.readlines())
  188. # A skipped test does not fail the whole suite.
  189. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  190. self.assertEqual(result.counts, kunit_parser.TestCounts(passed=4, skipped=1))
  191. def test_skipped_all_tests(self):
  192. skipped_log = test_data_path('test_skip_all_tests.log')
  193. with open(skipped_log) as file:
  194. result = kunit_parser.parse_run_tests(file.readlines())
  195. self.assertEqual(kunit_parser.TestStatus.SKIPPED, result.status)
  196. self.assertEqual(result.counts, kunit_parser.TestCounts(skipped=5))
  197. def test_ignores_hyphen(self):
  198. hyphen_log = test_data_path('test_strip_hyphen.log')
  199. with open(hyphen_log) as file:
  200. result = kunit_parser.parse_run_tests(file.readlines())
  201. # A skipped test does not fail the whole suite.
  202. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  203. self.assertEqual(
  204. "sysctl_test",
  205. result.subtests[0].name)
  206. self.assertEqual(
  207. "example",
  208. result.subtests[1].name)
  209. def test_ignores_prefix_printk_time(self):
  210. prefix_log = test_data_path('test_config_printk_time.log')
  211. with open(prefix_log) as file:
  212. result = kunit_parser.parse_run_tests(file.readlines())
  213. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  214. self.assertEqual('kunit-resource-test', result.subtests[0].name)
  215. self.assertEqual(result.counts.errors, 0)
  216. def test_ignores_multiple_prefixes(self):
  217. prefix_log = test_data_path('test_multiple_prefixes.log')
  218. with open(prefix_log) as file:
  219. result = kunit_parser.parse_run_tests(file.readlines())
  220. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  221. self.assertEqual('kunit-resource-test', result.subtests[0].name)
  222. self.assertEqual(result.counts.errors, 0)
  223. def test_prefix_mixed_kernel_output(self):
  224. mixed_prefix_log = test_data_path('test_interrupted_tap_output.log')
  225. with open(mixed_prefix_log) as file:
  226. result = kunit_parser.parse_run_tests(file.readlines())
  227. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  228. self.assertEqual('kunit-resource-test', result.subtests[0].name)
  229. self.assertEqual(result.counts.errors, 0)
  230. def test_prefix_poundsign(self):
  231. pound_log = test_data_path('test_pound_sign.log')
  232. with open(pound_log) as file:
  233. result = kunit_parser.parse_run_tests(file.readlines())
  234. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  235. self.assertEqual('kunit-resource-test', result.subtests[0].name)
  236. self.assertEqual(result.counts.errors, 0)
  237. def test_kernel_panic_end(self):
  238. panic_log = test_data_path('test_kernel_panic_interrupt.log')
  239. with open(panic_log) as file:
  240. result = kunit_parser.parse_run_tests(file.readlines())
  241. self.assertEqual(kunit_parser.TestStatus.TEST_CRASHED, result.status)
  242. self.assertEqual('kunit-resource-test', result.subtests[0].name)
  243. self.assertGreaterEqual(result.counts.errors, 1)
  244. def test_pound_no_prefix(self):
  245. pound_log = test_data_path('test_pound_no_prefix.log')
  246. with open(pound_log) as file:
  247. result = kunit_parser.parse_run_tests(file.readlines())
  248. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  249. self.assertEqual('kunit-resource-test', result.subtests[0].name)
  250. self.assertEqual(result.counts.errors, 0)
  251. def test_summarize_failures(self):
  252. output = """
  253. KTAP version 1
  254. 1..2
  255. # Subtest: all_failed_suite
  256. 1..2
  257. not ok 1 - test1
  258. not ok 2 - test2
  259. not ok 1 - all_failed_suite
  260. # Subtest: some_failed_suite
  261. 1..2
  262. ok 1 - test1
  263. not ok 2 - test2
  264. not ok 1 - some_failed_suite
  265. """
  266. result = kunit_parser.parse_run_tests(output.splitlines())
  267. self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
  268. self.assertEqual(kunit_parser._summarize_failed_tests(result),
  269. 'Failures: all_failed_suite, some_failed_suite.test2')
  270. def test_ktap_format(self):
  271. ktap_log = test_data_path('test_parse_ktap_output.log')
  272. with open(ktap_log) as file:
  273. result = kunit_parser.parse_run_tests(file.readlines())
  274. self.assertEqual(result.counts, kunit_parser.TestCounts(passed=3))
  275. self.assertEqual('suite', result.subtests[0].name)
  276. self.assertEqual('case_1', result.subtests[0].subtests[0].name)
  277. self.assertEqual('case_2', result.subtests[0].subtests[1].name)
  278. def test_parse_subtest_header(self):
  279. ktap_log = test_data_path('test_parse_subtest_header.log')
  280. with open(ktap_log) as file:
  281. kunit_parser.parse_run_tests(file.readlines())
  282. self.print_mock.assert_any_call(StrContains('suite (1 subtest)'))
  283. def test_parse_attributes(self):
  284. ktap_log = test_data_path('test_parse_attributes.log')
  285. with open(ktap_log) as file:
  286. result = kunit_parser.parse_run_tests(file.readlines())
  287. # Test should pass with no errors
  288. self.assertEqual(result.counts, kunit_parser.TestCounts(passed=1, errors=0))
  289. self.assertEqual(kunit_parser.TestStatus.SUCCESS, result.status)
  290. # Ensure suite header is parsed correctly
  291. self.print_mock.assert_any_call(StrContains('suite (1 subtest)'))
  292. # Ensure attributes in correct test log
  293. self.assertContains('# module: example', result.subtests[0].log)
  294. self.assertContains('# test.speed: slow', result.subtests[0].subtests[0].log)
  295. def test_show_test_output_on_failure(self):
  296. output = """
  297. KTAP version 1
  298. 1..1
  299. Test output.
  300. Indented more.
  301. not ok 1 test1
  302. """
  303. result = kunit_parser.parse_run_tests(output.splitlines())
  304. self.assertEqual(kunit_parser.TestStatus.FAILURE, result.status)
  305. self.print_mock.assert_any_call(StrContains('Test output.'))
  306. self.print_mock.assert_any_call(StrContains(' Indented more.'))
  307. self.noPrintCallContains('not ok 1 test1')
  308. def line_stream_from_strs(strs: Iterable[str]) -> kunit_parser.LineStream:
  309. return kunit_parser.LineStream(enumerate(strs, start=1))
  310. class LineStreamTest(unittest.TestCase):
  311. def test_basic(self):
  312. stream = line_stream_from_strs(['hello', 'world'])
  313. self.assertTrue(stream, msg='Should be more input')
  314. self.assertEqual(stream.line_number(), 1)
  315. self.assertEqual(stream.peek(), 'hello')
  316. self.assertEqual(stream.pop(), 'hello')
  317. self.assertTrue(stream, msg='Should be more input')
  318. self.assertEqual(stream.line_number(), 2)
  319. self.assertEqual(stream.peek(), 'world')
  320. self.assertEqual(stream.pop(), 'world')
  321. self.assertFalse(stream, msg='Should be no more input')
  322. with self.assertRaisesRegex(ValueError, 'LineStream: going past EOF'):
  323. stream.pop()
  324. def test_is_lazy(self):
  325. called_times = 0
  326. def generator():
  327. nonlocal called_times
  328. for _ in range(1,5):
  329. called_times += 1
  330. yield called_times, str(called_times)
  331. stream = kunit_parser.LineStream(generator())
  332. self.assertEqual(called_times, 0)
  333. self.assertEqual(stream.pop(), '1')
  334. self.assertEqual(called_times, 1)
  335. self.assertEqual(stream.pop(), '2')
  336. self.assertEqual(called_times, 2)
  337. class LinuxSourceTreeTest(unittest.TestCase):
  338. def setUp(self):
  339. mock.patch.object(signal, 'signal').start()
  340. self.addCleanup(mock.patch.stopall)
  341. def test_invalid_kunitconfig(self):
  342. with self.assertRaisesRegex(kunit_kernel.ConfigError, 'nonexistent.* does not exist'):
  343. kunit_kernel.LinuxSourceTree('', kunitconfig_paths=['/nonexistent_file'])
  344. def test_valid_kunitconfig(self):
  345. with tempfile.NamedTemporaryFile('wt') as kunitconfig:
  346. kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[kunitconfig.name])
  347. def test_dir_kunitconfig(self):
  348. with tempfile.TemporaryDirectory('') as dir:
  349. with open(os.path.join(dir, '.kunitconfig'), 'w'):
  350. pass
  351. kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[dir])
  352. def test_multiple_kunitconfig(self):
  353. want_kconfig = kunit_config.Kconfig()
  354. want_kconfig.add_entry('KUNIT', 'y')
  355. want_kconfig.add_entry('KUNIT_TEST', 'm')
  356. with tempfile.TemporaryDirectory('') as dir:
  357. other = os.path.join(dir, 'otherkunitconfig')
  358. with open(os.path.join(dir, '.kunitconfig'), 'w') as f:
  359. f.write('CONFIG_KUNIT=y')
  360. with open(other, 'w') as f:
  361. f.write('CONFIG_KUNIT_TEST=m')
  362. pass
  363. tree = kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[dir, other])
  364. self.assertTrue(want_kconfig.is_subset_of(tree._kconfig), msg=tree._kconfig)
  365. def test_multiple_kunitconfig_invalid(self):
  366. with tempfile.TemporaryDirectory('') as dir:
  367. other = os.path.join(dir, 'otherkunitconfig')
  368. with open(os.path.join(dir, '.kunitconfig'), 'w') as f:
  369. f.write('CONFIG_KUNIT=y')
  370. with open(other, 'w') as f:
  371. f.write('CONFIG_KUNIT=m')
  372. with self.assertRaisesRegex(kunit_kernel.ConfigError, '(?s)Multiple values.*CONFIG_KUNIT'):
  373. kunit_kernel.LinuxSourceTree('', kunitconfig_paths=[dir, other])
  374. def test_kconfig_add(self):
  375. want_kconfig = kunit_config.Kconfig()
  376. want_kconfig.add_entry('NOT_REAL', 'y')
  377. tree = kunit_kernel.LinuxSourceTree('', kconfig_add=['CONFIG_NOT_REAL=y'])
  378. self.assertTrue(want_kconfig.is_subset_of(tree._kconfig), msg=tree._kconfig)
  379. def test_invalid_arch(self):
  380. with self.assertRaisesRegex(kunit_kernel.ConfigError, 'not a valid arch, options are.*x86_64'):
  381. kunit_kernel.LinuxSourceTree('', arch='invalid')
  382. def test_run_kernel_hits_exception(self):
  383. def fake_start(unused_args, unused_build_dir):
  384. return subprocess.Popen(['echo "hi\nbye"'], shell=True, text=True, stdout=subprocess.PIPE)
  385. with tempfile.TemporaryDirectory('') as build_dir:
  386. tree = kunit_kernel.LinuxSourceTree(build_dir)
  387. mock.patch.object(tree._ops, 'start', side_effect=fake_start).start()
  388. with self.assertRaises(ValueError):
  389. for line in tree.run_kernel(build_dir=build_dir):
  390. self.assertEqual(line, 'hi\n')
  391. raise ValueError('uh oh, did not read all output')
  392. with open(kunit_kernel.get_outfile_path(build_dir), 'rt') as outfile:
  393. self.assertEqual(outfile.read(), 'hi\nbye\n', msg='Missing some output')
  394. def test_build_reconfig_no_config(self):
  395. with tempfile.TemporaryDirectory('') as build_dir:
  396. with open(kunit_kernel.get_kunitconfig_path(build_dir), 'w') as f:
  397. f.write('CONFIG_KUNIT=y')
  398. tree = kunit_kernel.LinuxSourceTree(build_dir)
  399. # Stub out the source tree operations, so we don't have
  400. # the defaults for any given architecture get in the
  401. # way.
  402. tree._ops = kunit_kernel.LinuxSourceTreeOperations('none', None)
  403. mock_build_config = mock.patch.object(tree, 'build_config').start()
  404. # Should generate the .config
  405. self.assertTrue(tree.build_reconfig(build_dir, make_options=[]))
  406. mock_build_config.assert_called_once_with(build_dir, [])
  407. def test_build_reconfig_existing_config(self):
  408. with tempfile.TemporaryDirectory('') as build_dir:
  409. # Existing .config is a superset, should not touch it
  410. with open(kunit_kernel.get_kunitconfig_path(build_dir), 'w') as f:
  411. f.write('CONFIG_KUNIT=y')
  412. with open(kunit_kernel.get_old_kunitconfig_path(build_dir), 'w') as f:
  413. f.write('CONFIG_KUNIT=y')
  414. with open(kunit_kernel.get_kconfig_path(build_dir), 'w') as f:
  415. f.write('CONFIG_KUNIT=y\nCONFIG_KUNIT_TEST=y')
  416. tree = kunit_kernel.LinuxSourceTree(build_dir)
  417. # Stub out the source tree operations, so we don't have
  418. # the defaults for any given architecture get in the
  419. # way.
  420. tree._ops = kunit_kernel.LinuxSourceTreeOperations('none', None)
  421. mock_build_config = mock.patch.object(tree, 'build_config').start()
  422. self.assertTrue(tree.build_reconfig(build_dir, make_options=[]))
  423. self.assertEqual(mock_build_config.call_count, 0)
  424. def test_build_reconfig_remove_option(self):
  425. with tempfile.TemporaryDirectory('') as build_dir:
  426. # We removed CONFIG_KUNIT_TEST=y from our .kunitconfig...
  427. with open(kunit_kernel.get_kunitconfig_path(build_dir), 'w') as f:
  428. f.write('CONFIG_KUNIT=y')
  429. with open(kunit_kernel.get_old_kunitconfig_path(build_dir), 'w') as f:
  430. f.write('CONFIG_KUNIT=y\nCONFIG_KUNIT_TEST=y')
  431. with open(kunit_kernel.get_kconfig_path(build_dir), 'w') as f:
  432. f.write('CONFIG_KUNIT=y\nCONFIG_KUNIT_TEST=y')
  433. tree = kunit_kernel.LinuxSourceTree(build_dir)
  434. # Stub out the source tree operations, so we don't have
  435. # the defaults for any given architecture get in the
  436. # way.
  437. tree._ops = kunit_kernel.LinuxSourceTreeOperations('none', None)
  438. mock_build_config = mock.patch.object(tree, 'build_config').start()
  439. # ... so we should trigger a call to build_config()
  440. self.assertTrue(tree.build_reconfig(build_dir, make_options=[]))
  441. mock_build_config.assert_called_once_with(build_dir, [])
  442. # TODO: add more test cases.
  443. class KUnitJsonTest(unittest.TestCase):
  444. def setUp(self):
  445. self.print_mock = mock.patch('kunit_printer.Printer.print').start()
  446. self.addCleanup(mock.patch.stopall)
  447. def _json_for(self, log_file):
  448. with open(test_data_path(log_file)) as file:
  449. test_result = kunit_parser.parse_run_tests(file)
  450. json_obj = kunit_json.get_json_result(
  451. test=test_result,
  452. metadata=kunit_json.Metadata())
  453. return json.loads(json_obj)
  454. def test_failed_test_json(self):
  455. result = self._json_for('test_is_test_passed-failure.log')
  456. self.assertEqual(
  457. {'name': 'example_simple_test', 'status': 'FAIL'},
  458. result["sub_groups"][1]["test_cases"][0])
  459. def test_crashed_test_json(self):
  460. result = self._json_for('test_kernel_panic_interrupt.log')
  461. self.assertEqual(
  462. {'name': '', 'status': 'ERROR'},
  463. result["sub_groups"][2]["test_cases"][1])
  464. def test_skipped_test_json(self):
  465. result = self._json_for('test_skip_tests.log')
  466. self.assertEqual(
  467. {'name': 'example_skip_test', 'status': 'SKIP'},
  468. result["sub_groups"][1]["test_cases"][1])
  469. def test_no_tests_json(self):
  470. result = self._json_for('test_is_test_passed-no_tests_run_with_header.log')
  471. self.assertEqual(0, len(result['sub_groups']))
  472. def test_nested_json(self):
  473. result = self._json_for('test_is_test_passed-all_passed_nested.log')
  474. self.assertEqual(
  475. {'name': 'example_simple_test', 'status': 'PASS'},
  476. result["sub_groups"][0]["sub_groups"][0]["test_cases"][0])
  477. class StrContains(str):
  478. def __eq__(self, other):
  479. return self in other
  480. class KUnitMainTest(unittest.TestCase):
  481. def setUp(self):
  482. path = test_data_path('test_is_test_passed-all_passed.log')
  483. with open(path) as file:
  484. all_passed_log = file.readlines()
  485. self.print_mock = mock.patch('kunit_printer.Printer.print').start()
  486. self.addCleanup(mock.patch.stopall)
  487. self.mock_linux_init = mock.patch.object(kunit_kernel, 'LinuxSourceTree').start()
  488. self.linux_source_mock = self.mock_linux_init.return_value
  489. self.linux_source_mock.build_reconfig.return_value = True
  490. self.linux_source_mock.build_kernel.return_value = True
  491. self.linux_source_mock.run_kernel.return_value = all_passed_log
  492. def test_config_passes_args_pass(self):
  493. kunit.main(['config', '--build_dir=.kunit'])
  494. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  495. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 0)
  496. def test_build_passes_args_pass(self):
  497. kunit.main(['build'])
  498. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  499. self.linux_source_mock.build_kernel.assert_called_once_with(kunit.get_default_jobs(), '.kunit', None)
  500. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 0)
  501. def test_exec_passes_args_pass(self):
  502. kunit.main(['exec'])
  503. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 0)
  504. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
  505. self.linux_source_mock.run_kernel.assert_called_once_with(
  506. args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
  507. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  508. def test_run_passes_args_pass(self):
  509. kunit.main(['run'])
  510. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  511. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
  512. self.linux_source_mock.run_kernel.assert_called_once_with(
  513. args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
  514. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  515. def test_exec_passes_args_fail(self):
  516. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  517. with self.assertRaises(SystemExit) as e:
  518. kunit.main(['exec'])
  519. self.assertEqual(e.exception.code, 1)
  520. def test_run_passes_args_fail(self):
  521. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  522. with self.assertRaises(SystemExit) as e:
  523. kunit.main(['run'])
  524. self.assertEqual(e.exception.code, 1)
  525. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  526. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
  527. self.print_mock.assert_any_call(StrContains('Could not find any KTAP output.'))
  528. def test_exec_no_tests(self):
  529. self.linux_source_mock.run_kernel = mock.Mock(return_value=['TAP version 14', '1..0'])
  530. with self.assertRaises(SystemExit) as e:
  531. kunit.main(['run'])
  532. self.assertEqual(e.exception.code, 1)
  533. self.linux_source_mock.run_kernel.assert_called_once_with(
  534. args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
  535. self.print_mock.assert_any_call(StrContains(' 0 tests run!'))
  536. def test_exec_raw_output(self):
  537. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  538. kunit.main(['exec', '--raw_output'])
  539. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
  540. for call in self.print_mock.call_args_list:
  541. self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
  542. self.assertNotEqual(call, mock.call(StrContains(' 0 tests run!')))
  543. def test_run_raw_output(self):
  544. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  545. kunit.main(['run', '--raw_output'])
  546. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  547. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
  548. for call in self.print_mock.call_args_list:
  549. self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
  550. self.assertNotEqual(call, mock.call(StrContains(' 0 tests run!')))
  551. def test_run_raw_output_kunit(self):
  552. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  553. kunit.main(['run', '--raw_output=kunit'])
  554. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  555. self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
  556. for call in self.print_mock.call_args_list:
  557. self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
  558. self.assertNotEqual(call, mock.call(StrContains(' 0 tests run')))
  559. def test_run_raw_output_invalid(self):
  560. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  561. with self.assertRaises(SystemExit) as e:
  562. kunit.main(['run', '--raw_output=invalid'])
  563. self.assertNotEqual(e.exception.code, 0)
  564. def test_run_raw_output_does_not_take_positional_args(self):
  565. # --raw_output is a string flag, but we don't want it to consume
  566. # any positional arguments, only ones after an '='
  567. self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
  568. kunit.main(['run', '--raw_output', 'filter_glob'])
  569. self.linux_source_mock.run_kernel.assert_called_once_with(
  570. args=None, build_dir='.kunit', filter_glob='filter_glob', filter='', filter_action=None, timeout=300)
  571. def test_exec_timeout(self):
  572. timeout = 3453
  573. kunit.main(['exec', '--timeout', str(timeout)])
  574. self.linux_source_mock.run_kernel.assert_called_once_with(
  575. args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=timeout)
  576. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  577. def test_run_timeout(self):
  578. timeout = 3453
  579. kunit.main(['run', '--timeout', str(timeout)])
  580. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  581. self.linux_source_mock.run_kernel.assert_called_once_with(
  582. args=None, build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=timeout)
  583. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  584. def test_run_builddir(self):
  585. build_dir = '.kunit'
  586. kunit.main(['run', '--build_dir=.kunit'])
  587. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  588. self.linux_source_mock.run_kernel.assert_called_once_with(
  589. args=None, build_dir=build_dir, filter_glob='', filter='', filter_action=None, timeout=300)
  590. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  591. def test_config_builddir(self):
  592. build_dir = '.kunit'
  593. kunit.main(['config', '--build_dir', build_dir])
  594. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  595. def test_build_builddir(self):
  596. build_dir = '.kunit'
  597. jobs = kunit.get_default_jobs()
  598. kunit.main(['build', '--build_dir', build_dir])
  599. self.linux_source_mock.build_kernel.assert_called_once_with(jobs, build_dir, None)
  600. def test_exec_builddir(self):
  601. build_dir = '.kunit'
  602. kunit.main(['exec', '--build_dir', build_dir])
  603. self.linux_source_mock.run_kernel.assert_called_once_with(
  604. args=None, build_dir=build_dir, filter_glob='', filter='', filter_action=None, timeout=300)
  605. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  606. def test_run_kunitconfig(self):
  607. kunit.main(['run', '--kunitconfig=mykunitconfig'])
  608. # Just verify that we parsed and initialized it correctly here.
  609. self.mock_linux_init.assert_called_once_with('.kunit',
  610. kunitconfig_paths=['mykunitconfig'],
  611. kconfig_add=None,
  612. arch='um',
  613. cross_compile=None,
  614. qemu_config_path=None,
  615. extra_qemu_args=[])
  616. def test_config_kunitconfig(self):
  617. kunit.main(['config', '--kunitconfig=mykunitconfig'])
  618. # Just verify that we parsed and initialized it correctly here.
  619. self.mock_linux_init.assert_called_once_with('.kunit',
  620. kunitconfig_paths=['mykunitconfig'],
  621. kconfig_add=None,
  622. arch='um',
  623. cross_compile=None,
  624. qemu_config_path=None,
  625. extra_qemu_args=[])
  626. def test_config_alltests(self):
  627. kunit.main(['config', '--kunitconfig=mykunitconfig', '--alltests'])
  628. # Just verify that we parsed and initialized it correctly here.
  629. self.mock_linux_init.assert_called_once_with('.kunit',
  630. kunitconfig_paths=[kunit_kernel.ALL_TESTS_CONFIG_PATH, 'mykunitconfig'],
  631. kconfig_add=None,
  632. arch='um',
  633. cross_compile=None,
  634. qemu_config_path=None,
  635. extra_qemu_args=[])
  636. @mock.patch.object(kunit_kernel, 'LinuxSourceTree')
  637. def test_run_multiple_kunitconfig(self, mock_linux_init):
  638. mock_linux_init.return_value = self.linux_source_mock
  639. kunit.main(['run', '--kunitconfig=mykunitconfig', '--kunitconfig=other'])
  640. # Just verify that we parsed and initialized it correctly here.
  641. mock_linux_init.assert_called_once_with('.kunit',
  642. kunitconfig_paths=['mykunitconfig', 'other'],
  643. kconfig_add=None,
  644. arch='um',
  645. cross_compile=None,
  646. qemu_config_path=None,
  647. extra_qemu_args=[])
  648. def test_run_kconfig_add(self):
  649. kunit.main(['run', '--kconfig_add=CONFIG_KASAN=y', '--kconfig_add=CONFIG_KCSAN=y'])
  650. # Just verify that we parsed and initialized it correctly here.
  651. self.mock_linux_init.assert_called_once_with('.kunit',
  652. kunitconfig_paths=[],
  653. kconfig_add=['CONFIG_KASAN=y', 'CONFIG_KCSAN=y'],
  654. arch='um',
  655. cross_compile=None,
  656. qemu_config_path=None,
  657. extra_qemu_args=[])
  658. def test_run_qemu_args(self):
  659. kunit.main(['run', '--arch=x86_64', '--qemu_args', '-m 2048'])
  660. # Just verify that we parsed and initialized it correctly here.
  661. self.mock_linux_init.assert_called_once_with('.kunit',
  662. kunitconfig_paths=[],
  663. kconfig_add=None,
  664. arch='x86_64',
  665. cross_compile=None,
  666. qemu_config_path=None,
  667. extra_qemu_args=['-m', '2048'])
  668. def test_run_kernel_args(self):
  669. kunit.main(['run', '--kernel_args=a=1', '--kernel_args=b=2'])
  670. self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
  671. self.linux_source_mock.run_kernel.assert_called_once_with(
  672. args=['a=1','b=2'], build_dir='.kunit', filter_glob='', filter='', filter_action=None, timeout=300)
  673. self.print_mock.assert_any_call(StrContains('Testing complete.'))
  674. def test_list_tests(self):
  675. want = ['suite.test1', 'suite.test2', 'suite2.test1']
  676. self.linux_source_mock.run_kernel.return_value = ['TAP version 14', 'init: random output'] + want
  677. got = kunit._list_tests(self.linux_source_mock,
  678. kunit.KunitExecRequest(None, None, '.kunit', 300, 'suite*', '', None, None, 'suite', False, False))
  679. self.assertEqual(got, want)
  680. # Should respect the user's filter glob when listing tests.
  681. self.linux_source_mock.run_kernel.assert_called_once_with(
  682. args=['kunit.action=list'], build_dir='.kunit', filter_glob='suite*', filter='', filter_action=None, timeout=300)
  683. @mock.patch.object(kunit, '_list_tests')
  684. def test_run_isolated_by_suite(self, mock_tests):
  685. mock_tests.return_value = ['suite.test1', 'suite.test2', 'suite2.test1']
  686. kunit.main(['exec', '--run_isolated=suite', 'suite*.test*'])
  687. # Should respect the user's filter glob when listing tests.
  688. mock_tests.assert_called_once_with(mock.ANY,
  689. kunit.KunitExecRequest(None, None, '.kunit', 300, 'suite*.test*', '', None, None, 'suite', False, False))
  690. self.linux_source_mock.run_kernel.assert_has_calls([
  691. mock.call(args=None, build_dir='.kunit', filter_glob='suite.test*', filter='', filter_action=None, timeout=300),
  692. mock.call(args=None, build_dir='.kunit', filter_glob='suite2.test*', filter='', filter_action=None, timeout=300),
  693. ])
  694. @mock.patch.object(kunit, '_list_tests')
  695. def test_run_isolated_by_test(self, mock_tests):
  696. mock_tests.return_value = ['suite.test1', 'suite.test2', 'suite2.test1']
  697. kunit.main(['exec', '--run_isolated=test', 'suite*'])
  698. # Should respect the user's filter glob when listing tests.
  699. mock_tests.assert_called_once_with(mock.ANY,
  700. kunit.KunitExecRequest(None, None, '.kunit', 300, 'suite*', '', None, None, 'test', False, False))
  701. self.linux_source_mock.run_kernel.assert_has_calls([
  702. mock.call(args=None, build_dir='.kunit', filter_glob='suite.test1', filter='', filter_action=None, timeout=300),
  703. mock.call(args=None, build_dir='.kunit', filter_glob='suite.test2', filter='', filter_action=None, timeout=300),
  704. mock.call(args=None, build_dir='.kunit', filter_glob='suite2.test1', filter='', filter_action=None, timeout=300),
  705. ])
  706. if __name__ == '__main__':
  707. unittest.main()