xref: /linux-6.15/tools/testing/kunit/kunit.py (revision 89aa72cd)
1#!/usr/bin/env python3
2# SPDX-License-Identifier: GPL-2.0
3#
4# A thin wrapper on top of the KUnit Kernel
5#
6# Copyright (C) 2019, Google LLC.
7# Author: Felix Guo <[email protected]>
8# Author: Brendan Higgins <[email protected]>
9
10import argparse
11import os
12import re
13import sys
14import time
15
16assert sys.version_info >= (3, 7), "Python version is too old"
17
18from dataclasses import dataclass
19from enum import Enum, auto
20from typing import Iterable, List, Optional, Sequence, Tuple
21
22import kunit_json
23import kunit_kernel
24import kunit_parser
25
26class KunitStatus(Enum):
27	SUCCESS = auto()
28	CONFIG_FAILURE = auto()
29	BUILD_FAILURE = auto()
30	TEST_FAILURE = auto()
31
32@dataclass
33class KunitResult:
34	status: KunitStatus
35	elapsed_time: float
36
37@dataclass
38class KunitConfigRequest:
39	build_dir: str
40	make_options: Optional[List[str]]
41
42@dataclass
43class KunitBuildRequest(KunitConfigRequest):
44	jobs: int
45	alltests: bool
46
47@dataclass
48class KunitParseRequest:
49	raw_output: Optional[str]
50	build_dir: str
51	json: Optional[str]
52
53@dataclass
54class KunitExecRequest(KunitParseRequest):
55	timeout: int
56	alltests: bool
57	filter_glob: str
58	kernel_args: Optional[List[str]]
59	run_isolated: Optional[str]
60
61@dataclass
62class KunitRequest(KunitExecRequest, KunitBuildRequest):
63	pass
64
65
66def 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')
69	if len(parts) != 2:
70		sys.exit(1)
71	return parts[0]
72
73def config_tests(linux: kunit_kernel.LinuxSourceTree,
74		 request: KunitConfigRequest) -> KunitResult:
75	kunit_parser.print_with_timestamp('Configuring KUnit Kernel ...')
76
77	config_start = time.time()
78	success = linux.build_reconfig(request.build_dir, request.make_options)
79	config_end = time.time()
80	if not success:
81		return KunitResult(KunitStatus.CONFIG_FAILURE,
82				   config_end - config_start)
83	return KunitResult(KunitStatus.SUCCESS,
84			   config_end - config_start)
85
86def build_tests(linux: kunit_kernel.LinuxSourceTree,
87		request: KunitBuildRequest) -> KunitResult:
88	kunit_parser.print_with_timestamp('Building KUnit Kernel ...')
89
90	build_start = time.time()
91	success = linux.build_kernel(request.alltests,
92				     request.jobs,
93				     request.build_dir,
94				     request.make_options)
95	build_end = time.time()
96	if not success:
97		return KunitResult(KunitStatus.BUILD_FAILURE,
98				   build_end - build_start)
99	if not success:
100		return KunitResult(KunitStatus.BUILD_FAILURE,
101				   build_end - build_start)
102	return KunitResult(KunitStatus.SUCCESS,
103			   build_end - build_start)
104
105def config_and_build_tests(linux: kunit_kernel.LinuxSourceTree,
106			   request: KunitBuildRequest) -> KunitResult:
107	config_result = config_tests(linux, request)
108	if config_result.status != KunitStatus.SUCCESS:
109		return config_result
110
111	return build_tests(linux, request)
112
113def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]:
114	args = ['kunit.action=list']
115	if request.kernel_args:
116		args.extend(request.kernel_args)
117
118	output = linux.run_kernel(args=args,
119			   timeout=None if request.alltests else request.timeout,
120			   filter_glob=request.filter_glob,
121			   build_dir=request.build_dir)
122	lines = kunit_parser.extract_tap_lines(output)
123	# Hack! Drop the dummy TAP version header that the executor prints out.
124	lines.pop()
125
126	# Filter out any extraneous non-test output that might have gotten mixed in.
127	return [l for l in lines if re.match('^[^\s.]+\.[^\s.]+$', l)]
128
129def _suites_from_test_list(tests: List[str]) -> List[str]:
130	"""Extracts all the suites from an ordered list of tests."""
131	suites = []  # type: List[str]
132	for t in tests:
133		parts = t.split('.', maxsplit=2)
134		if len(parts) != 2:
135			raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"')
136		suite, case = parts
137		if not suites or suites[-1] != suite:
138			suites.append(suite)
139	return suites
140
141
142
143def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult:
144	filter_globs = [request.filter_glob]
145	if request.run_isolated:
146		tests = _list_tests(linux, request)
147		if request.run_isolated == 'test':
148			filter_globs = tests
149		if request.run_isolated == 'suite':
150			filter_globs = _suites_from_test_list(tests)
151			# Apply the test-part of the user's glob, if present.
152			if '.' in request.filter_glob:
153				test_glob = request.filter_glob.split('.', maxsplit=2)[1]
154				filter_globs = [g + '.'+ test_glob for g in filter_globs]
155
156	test_counts = kunit_parser.TestCounts()
157	exec_time = 0.0
158	for i, filter_glob in enumerate(filter_globs):
159		kunit_parser.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs)))
160
161		test_start = time.time()
162		run_result = linux.run_kernel(
163			args=request.kernel_args,
164			timeout=None if request.alltests else request.timeout,
165			filter_glob=filter_glob,
166			build_dir=request.build_dir)
167
168		_, test_result = parse_tests(request, run_result)
169		# run_kernel() doesn't block on the kernel exiting.
170		# That only happens after we get the last line of output from `run_result`.
171		# So exec_time here actually contains parsing + execution time, which is fine.
172		test_end = time.time()
173		exec_time += test_end - test_start
174
175		test_counts.add_subtest_counts(test_result.counts)
176
177	if len(filter_globs) == 1 and test_counts.crashed > 0:
178		bd = request.build_dir
179		print('The kernel seems to have crashed; you can decode the stack traces with:')
180		print('$ scripts/decode_stacktrace.sh {}/vmlinux {} < {} | tee {}/decoded.log | {} parse'.format(
181				bd, bd, kunit_kernel.get_outfile_path(bd), bd, sys.argv[0]))
182
183	kunit_status = _map_to_overall_status(test_counts.get_status())
184	return KunitResult(status=kunit_status, elapsed_time=exec_time)
185
186def _map_to_overall_status(test_status: kunit_parser.TestStatus) -> KunitStatus:
187	if test_status in (kunit_parser.TestStatus.SUCCESS, kunit_parser.TestStatus.SKIPPED):
188		return KunitStatus.SUCCESS
189	else:
190		return KunitStatus.TEST_FAILURE
191
192def parse_tests(request: KunitParseRequest, input_data: Iterable[str]) -> Tuple[KunitResult, kunit_parser.Test]:
193	parse_start = time.time()
194
195	test_result = kunit_parser.Test()
196
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
201
202		output: Iterable[str] = input_data
203		if request.raw_output == 'all':
204			pass
205		elif request.raw_output == 'kunit':
206			output = kunit_parser.extract_tap_lines(output)
207		else:
208			print(f'Unknown --raw_output option "{request.raw_output}"', file=sys.stderr)
209		for line in output:
210			print(line.rstrip())
211
212	else:
213		test_result = kunit_parser.parse_run_tests(input_data)
214	parse_end = time.time()
215
216	if request.json:
217		json_str = kunit_json.get_json_result(
218					test=test_result,
219					def_config='kunit_defconfig',
220					build_dir=request.build_dir)
221		if request.json == 'stdout':
222			print(json_str)
223		else:
224			with open(request.json, 'w') as f:
225				f.write(json_str)
226			kunit_parser.print_with_timestamp("Test results stored in %s" %
227				os.path.abspath(request.json))
228
229	if test_result.status != kunit_parser.TestStatus.SUCCESS:
230		return KunitResult(KunitStatus.TEST_FAILURE, parse_end - parse_start), test_result
231
232	return KunitResult(KunitStatus.SUCCESS, parse_end - parse_start), test_result
233
234def run_tests(linux: kunit_kernel.LinuxSourceTree,
235	      request: KunitRequest) -> KunitResult:
236	run_start = time.time()
237
238	config_result = config_tests(linux, request)
239	if config_result.status != KunitStatus.SUCCESS:
240		return config_result
241
242	build_result = build_tests(linux, request)
243	if build_result.status != KunitStatus.SUCCESS:
244		return build_result
245
246	exec_result = exec_tests(linux, request)
247
248	run_end = time.time()
249
250	kunit_parser.print_with_timestamp((
251		'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
252		'building, %.3fs running\n') % (
253				run_end - run_start,
254				config_result.elapsed_time,
255				build_result.elapsed_time,
256				exec_result.elapsed_time))
257	return exec_result
258
259# Problem:
260# $ kunit.py run --json
261# works as one would expect and prints the parsed test results as JSON.
262# $ kunit.py run --json suite_name
263# would *not* pass suite_name as the filter_glob and print as json.
264# argparse will consider it to be another way of writing
265# $ kunit.py run --json=suite_name
266# i.e. it would run all tests, and dump the json to a `suite_name` file.
267# So we hackily automatically rewrite --json => --json=stdout
268pseudo_bool_flag_defaults = {
269		'--json': 'stdout',
270		'--raw_output': 'kunit',
271}
272def massage_argv(argv: Sequence[str]) -> Sequence[str]:
273	def massage_arg(arg: str) -> str:
274		if arg not in pseudo_bool_flag_defaults:
275			return arg
276		return  f'{arg}={pseudo_bool_flag_defaults[arg]}'
277	return list(map(massage_arg, argv))
278
279def get_default_jobs() -> int:
280	return len(os.sched_getaffinity(0))
281
282def add_common_opts(parser) -> None:
283	parser.add_argument('--build_dir',
284			    help='As in the make command, it specifies the build '
285			    'directory.',
286			    type=str, default='.kunit', metavar='build_dir')
287	parser.add_argument('--make_options',
288			    help='X=Y make option, can be repeated.',
289			    action='append')
290	parser.add_argument('--alltests',
291			    help='Run all KUnit tests through allyesconfig',
292			    action='store_true')
293	parser.add_argument('--kunitconfig',
294			     help='Path to Kconfig fragment that enables KUnit tests.'
295			     ' If given a directory, (e.g. lib/kunit), "/.kunitconfig" '
296			     'will get  automatically appended.',
297			     metavar='kunitconfig')
298	parser.add_argument('--kconfig_add',
299			     help='Additional Kconfig options to append to the '
300			     '.kunitconfig, e.g. CONFIG_KASAN=y. Can be repeated.',
301			    action='append')
302
303	parser.add_argument('--arch',
304			    help=('Specifies the architecture to run tests under. '
305				  'The architecture specified here must match the '
306				  'string passed to the ARCH make param, '
307				  'e.g. i386, x86_64, arm, um, etc. Non-UML '
308				  'architectures run on QEMU.'),
309			    type=str, default='um', metavar='arch')
310
311	parser.add_argument('--cross_compile',
312			    help=('Sets make\'s CROSS_COMPILE variable; it should '
313				  'be set to a toolchain path prefix (the prefix '
314				  'of gcc and other tools in your toolchain, for '
315				  'example `sparc64-linux-gnu-` if you have the '
316				  'sparc toolchain installed on your system, or '
317				  '`$HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux-` '
318				  'if you have downloaded the microblaze toolchain '
319				  'from the 0-day website to a directory in your '
320				  'home directory called `toolchains`).'),
321			    metavar='cross_compile')
322
323	parser.add_argument('--qemu_config',
324			    help=('Takes a path to a path to a file containing '
325				  'a QemuArchParams object.'),
326			    type=str, metavar='qemu_config')
327
328def add_build_opts(parser) -> None:
329	parser.add_argument('--jobs',
330			    help='As in the make command, "Specifies  the number of '
331			    'jobs (commands) to run simultaneously."',
332			    type=int, default=get_default_jobs(), metavar='jobs')
333
334def add_exec_opts(parser) -> None:
335	parser.add_argument('--timeout',
336			    help='maximum number of seconds to allow for all tests '
337			    'to run. This does not include time taken to build the '
338			    'tests.',
339			    type=int,
340			    default=300,
341			    metavar='timeout')
342	parser.add_argument('filter_glob',
343			    help='Filter which KUnit test suites/tests run at '
344			    'boot-time, e.g. list* or list*.*del_test',
345			    type=str,
346			    nargs='?',
347			    default='',
348			    metavar='filter_glob')
349	parser.add_argument('--kernel_args',
350			    help='Kernel command-line parameters. Maybe be repeated',
351			     action='append')
352	parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
353			    'individual suite/test. This is can be useful for debugging '
354			    'a non-hermetic test, one that might pass/fail based on '
355			    'what ran before it.',
356			    type=str,
357			    choices=['suite', 'test']),
358
359def add_parse_opts(parser) -> None:
360	parser.add_argument('--raw_output', help='If set don\'t format output from kernel. '
361			    'If set to --raw_output=kunit, filters to just KUnit output.',
362			    type=str, nargs='?', const='all', default=None)
363	parser.add_argument('--json',
364			    nargs='?',
365			    help='Stores test results in a JSON, and either '
366			    'prints to stdout or saves to file if a '
367			    'filename is specified',
368			    type=str, const='stdout', default=None)
369
370def main(argv, linux=None):
371	parser = argparse.ArgumentParser(
372			description='Helps writing and running KUnit tests.')
373	subparser = parser.add_subparsers(dest='subcommand')
374
375	# The 'run' command will config, build, exec, and parse in one go.
376	run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
377	add_common_opts(run_parser)
378	add_build_opts(run_parser)
379	add_exec_opts(run_parser)
380	add_parse_opts(run_parser)
381
382	config_parser = subparser.add_parser('config',
383						help='Ensures that .config contains all of '
384						'the options in .kunitconfig')
385	add_common_opts(config_parser)
386
387	build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
388	add_common_opts(build_parser)
389	add_build_opts(build_parser)
390
391	exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
392	add_common_opts(exec_parser)
393	add_exec_opts(exec_parser)
394	add_parse_opts(exec_parser)
395
396	# The 'parse' option is special, as it doesn't need the kernel source
397	# (therefore there is no need for a build_dir, hence no add_common_opts)
398	# and the '--file' argument is not relevant to 'run', so isn't in
399	# add_parse_opts()
400	parse_parser = subparser.add_parser('parse',
401					    help='Parses KUnit results from a file, '
402					    'and parses formatted results.')
403	add_parse_opts(parse_parser)
404	parse_parser.add_argument('file',
405				  help='Specifies the file to read results from.',
406				  type=str, nargs='?', metavar='input_file')
407
408	cli_args = parser.parse_args(massage_argv(argv))
409
410	if get_kernel_root_path():
411		os.chdir(get_kernel_root_path())
412
413	if cli_args.subcommand == 'run':
414		if not os.path.exists(cli_args.build_dir):
415			os.mkdir(cli_args.build_dir)
416
417		if not linux:
418			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
419					kunitconfig_path=cli_args.kunitconfig,
420					kconfig_add=cli_args.kconfig_add,
421					arch=cli_args.arch,
422					cross_compile=cli_args.cross_compile,
423					qemu_config_path=cli_args.qemu_config)
424
425		request = KunitRequest(build_dir=cli_args.build_dir,
426				       make_options=cli_args.make_options,
427				       jobs=cli_args.jobs,
428				       alltests=cli_args.alltests,
429				       raw_output=cli_args.raw_output,
430				       json=cli_args.json,
431				       timeout=cli_args.timeout,
432				       filter_glob=cli_args.filter_glob,
433				       kernel_args=cli_args.kernel_args,
434				       run_isolated=cli_args.run_isolated)
435		result = run_tests(linux, request)
436		if result.status != KunitStatus.SUCCESS:
437			sys.exit(1)
438	elif cli_args.subcommand == 'config':
439		if cli_args.build_dir and (
440				not os.path.exists(cli_args.build_dir)):
441			os.mkdir(cli_args.build_dir)
442
443		if not linux:
444			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
445					kunitconfig_path=cli_args.kunitconfig,
446					kconfig_add=cli_args.kconfig_add,
447					arch=cli_args.arch,
448					cross_compile=cli_args.cross_compile,
449					qemu_config_path=cli_args.qemu_config)
450
451		request = KunitConfigRequest(build_dir=cli_args.build_dir,
452					     make_options=cli_args.make_options)
453		result = config_tests(linux, request)
454		kunit_parser.print_with_timestamp((
455			'Elapsed time: %.3fs\n') % (
456				result.elapsed_time))
457		if result.status != KunitStatus.SUCCESS:
458			sys.exit(1)
459	elif cli_args.subcommand == 'build':
460		if not linux:
461			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
462					kunitconfig_path=cli_args.kunitconfig,
463					kconfig_add=cli_args.kconfig_add,
464					arch=cli_args.arch,
465					cross_compile=cli_args.cross_compile,
466					qemu_config_path=cli_args.qemu_config)
467
468		request = KunitBuildRequest(build_dir=cli_args.build_dir,
469					    make_options=cli_args.make_options,
470					    jobs=cli_args.jobs,
471					    alltests=cli_args.alltests)
472		result = config_and_build_tests(linux, request)
473		kunit_parser.print_with_timestamp((
474			'Elapsed time: %.3fs\n') % (
475				result.elapsed_time))
476		if result.status != KunitStatus.SUCCESS:
477			sys.exit(1)
478	elif cli_args.subcommand == 'exec':
479		if not linux:
480			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
481					kunitconfig_path=cli_args.kunitconfig,
482					kconfig_add=cli_args.kconfig_add,
483					arch=cli_args.arch,
484					cross_compile=cli_args.cross_compile,
485					qemu_config_path=cli_args.qemu_config)
486
487		exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
488						build_dir=cli_args.build_dir,
489						json=cli_args.json,
490						timeout=cli_args.timeout,
491						alltests=cli_args.alltests,
492						filter_glob=cli_args.filter_glob,
493						kernel_args=cli_args.kernel_args,
494						run_isolated=cli_args.run_isolated)
495		result = exec_tests(linux, exec_request)
496		kunit_parser.print_with_timestamp((
497			'Elapsed time: %.3fs\n') % (result.elapsed_time))
498		if result.status != KunitStatus.SUCCESS:
499			sys.exit(1)
500	elif cli_args.subcommand == 'parse':
501		if cli_args.file == None:
502			sys.stdin.reconfigure(errors='backslashreplace')  # pytype: disable=attribute-error
503			kunit_output = sys.stdin
504		else:
505			with open(cli_args.file, 'r', errors='backslashreplace') as f:
506				kunit_output = f.read().splitlines()
507		request = KunitParseRequest(raw_output=cli_args.raw_output,
508					    build_dir='',
509					    json=cli_args.json)
510		result, _ = parse_tests(request, kunit_output)
511		if result.status != KunitStatus.SUCCESS:
512			sys.exit(1)
513	else:
514		parser.print_help()
515
516if __name__ == '__main__':
517	main(sys.argv[1:])
518