2 # SPDX-License-Identifier: GPL-2.0
4 # A collection of tests for tools/testing/kunit/kunit.py
6 # Copyright (C) 2019, Google LLC.
7 # Author: Brendan Higgins <brendanhiggins@google.com>
10 from unittest import mock
12 import tempfile, shutil # Handling test_tmpdir
26 abs_test_data_dir = ''
29 global test_tmpdir, abs_test_data_dir
30 test_tmpdir = tempfile.mkdtemp()
31 abs_test_data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'test_data'))
34 shutil.rmtree(test_tmpdir)
36 def test_data_path(path):
37 return os.path.join(abs_test_data_dir, path)
39 class KconfigTest(unittest.TestCase):
41 def test_is_subset_of(self):
42 kconfig0 = kunit_config.Kconfig()
43 self.assertTrue(kconfig0.is_subset_of(kconfig0))
45 kconfig1 = kunit_config.Kconfig()
46 kconfig1.add_entry(kunit_config.KconfigEntry('TEST', 'y'))
47 self.assertTrue(kconfig1.is_subset_of(kconfig1))
48 self.assertTrue(kconfig0.is_subset_of(kconfig1))
49 self.assertFalse(kconfig1.is_subset_of(kconfig0))
51 def test_read_from_file(self):
52 kconfig = kunit_config.Kconfig()
53 kconfig_path = test_data_path('test_read_from_file.kconfig')
55 kconfig.read_from_file(kconfig_path)
57 expected_kconfig = kunit_config.Kconfig()
58 expected_kconfig.add_entry(
59 kunit_config.KconfigEntry('UML', 'y'))
60 expected_kconfig.add_entry(
61 kunit_config.KconfigEntry('MMU', 'y'))
62 expected_kconfig.add_entry(
63 kunit_config.KconfigEntry('TEST', 'y'))
64 expected_kconfig.add_entry(
65 kunit_config.KconfigEntry('EXAMPLE_TEST', 'y'))
66 expected_kconfig.add_entry(
67 kunit_config.KconfigEntry('MK8', 'n'))
69 self.assertEqual(kconfig.entries(), expected_kconfig.entries())
71 def test_write_to_file(self):
72 kconfig_path = os.path.join(test_tmpdir, '.config')
74 expected_kconfig = kunit_config.Kconfig()
75 expected_kconfig.add_entry(
76 kunit_config.KconfigEntry('UML', 'y'))
77 expected_kconfig.add_entry(
78 kunit_config.KconfigEntry('MMU', 'y'))
79 expected_kconfig.add_entry(
80 kunit_config.KconfigEntry('TEST', 'y'))
81 expected_kconfig.add_entry(
82 kunit_config.KconfigEntry('EXAMPLE_TEST', 'y'))
83 expected_kconfig.add_entry(
84 kunit_config.KconfigEntry('MK8', 'n'))
86 expected_kconfig.write_to_file(kconfig_path)
88 actual_kconfig = kunit_config.Kconfig()
89 actual_kconfig.read_from_file(kconfig_path)
91 self.assertEqual(actual_kconfig.entries(),
92 expected_kconfig.entries())
94 class KUnitParserTest(unittest.TestCase):
96 def assertContains(self, needle: str, haystack: kunit_parser.LineStream):
97 # Clone the iterator so we can print the contents on failure.
98 copy, backup = itertools.tee(haystack)
102 raise AssertionError(f'"{needle}" not found in {list(backup)}!')
104 def test_output_isolated_correctly(self):
105 log_path = test_data_path('test_output_isolated_correctly.log')
106 with open(log_path) as file:
107 result = kunit_parser.extract_tap_lines(file.readlines())
108 self.assertContains('TAP version 14', result)
109 self.assertContains(' # Subtest: example', result)
110 self.assertContains(' 1..2', result)
111 self.assertContains(' ok 1 - example_simple_test', result)
112 self.assertContains(' ok 2 - example_mock_test', result)
113 self.assertContains('ok 1 - example', result)
115 def test_output_with_prefix_isolated_correctly(self):
116 log_path = test_data_path('test_pound_sign.log')
117 with open(log_path) as file:
118 result = kunit_parser.extract_tap_lines(file.readlines())
119 self.assertContains('TAP version 14', result)
120 self.assertContains(' # Subtest: kunit-resource-test', result)
121 self.assertContains(' 1..5', result)
122 self.assertContains(' ok 1 - kunit_resource_test_init_resources', result)
123 self.assertContains(' ok 2 - kunit_resource_test_alloc_resource', result)
124 self.assertContains(' ok 3 - kunit_resource_test_destroy_resource', result)
125 self.assertContains(' foo bar #', result)
126 self.assertContains(' ok 4 - kunit_resource_test_cleanup_resources', result)
127 self.assertContains(' ok 5 - kunit_resource_test_proper_free_ordering', result)
128 self.assertContains('ok 1 - kunit-resource-test', result)
129 self.assertContains(' foo bar # non-kunit output', result)
130 self.assertContains(' # Subtest: kunit-try-catch-test', result)
131 self.assertContains(' 1..2', result)
132 self.assertContains(' ok 1 - kunit_test_try_catch_successful_try_no_catch',
134 self.assertContains(' ok 2 - kunit_test_try_catch_unsuccessful_try_does_catch',
136 self.assertContains('ok 2 - kunit-try-catch-test', result)
137 self.assertContains(' # Subtest: string-stream-test', result)
138 self.assertContains(' 1..3', result)
139 self.assertContains(' ok 1 - string_stream_test_empty_on_creation', result)
140 self.assertContains(' ok 2 - string_stream_test_not_empty_after_add', result)
141 self.assertContains(' ok 3 - string_stream_test_get_string', result)
142 self.assertContains('ok 3 - string-stream-test', result)
144 def test_parse_successful_test_log(self):
145 all_passed_log = test_data_path('test_is_test_passed-all_passed.log')
146 with open(all_passed_log) as file:
147 result = kunit_parser.parse_run_tests(file.readlines())
149 kunit_parser.TestStatus.SUCCESS,
152 def test_parse_failed_test_log(self):
153 failed_log = test_data_path('test_is_test_passed-failure.log')
154 with open(failed_log) as file:
155 result = kunit_parser.parse_run_tests(file.readlines())
157 kunit_parser.TestStatus.FAILURE,
160 def test_no_header(self):
161 empty_log = test_data_path('test_is_test_passed-no_tests_run_no_header.log')
162 with open(empty_log) as file:
163 result = kunit_parser.parse_run_tests(
164 kunit_parser.extract_tap_lines(file.readlines()))
165 self.assertEqual(0, len(result.suites))
167 kunit_parser.TestStatus.FAILURE_TO_PARSE_TESTS,
170 def test_no_tests(self):
171 empty_log = test_data_path('test_is_test_passed-no_tests_run_with_header.log')
172 with open(empty_log) as file:
173 result = kunit_parser.parse_run_tests(
174 kunit_parser.extract_tap_lines(file.readlines()))
175 self.assertEqual(0, len(result.suites))
177 kunit_parser.TestStatus.NO_TESTS,
180 def test_no_kunit_output(self):
181 crash_log = test_data_path('test_insufficient_memory.log')
182 print_mock = mock.patch('builtins.print').start()
183 with open(crash_log) as file:
184 result = kunit_parser.parse_run_tests(
185 kunit_parser.extract_tap_lines(file.readlines()))
186 print_mock.assert_any_call(StrContains('could not parse test results!'))
190 def test_crashed_test(self):
191 crashed_log = test_data_path('test_is_test_passed-crash.log')
192 with open(crashed_log) as file:
193 result = kunit_parser.parse_run_tests(file.readlines())
195 kunit_parser.TestStatus.TEST_CRASHED,
198 def test_skipped_test(self):
199 skipped_log = test_data_path('test_skip_tests.log')
200 file = open(skipped_log)
201 result = kunit_parser.parse_run_tests(file.readlines())
203 # A skipped test does not fail the whole suite.
205 kunit_parser.TestStatus.SUCCESS,
209 def test_skipped_all_tests(self):
210 skipped_log = test_data_path('test_skip_all_tests.log')
211 file = open(skipped_log)
212 result = kunit_parser.parse_run_tests(file.readlines())
215 kunit_parser.TestStatus.SKIPPED,
220 def test_ignores_prefix_printk_time(self):
221 prefix_log = test_data_path('test_config_printk_time.log')
222 with open(prefix_log) as file:
223 result = kunit_parser.parse_run_tests(file.readlines())
225 kunit_parser.TestStatus.SUCCESS,
227 self.assertEqual('kunit-resource-test', result.suites[0].name)
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())
234 kunit_parser.TestStatus.SUCCESS,
236 self.assertEqual('kunit-resource-test', result.suites[0].name)
238 def test_prefix_mixed_kernel_output(self):
239 mixed_prefix_log = test_data_path('test_interrupted_tap_output.log')
240 with open(mixed_prefix_log) as file:
241 result = kunit_parser.parse_run_tests(file.readlines())
243 kunit_parser.TestStatus.SUCCESS,
245 self.assertEqual('kunit-resource-test', result.suites[0].name)
247 def test_prefix_poundsign(self):
248 pound_log = test_data_path('test_pound_sign.log')
249 with open(pound_log) as file:
250 result = kunit_parser.parse_run_tests(file.readlines())
252 kunit_parser.TestStatus.SUCCESS,
254 self.assertEqual('kunit-resource-test', result.suites[0].name)
256 def test_kernel_panic_end(self):
257 panic_log = test_data_path('test_kernel_panic_interrupt.log')
258 with open(panic_log) as file:
259 result = kunit_parser.parse_run_tests(file.readlines())
261 kunit_parser.TestStatus.TEST_CRASHED,
263 self.assertEqual('kunit-resource-test', result.suites[0].name)
265 def test_pound_no_prefix(self):
266 pound_log = test_data_path('test_pound_no_prefix.log')
267 with open(pound_log) as file:
268 result = kunit_parser.parse_run_tests(file.readlines())
270 kunit_parser.TestStatus.SUCCESS,
272 self.assertEqual('kunit-resource-test', result.suites[0].name)
274 class LinuxSourceTreeTest(unittest.TestCase):
277 mock.patch.object(signal, 'signal').start()
278 self.addCleanup(mock.patch.stopall)
280 def test_invalid_kunitconfig(self):
281 with self.assertRaisesRegex(kunit_kernel.ConfigError, 'nonexistent.* does not exist'):
282 kunit_kernel.LinuxSourceTree('', kunitconfig_path='/nonexistent_file')
284 def test_valid_kunitconfig(self):
285 with tempfile.NamedTemporaryFile('wt') as kunitconfig:
286 tree = kunit_kernel.LinuxSourceTree('', kunitconfig_path=kunitconfig.name)
288 def test_dir_kunitconfig(self):
289 with tempfile.TemporaryDirectory('') as dir:
290 with open(os.path.join(dir, '.kunitconfig'), 'w') as f:
292 tree = kunit_kernel.LinuxSourceTree('', kunitconfig_path=dir)
294 # TODO: add more test cases.
297 class KUnitJsonTest(unittest.TestCase):
299 def _json_for(self, log_file):
300 with open(test_data_path(log_file)) as file:
301 test_result = kunit_parser.parse_run_tests(file)
302 json_obj = kunit_json.get_json_result(
303 test_result=test_result,
304 def_config='kunit_defconfig',
307 return json.loads(json_obj)
309 def test_failed_test_json(self):
310 result = self._json_for('test_is_test_passed-failure.log')
312 {'name': 'example_simple_test', 'status': 'FAIL'},
313 result["sub_groups"][1]["test_cases"][0])
315 def test_crashed_test_json(self):
316 result = self._json_for('test_is_test_passed-crash.log')
318 {'name': 'example_simple_test', 'status': 'ERROR'},
319 result["sub_groups"][1]["test_cases"][0])
321 def test_no_tests_json(self):
322 result = self._json_for('test_is_test_passed-no_tests_run_with_header.log')
323 self.assertEqual(0, len(result['sub_groups']))
325 class StrContains(str):
326 def __eq__(self, other):
329 class KUnitMainTest(unittest.TestCase):
331 path = test_data_path('test_is_test_passed-all_passed.log')
332 with open(path) as file:
333 all_passed_log = file.readlines()
335 self.print_mock = mock.patch('builtins.print').start()
336 self.addCleanup(mock.patch.stopall)
338 self.linux_source_mock = mock.Mock()
339 self.linux_source_mock.build_reconfig = mock.Mock(return_value=True)
340 self.linux_source_mock.build_kernel = mock.Mock(return_value=True)
341 self.linux_source_mock.run_kernel = mock.Mock(return_value=all_passed_log)
343 def test_config_passes_args_pass(self):
344 kunit.main(['config', '--build_dir=.kunit'], self.linux_source_mock)
345 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
346 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 0)
348 def test_build_passes_args_pass(self):
349 kunit.main(['build'], self.linux_source_mock)
350 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 0)
351 self.linux_source_mock.build_kernel.assert_called_once_with(False, 8, '.kunit', None)
352 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 0)
354 def test_exec_passes_args_pass(self):
355 kunit.main(['exec'], self.linux_source_mock)
356 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 0)
357 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
358 self.linux_source_mock.run_kernel.assert_called_once_with(
359 args=None, build_dir='.kunit', filter_glob='', timeout=300)
360 self.print_mock.assert_any_call(StrContains('Testing complete.'))
362 def test_run_passes_args_pass(self):
363 kunit.main(['run'], self.linux_source_mock)
364 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
365 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
366 self.linux_source_mock.run_kernel.assert_called_once_with(
367 args=None, build_dir='.kunit', filter_glob='', timeout=300)
368 self.print_mock.assert_any_call(StrContains('Testing complete.'))
370 def test_exec_passes_args_fail(self):
371 self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
372 with self.assertRaises(SystemExit) as e:
373 kunit.main(['exec'], self.linux_source_mock)
374 self.assertEqual(e.exception.code, 1)
376 def test_run_passes_args_fail(self):
377 self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
378 with self.assertRaises(SystemExit) as e:
379 kunit.main(['run'], self.linux_source_mock)
380 self.assertEqual(e.exception.code, 1)
381 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
382 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
383 self.print_mock.assert_any_call(StrContains(' 0 tests run'))
385 def test_exec_raw_output(self):
386 self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
387 kunit.main(['exec', '--raw_output'], self.linux_source_mock)
388 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
389 for call in self.print_mock.call_args_list:
390 self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
391 self.assertNotEqual(call, mock.call(StrContains(' 0 tests run')))
393 def test_run_raw_output(self):
394 self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
395 kunit.main(['run', '--raw_output'], self.linux_source_mock)
396 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
397 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
398 for call in self.print_mock.call_args_list:
399 self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
400 self.assertNotEqual(call, mock.call(StrContains(' 0 tests run')))
402 def test_run_raw_output_kunit(self):
403 self.linux_source_mock.run_kernel = mock.Mock(return_value=[])
404 kunit.main(['run', '--raw_output=kunit'], self.linux_source_mock)
405 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
406 self.assertEqual(self.linux_source_mock.run_kernel.call_count, 1)
407 for call in self.print_mock.call_args_list:
408 self.assertNotEqual(call, mock.call(StrContains('Testing complete.')))
409 self.assertNotEqual(call, mock.call(StrContains(' 0 tests run')))
411 def test_exec_timeout(self):
413 kunit.main(['exec', '--timeout', str(timeout)], self.linux_source_mock)
414 self.linux_source_mock.run_kernel.assert_called_once_with(
415 args=None, build_dir='.kunit', filter_glob='', timeout=timeout)
416 self.print_mock.assert_any_call(StrContains('Testing complete.'))
418 def test_run_timeout(self):
420 kunit.main(['run', '--timeout', str(timeout)], self.linux_source_mock)
421 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
422 self.linux_source_mock.run_kernel.assert_called_once_with(
423 args=None, build_dir='.kunit', filter_glob='', timeout=timeout)
424 self.print_mock.assert_any_call(StrContains('Testing complete.'))
426 def test_run_builddir(self):
428 kunit.main(['run', '--build_dir=.kunit'], self.linux_source_mock)
429 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
430 self.linux_source_mock.run_kernel.assert_called_once_with(
431 args=None, build_dir=build_dir, filter_glob='', timeout=300)
432 self.print_mock.assert_any_call(StrContains('Testing complete.'))
434 def test_config_builddir(self):
436 kunit.main(['config', '--build_dir', build_dir], self.linux_source_mock)
437 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
439 def test_build_builddir(self):
441 kunit.main(['build', '--build_dir', build_dir], self.linux_source_mock)
442 self.linux_source_mock.build_kernel.assert_called_once_with(False, 8, build_dir, None)
444 def test_exec_builddir(self):
446 kunit.main(['exec', '--build_dir', build_dir], self.linux_source_mock)
447 self.linux_source_mock.run_kernel.assert_called_once_with(
448 args=None, build_dir=build_dir, filter_glob='', timeout=300)
449 self.print_mock.assert_any_call(StrContains('Testing complete.'))
451 @mock.patch.object(kunit_kernel, 'LinuxSourceTree')
452 def test_run_kunitconfig(self, mock_linux_init):
453 mock_linux_init.return_value = self.linux_source_mock
454 kunit.main(['run', '--kunitconfig=mykunitconfig'])
455 # Just verify that we parsed and initialized it correctly here.
456 mock_linux_init.assert_called_once_with('.kunit',
457 kunitconfig_path='mykunitconfig',
460 qemu_config_path=None)
462 @mock.patch.object(kunit_kernel, 'LinuxSourceTree')
463 def test_config_kunitconfig(self, mock_linux_init):
464 mock_linux_init.return_value = self.linux_source_mock
465 kunit.main(['config', '--kunitconfig=mykunitconfig'])
466 # Just verify that we parsed and initialized it correctly here.
467 mock_linux_init.assert_called_once_with('.kunit',
468 kunitconfig_path='mykunitconfig',
471 qemu_config_path=None)
473 def test_run_kernel_args(self):
474 kunit.main(['run', '--kernel_args=a=1', '--kernel_args=b=2'], self.linux_source_mock)
475 self.assertEqual(self.linux_source_mock.build_reconfig.call_count, 1)
476 self.linux_source_mock.run_kernel.assert_called_once_with(
477 args=['a=1','b=2'], build_dir='.kunit', filter_glob='', timeout=300)
478 self.print_mock.assert_any_call(StrContains('Testing complete.'))
481 if __name__ == '__main__':