kunit_tool_test.py 38 KB

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