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