2 # SPDX-License-Identifier: GPL-2.0
4 # A thin wrapper on top of the KUnit Kernel
6 # Copyright (C) 2019, Google LLC.
7 # Author: Felix Guo <felixguoxiuping@gmail.com>
8 # Author: Brendan Higgins <brendanhiggins@google.com>
17 assert sys.version_info >= (3, 7), "Python version is too old"
19 from dataclasses import dataclass
20 from enum import Enum, auto
21 from typing import Iterable, List, Optional, Sequence, Tuple
26 from kunit_printer import stdout
28 class KunitStatus(Enum):
30 CONFIG_FAILURE = auto()
31 BUILD_FAILURE = auto()
40 class KunitConfigRequest:
42 make_options: Optional[List[str]]
45 class KunitBuildRequest(KunitConfigRequest):
49 class KunitParseRequest:
50 raw_output: Optional[str]
54 class KunitExecRequest(KunitParseRequest):
58 kernel_args: Optional[List[str]]
59 run_isolated: Optional[str]
62 class KunitRequest(KunitExecRequest, KunitBuildRequest):
66 def get_kernel_root_path() -> str:
67 path = sys.argv[0] if not __file__ else __file__
68 parts = os.path.realpath(path).split('tools/testing/kunit')
73 def config_tests(linux: kunit_kernel.LinuxSourceTree,
74 request: KunitConfigRequest) -> KunitResult:
75 stdout.print_with_timestamp('Configuring KUnit Kernel ...')
77 config_start = time.time()
78 success = linux.build_reconfig(request.build_dir, request.make_options)
79 config_end = time.time()
81 return KunitResult(KunitStatus.CONFIG_FAILURE,
82 config_end - config_start)
83 return KunitResult(KunitStatus.SUCCESS,
84 config_end - config_start)
86 def build_tests(linux: kunit_kernel.LinuxSourceTree,
87 request: KunitBuildRequest) -> KunitResult:
88 stdout.print_with_timestamp('Building KUnit Kernel ...')
90 build_start = time.time()
91 success = linux.build_kernel(request.jobs,
94 build_end = time.time()
96 return KunitResult(KunitStatus.BUILD_FAILURE,
97 build_end - build_start)
99 return KunitResult(KunitStatus.BUILD_FAILURE,
100 build_end - build_start)
101 return KunitResult(KunitStatus.SUCCESS,
102 build_end - build_start)
104 def config_and_build_tests(linux: kunit_kernel.LinuxSourceTree,
105 request: KunitBuildRequest) -> KunitResult:
106 config_result = config_tests(linux, request)
107 if config_result.status != KunitStatus.SUCCESS:
110 return build_tests(linux, request)
112 def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]:
113 args = ['kunit.action=list']
114 if request.kernel_args:
115 args.extend(request.kernel_args)
117 output = linux.run_kernel(args=args,
118 timeout=request.timeout,
119 filter_glob=request.filter_glob,
120 build_dir=request.build_dir)
121 lines = kunit_parser.extract_tap_lines(output)
122 # Hack! Drop the dummy TAP version header that the executor prints out.
125 # Filter out any extraneous non-test output that might have gotten mixed in.
126 return [l for l in lines if re.match(r'^[^\s.]+\.[^\s.]+$', l)]
128 def _suites_from_test_list(tests: List[str]) -> List[str]:
129 """Extracts all the suites from an ordered list of tests."""
130 suites = [] # type: List[str]
132 parts = t.split('.', maxsplit=2)
134 raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"')
136 if not suites or suites[-1] != suite:
142 def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult:
143 filter_globs = [request.filter_glob]
144 if request.run_isolated:
145 tests = _list_tests(linux, request)
146 if request.run_isolated == 'test':
148 if request.run_isolated == 'suite':
149 filter_globs = _suites_from_test_list(tests)
150 # Apply the test-part of the user's glob, if present.
151 if '.' in request.filter_glob:
152 test_glob = request.filter_glob.split('.', maxsplit=2)[1]
153 filter_globs = [g + '.'+ test_glob for g in filter_globs]
155 metadata = kunit_json.Metadata(arch=linux.arch(), build_dir=request.build_dir, def_config='kunit_defconfig')
157 test_counts = kunit_parser.TestCounts()
159 for i, filter_glob in enumerate(filter_globs):
160 stdout.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs)))
162 test_start = time.time()
163 run_result = linux.run_kernel(
164 args=request.kernel_args,
165 timeout=request.timeout,
166 filter_glob=filter_glob,
167 build_dir=request.build_dir)
169 _, test_result = parse_tests(request, metadata, run_result)
170 # run_kernel() doesn't block on the kernel exiting.
171 # That only happens after we get the last line of output from `run_result`.
172 # So exec_time here actually contains parsing + execution time, which is fine.
173 test_end = time.time()
174 exec_time += test_end - test_start
176 test_counts.add_subtest_counts(test_result.counts)
178 if len(filter_globs) == 1 and test_counts.crashed > 0:
179 bd = request.build_dir
180 print('The kernel seems to have crashed; you can decode the stack traces with:')
181 print('$ scripts/decode_stacktrace.sh {}/vmlinux {} < {} | tee {}/decoded.log | {} parse'.format(
182 bd, bd, kunit_kernel.get_outfile_path(bd), bd, sys.argv[0]))
184 kunit_status = _map_to_overall_status(test_counts.get_status())
185 return KunitResult(status=kunit_status, elapsed_time=exec_time)
187 def _map_to_overall_status(test_status: kunit_parser.TestStatus) -> KunitStatus:
188 if test_status in (kunit_parser.TestStatus.SUCCESS, kunit_parser.TestStatus.SKIPPED):
189 return KunitStatus.SUCCESS
190 return KunitStatus.TEST_FAILURE
192 def parse_tests(request: KunitParseRequest, metadata: kunit_json.Metadata, input_data: Iterable[str]) -> Tuple[KunitResult, kunit_parser.Test]:
193 parse_start = time.time()
195 test_result = kunit_parser.Test()
197 if request.raw_output:
198 # Treat unparsed results as one passing test.
199 test_result.status = kunit_parser.TestStatus.SUCCESS
200 test_result.counts.passed = 1
202 output: Iterable[str] = input_data
203 if request.raw_output == 'all':
205 elif request.raw_output == 'kunit':
206 output = kunit_parser.extract_tap_lines(output, lstrip=False)
211 test_result = kunit_parser.parse_run_tests(input_data)
212 parse_end = time.time()
215 json_str = kunit_json.get_json_result(
218 if request.json == 'stdout':
221 with open(request.json, 'w') as f:
223 stdout.print_with_timestamp("Test results stored in %s" %
224 os.path.abspath(request.json))
226 if test_result.status != kunit_parser.TestStatus.SUCCESS:
227 return KunitResult(KunitStatus.TEST_FAILURE, parse_end - parse_start), test_result
229 return KunitResult(KunitStatus.SUCCESS, parse_end - parse_start), test_result
231 def run_tests(linux: kunit_kernel.LinuxSourceTree,
232 request: KunitRequest) -> KunitResult:
233 run_start = time.time()
235 config_result = config_tests(linux, request)
236 if config_result.status != KunitStatus.SUCCESS:
239 build_result = build_tests(linux, request)
240 if build_result.status != KunitStatus.SUCCESS:
243 exec_result = exec_tests(linux, request)
245 run_end = time.time()
247 stdout.print_with_timestamp((
248 'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
249 'building, %.3fs running\n') % (
251 config_result.elapsed_time,
252 build_result.elapsed_time,
253 exec_result.elapsed_time))
257 # $ kunit.py run --json
258 # works as one would expect and prints the parsed test results as JSON.
259 # $ kunit.py run --json suite_name
260 # would *not* pass suite_name as the filter_glob and print as json.
261 # argparse will consider it to be another way of writing
262 # $ kunit.py run --json=suite_name
263 # i.e. it would run all tests, and dump the json to a `suite_name` file.
264 # So we hackily automatically rewrite --json => --json=stdout
265 pseudo_bool_flag_defaults = {
267 '--raw_output': 'kunit',
269 def massage_argv(argv: Sequence[str]) -> Sequence[str]:
270 def massage_arg(arg: str) -> str:
271 if arg not in pseudo_bool_flag_defaults:
273 return f'{arg}={pseudo_bool_flag_defaults[arg]}'
274 return list(map(massage_arg, argv))
276 def get_default_jobs() -> int:
277 return len(os.sched_getaffinity(0))
279 def add_common_opts(parser) -> None:
280 parser.add_argument('--build_dir',
281 help='As in the make command, it specifies the build '
283 type=str, default='.kunit', metavar='DIR')
284 parser.add_argument('--make_options',
285 help='X=Y make option, can be repeated.',
286 action='append', metavar='X=Y')
287 parser.add_argument('--alltests',
288 help='Run all KUnit tests via tools/testing/kunit/configs/all_tests.config',
290 parser.add_argument('--kunitconfig',
291 help='Path to Kconfig fragment that enables KUnit tests.'
292 ' If given a directory, (e.g. lib/kunit), "/.kunitconfig" '
293 'will get automatically appended. If repeated, the files '
294 'blindly concatenated, which might not work in all cases.',
295 action='append', metavar='PATHS')
296 parser.add_argument('--kconfig_add',
297 help='Additional Kconfig options to append to the '
298 '.kunitconfig, e.g. CONFIG_KASAN=y. Can be repeated.',
299 action='append', metavar='CONFIG_X=Y')
301 parser.add_argument('--arch',
302 help=('Specifies the architecture to run tests under. '
303 'The architecture specified here must match the '
304 'string passed to the ARCH make param, '
305 'e.g. i386, x86_64, arm, um, etc. Non-UML '
306 'architectures run on QEMU.'),
307 type=str, default='um', metavar='ARCH')
309 parser.add_argument('--cross_compile',
310 help=('Sets make\'s CROSS_COMPILE variable; it should '
311 'be set to a toolchain path prefix (the prefix '
312 'of gcc and other tools in your toolchain, for '
313 'example `sparc64-linux-gnu-` if you have the '
314 'sparc toolchain installed on your system, or '
315 '`$HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux-` '
316 'if you have downloaded the microblaze toolchain '
317 'from the 0-day website to a directory in your '
318 'home directory called `toolchains`).'),
321 parser.add_argument('--qemu_config',
322 help=('Takes a path to a path to a file containing '
323 'a QemuArchParams object.'),
324 type=str, metavar='FILE')
326 parser.add_argument('--qemu_args',
327 help='Additional QEMU arguments, e.g. "-smp 8"',
328 action='append', metavar='')
330 def add_build_opts(parser) -> None:
331 parser.add_argument('--jobs',
332 help='As in the make command, "Specifies the number of '
333 'jobs (commands) to run simultaneously."',
334 type=int, default=get_default_jobs(), metavar='N')
336 def add_exec_opts(parser) -> None:
337 parser.add_argument('--timeout',
338 help='maximum number of seconds to allow for all tests '
339 'to run. This does not include time taken to build the '
344 parser.add_argument('filter_glob',
345 help='Filter which KUnit test suites/tests run at '
346 'boot-time, e.g. list* or list*.*del_test',
350 metavar='filter_glob')
351 parser.add_argument('--kernel_args',
352 help='Kernel command-line parameters. Maybe be repeated',
353 action='append', metavar='')
354 parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
355 'individual suite/test. This is can be useful for debugging '
356 'a non-hermetic test, one that might pass/fail based on '
357 'what ran before it.',
359 choices=['suite', 'test'])
361 def add_parse_opts(parser) -> None:
362 parser.add_argument('--raw_output', help='If set don\'t format output from kernel. '
363 'If set to --raw_output=kunit, filters to just KUnit output.',
364 type=str, nargs='?', const='all', default=None, choices=['all', 'kunit'])
365 parser.add_argument('--json',
367 help='Stores test results in a JSON, and either '
368 'prints to stdout or saves to file if a '
369 'filename is specified',
370 type=str, const='stdout', default=None, metavar='FILE')
373 def tree_from_args(cli_args: argparse.Namespace) -> kunit_kernel.LinuxSourceTree:
374 """Returns a LinuxSourceTree based on the user's arguments."""
375 # Allow users to specify multiple arguments in one string, e.g. '-smp 8'
376 qemu_args: List[str] = []
377 if cli_args.qemu_args:
378 for arg in cli_args.qemu_args:
379 qemu_args.extend(shlex.split(arg))
381 kunitconfigs = cli_args.kunitconfig if cli_args.kunitconfig else []
382 if cli_args.alltests:
383 # Prepend so user-specified options take prio if we ever allow
384 # --kunitconfig options to have differing options.
385 kunitconfigs = [kunit_kernel.ALL_TESTS_CONFIG_PATH] + kunitconfigs
387 return kunit_kernel.LinuxSourceTree(cli_args.build_dir,
388 kunitconfig_paths=kunitconfigs,
389 kconfig_add=cli_args.kconfig_add,
391 cross_compile=cli_args.cross_compile,
392 qemu_config_path=cli_args.qemu_config,
393 extra_qemu_args=qemu_args)
397 parser = argparse.ArgumentParser(
398 description='Helps writing and running KUnit tests.')
399 subparser = parser.add_subparsers(dest='subcommand')
401 # The 'run' command will config, build, exec, and parse in one go.
402 run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
403 add_common_opts(run_parser)
404 add_build_opts(run_parser)
405 add_exec_opts(run_parser)
406 add_parse_opts(run_parser)
408 config_parser = subparser.add_parser('config',
409 help='Ensures that .config contains all of '
410 'the options in .kunitconfig')
411 add_common_opts(config_parser)
413 build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
414 add_common_opts(build_parser)
415 add_build_opts(build_parser)
417 exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
418 add_common_opts(exec_parser)
419 add_exec_opts(exec_parser)
420 add_parse_opts(exec_parser)
422 # The 'parse' option is special, as it doesn't need the kernel source
423 # (therefore there is no need for a build_dir, hence no add_common_opts)
424 # and the '--file' argument is not relevant to 'run', so isn't in
426 parse_parser = subparser.add_parser('parse',
427 help='Parses KUnit results from a file, '
428 'and parses formatted results.')
429 add_parse_opts(parse_parser)
430 parse_parser.add_argument('file',
431 help='Specifies the file to read results from.',
432 type=str, nargs='?', metavar='input_file')
434 cli_args = parser.parse_args(massage_argv(argv))
436 if get_kernel_root_path():
437 os.chdir(get_kernel_root_path())
439 if cli_args.subcommand == 'run':
440 if not os.path.exists(cli_args.build_dir):
441 os.mkdir(cli_args.build_dir)
443 linux = tree_from_args(cli_args)
444 request = KunitRequest(build_dir=cli_args.build_dir,
445 make_options=cli_args.make_options,
447 raw_output=cli_args.raw_output,
449 timeout=cli_args.timeout,
450 filter_glob=cli_args.filter_glob,
451 kernel_args=cli_args.kernel_args,
452 run_isolated=cli_args.run_isolated)
453 result = run_tests(linux, request)
454 if result.status != KunitStatus.SUCCESS:
456 elif cli_args.subcommand == 'config':
457 if cli_args.build_dir and (
458 not os.path.exists(cli_args.build_dir)):
459 os.mkdir(cli_args.build_dir)
461 linux = tree_from_args(cli_args)
462 request = KunitConfigRequest(build_dir=cli_args.build_dir,
463 make_options=cli_args.make_options)
464 result = config_tests(linux, request)
465 stdout.print_with_timestamp((
466 'Elapsed time: %.3fs\n') % (
467 result.elapsed_time))
468 if result.status != KunitStatus.SUCCESS:
470 elif cli_args.subcommand == 'build':
471 linux = tree_from_args(cli_args)
472 request = KunitBuildRequest(build_dir=cli_args.build_dir,
473 make_options=cli_args.make_options,
475 result = config_and_build_tests(linux, request)
476 stdout.print_with_timestamp((
477 'Elapsed time: %.3fs\n') % (
478 result.elapsed_time))
479 if result.status != KunitStatus.SUCCESS:
481 elif cli_args.subcommand == 'exec':
482 linux = tree_from_args(cli_args)
483 exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
484 build_dir=cli_args.build_dir,
486 timeout=cli_args.timeout,
487 filter_glob=cli_args.filter_glob,
488 kernel_args=cli_args.kernel_args,
489 run_isolated=cli_args.run_isolated)
490 result = exec_tests(linux, exec_request)
491 stdout.print_with_timestamp((
492 'Elapsed time: %.3fs\n') % (result.elapsed_time))
493 if result.status != KunitStatus.SUCCESS:
495 elif cli_args.subcommand == 'parse':
496 if cli_args.file is None:
497 sys.stdin.reconfigure(errors='backslashreplace') # pytype: disable=attribute-error
498 kunit_output = sys.stdin
500 with open(cli_args.file, 'r', errors='backslashreplace') as f:
501 kunit_output = f.read().splitlines()
502 # We know nothing about how the result was created!
503 metadata = kunit_json.Metadata()
504 request = KunitParseRequest(raw_output=cli_args.raw_output,
506 result, _ = parse_tests(request, metadata, kunit_output)
507 if result.status != KunitStatus.SUCCESS:
512 if __name__ == '__main__':