Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

kunit: tool: support running each suite/test separately

The new --run_isolated flag makes the tool boot the kernel once per
suite or test, preventing leftover state from one suite to impact the
other. This can be useful as a starting point to debugging test
hermeticity issues.

Note: it takes a lot longer, so people should not use it normally.

Consider the following very simplified example:

bool disable_something_for_test = false;
void function_being_tested() {
...
if (disable_something_for_test) return;
...
}

static void test_before(struct kunit *test)
{
disable_something_for_test = true;
function_being_tested();
/* oops, we forgot to reset it back to false */
}

static void test_after(struct kunit *test)
{
/* oops, now "fixing" test_before can cause test_after to fail! */
function_being_tested();
}

Presented like this, the issues are obvious, but it gets a lot more
complicated to track down as the amount of test setup and helper
functions increases.

Another use case is memory corruption. It might not be surfaced as a
failure/crash in the test case or suite that caused it. I've noticed in
kunit's own unit tests, the 3rd suite after might be the one to finally
crash after an out-of-bounds write, for example.

Example usage:

Per suite:
$ ./tools/testing/kunit/kunit.py run --kunitconfig=lib/kunit --run_isolated=suite
...
Starting KUnit Kernel (1/7)...
============================================================
======== [PASSED] kunit_executor_test ========
....
Testing complete. 5 tests run. 0 failed. 0 crashed. 0 skipped.
Starting KUnit Kernel (2/7)...
============================================================
======== [PASSED] kunit-try-catch-test ========
...

Per test:
$ ./tools/testing/kunit/kunit.py run --kunitconfig=lib/kunit --run_isolated=test
Starting KUnit Kernel (1/23)...
============================================================
======== [PASSED] kunit_executor_test ========
[PASSED] parse_filter_test
============================================================
Testing complete. 1 tests run. 0 failed. 0 crashed. 0 skipped.
Starting KUnit Kernel (2/23)...
============================================================
======== [PASSED] kunit_executor_test ========
[PASSED] filter_subsuite_test
...

It works with filters as well:
$ ./tools/testing/kunit/kunit.py run --kunitconfig=lib/kunit --run_isolated=suite example
...
Starting KUnit Kernel (1/1)...
============================================================
======== [PASSED] example ========
...

It also handles test filters, '*.*skip*' runs these 3 tests:
kunit_status.kunit_status_mark_skipped_test
example.example_skip_test
example.example_mark_skipped_test

Fixed up merge conflict between:
d8c23ead708b ("kunit: tool: better handling of quasi-bool args (--json, --raw_output)") and
6710951ee039 ("kunit: tool: support running each suite/test separately")
Reported-by: Stephen Rothwell <sfr@canb.auug.org.au>
Shuah Khan <skhan@linuxfoundation.org>

Signed-off-by: Daniel Latypov <dlatypov@google.com>
Reviewed-by: David Gow <davidgow@google.com>
Reviewed-by: Brendan Higgins <brendanhiggins@google.com>
Signed-off-by: Shuah Khan <skhan@linuxfoundation.org>

authored by

Daniel Latypov and committed by
Shuah Khan
ff9e09a3 5f6aa6d8

+116 -20
+76 -20
tools/testing/kunit/kunit.py
··· 8 8 # Author: Brendan Higgins <brendanhiggins@google.com> 9 9 10 10 import argparse 11 - import sys 12 11 import os 12 + import re 13 + import sys 13 14 import time 14 15 15 16 assert sys.version_info >= (3, 7), "Python version is too old" 16 17 17 18 from collections import namedtuple 18 19 from enum import Enum, auto 19 - from typing import Iterable, Sequence 20 + from typing import Iterable, Sequence, List 20 21 21 22 import kunit_json 22 23 import kunit_kernel ··· 31 30 ['jobs', 'build_dir', 'alltests', 32 31 'make_options']) 33 32 KunitExecRequest = namedtuple('KunitExecRequest', 34 - ['timeout', 'build_dir', 'alltests', 35 - 'filter_glob', 'kernel_args']) 33 + ['timeout', 'build_dir', 'alltests', 34 + 'filter_glob', 'kernel_args', 'run_isolated']) 36 35 KunitParseRequest = namedtuple('KunitParseRequest', 37 36 ['raw_output', 'build_dir', 'json']) 38 37 KunitRequest = namedtuple('KunitRequest', ['raw_output','timeout', 'jobs', 39 38 'build_dir', 'alltests', 'filter_glob', 40 - 'kernel_args', 'json', 'make_options']) 39 + 'kernel_args', 'run_isolated', 'json', 'make_options']) 41 40 42 41 KernelDirectoryPath = sys.argv[0].split('tools/testing/kunit/')[0] 43 42 ··· 91 90 'built kernel successfully', 92 91 build_end - build_start) 93 92 93 + def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]: 94 + args = ['kunit.action=list'] 95 + if request.kernel_args: 96 + args.extend(request.kernel_args) 97 + 98 + output = linux.run_kernel(args=args, 99 + timeout=None if request.alltests else request.timeout, 100 + filter_glob=request.filter_glob, 101 + build_dir=request.build_dir) 102 + lines = kunit_parser.extract_tap_lines(output) 103 + # Hack! Drop the dummy TAP version header that the executor prints out. 104 + lines.pop() 105 + 106 + # Filter out any extraneous non-test output that might have gotten mixed in. 107 + return [l for l in lines if re.match('^[^\s.]+\.[^\s.]+$', l)] 108 + 109 + def _suites_from_test_list(tests: List[str]) -> List[str]: 110 + """Extracts all the suites from an ordered list of tests.""" 111 + suites = [] # type: List[str] 112 + for t in tests: 113 + parts = t.split('.', maxsplit=2) 114 + if len(parts) != 2: 115 + raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"') 116 + suite, case = parts 117 + if not suites or suites[-1] != suite: 118 + suites.append(suite) 119 + return suites 120 + 121 + 122 + 94 123 def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest, 95 124 parse_request: KunitParseRequest) -> KunitResult: 96 - kunit_parser.print_with_timestamp('Starting KUnit Kernel ...') 97 - test_start = time.time() 98 - run_result = linux.run_kernel( 99 - args=request.kernel_args, 100 - timeout=None if request.alltests else request.timeout, 101 - filter_glob=request.filter_glob, 102 - build_dir=request.build_dir) 125 + filter_globs = [request.filter_glob] 126 + if request.run_isolated: 127 + tests = _list_tests(linux, request) 128 + if request.run_isolated == 'test': 129 + filter_globs = tests 130 + if request.run_isolated == 'suite': 131 + filter_globs = _suites_from_test_list(tests) 132 + # Apply the test-part of the user's glob, if present. 133 + if '.' in request.filter_glob: 134 + test_glob = request.filter_glob.split('.', maxsplit=2)[1] 135 + filter_globs = [g + '.'+ test_glob for g in filter_globs] 103 136 104 - result = parse_tests(parse_request, run_result) 137 + overall_status = kunit_parser.TestStatus.SUCCESS 138 + exec_time = 0.0 139 + for i, filter_glob in enumerate(filter_globs): 140 + kunit_parser.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs))) 105 141 106 - # run_kernel() doesn't block on the kernel exiting. 107 - # That only happens after we get the last line of output from `run_result`. 108 - # So exec_time here actually contains parsing + execution time, which is fine. 109 - test_end = time.time() 110 - exec_time = test_end - test_start 142 + test_start = time.time() 143 + run_result = linux.run_kernel( 144 + args=request.kernel_args, 145 + timeout=None if request.alltests else request.timeout, 146 + filter_glob=filter_glob, 147 + build_dir=request.build_dir) 148 + 149 + result = parse_tests(parse_request, run_result) 150 + # run_kernel() doesn't block on the kernel exiting. 151 + # That only happens after we get the last line of output from `run_result`. 152 + # So exec_time here actually contains parsing + execution time, which is fine. 153 + test_end = time.time() 154 + exec_time += test_end - test_start 155 + 156 + overall_status = kunit_parser.max_status(overall_status, result.status) 111 157 112 158 return KunitResult(status=result.status, result=result.result, elapsed_time=exec_time) 113 159 ··· 215 167 216 168 exec_request = KunitExecRequest(request.timeout, request.build_dir, 217 169 request.alltests, request.filter_glob, 218 - request.kernel_args) 170 + request.kernel_args, request.run_isolated) 219 171 parse_request = KunitParseRequest(request.raw_output, 220 172 request.build_dir, 221 173 request.json) ··· 319 271 parser.add_argument('--kernel_args', 320 272 help='Kernel command-line parameters. Maybe be repeated', 321 273 action='append') 274 + parser.add_argument('--run_isolated', help='If set, boot the kernel for each ' 275 + 'individual suite/test. This is can be useful for debugging ' 276 + 'a non-hermetic test, one that might pass/fail based on ' 277 + 'what ran before it.', 278 + type=str, 279 + choices=['suite', 'test']), 322 280 323 281 def add_parse_opts(parser) -> None: 324 282 parser.add_argument('--raw_output', help='If set don\'t format output from kernel. ' ··· 398 344 cli_args.alltests, 399 345 cli_args.filter_glob, 400 346 cli_args.kernel_args, 347 + cli_args.run_isolated, 401 348 cli_args.json, 402 349 cli_args.make_options) 403 350 result = run_tests(linux, request) ··· 454 399 cli_args.build_dir, 455 400 cli_args.alltests, 456 401 cli_args.filter_glob, 457 - cli_args.kernel_args) 402 + cli_args.kernel_args, 403 + cli_args.run_isolated) 458 404 parse_request = KunitParseRequest(cli_args.raw_output, 459 405 cli_args.build_dir, 460 406 cli_args.json)
+40
tools/testing/kunit/kunit_tool_test.py
··· 487 487 args=['a=1','b=2'], build_dir='.kunit', filter_glob='', timeout=300) 488 488 self.print_mock.assert_any_call(StrContains('Testing complete.')) 489 489 490 + def test_list_tests(self): 491 + want = ['suite.test1', 'suite.test2', 'suite2.test1'] 492 + self.linux_source_mock.run_kernel.return_value = ['TAP version 14', 'init: random output'] + want 493 + 494 + got = kunit._list_tests(self.linux_source_mock, 495 + kunit.KunitExecRequest(300, '.kunit', False, 'suite*', None, 'suite')) 496 + 497 + self.assertEqual(got, want) 498 + # Should respect the user's filter glob when listing tests. 499 + self.linux_source_mock.run_kernel.assert_called_once_with( 500 + args=['kunit.action=list'], build_dir='.kunit', filter_glob='suite*', timeout=300) 501 + 502 + 503 + @mock.patch.object(kunit, '_list_tests') 504 + def test_run_isolated_by_suite(self, mock_tests): 505 + mock_tests.return_value = ['suite.test1', 'suite.test2', 'suite2.test1'] 506 + kunit.main(['exec', '--run_isolated=suite', 'suite*.test*'], self.linux_source_mock) 507 + 508 + # Should respect the user's filter glob when listing tests. 509 + mock_tests.assert_called_once_with(mock.ANY, 510 + kunit.KunitExecRequest(300, '.kunit', False, 'suite*.test*', None, 'suite')) 511 + self.linux_source_mock.run_kernel.assert_has_calls([ 512 + mock.call(args=None, build_dir='.kunit', filter_glob='suite.test*', timeout=300), 513 + mock.call(args=None, build_dir='.kunit', filter_glob='suite2.test*', timeout=300), 514 + ]) 515 + 516 + @mock.patch.object(kunit, '_list_tests') 517 + def test_run_isolated_by_test(self, mock_tests): 518 + mock_tests.return_value = ['suite.test1', 'suite.test2', 'suite2.test1'] 519 + kunit.main(['exec', '--run_isolated=test', 'suite*'], self.linux_source_mock) 520 + 521 + # Should respect the user's filter glob when listing tests. 522 + mock_tests.assert_called_once_with(mock.ANY, 523 + kunit.KunitExecRequest(300, '.kunit', False, 'suite*', None, 'test')) 524 + self.linux_source_mock.run_kernel.assert_has_calls([ 525 + mock.call(args=None, build_dir='.kunit', filter_glob='suite.test1', timeout=300), 526 + mock.call(args=None, build_dir='.kunit', filter_glob='suite.test2', timeout=300), 527 + mock.call(args=None, build_dir='.kunit', filter_glob='suite2.test1', timeout=300), 528 + ]) 529 + 490 530 491 531 if __name__ == '__main__': 492 532 unittest.main()