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