xref: /linux/tools/testing/kunit/kunit.py (revision db1679813f9f86b05bbbc6f05f4cdbe481d59352)
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 <felixguoxiuping@gmail.com>
8# Author: Brendan Higgins <brendanhiggins@google.com>
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 Any, Iterable, Sequence, List, Optional
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	result: Any
36	elapsed_time: float
37
38@dataclass
39class KunitConfigRequest:
40	build_dir: str
41	make_options: Optional[List[str]]
42
43@dataclass
44class KunitBuildRequest(KunitConfigRequest):
45	jobs: int
46	alltests: bool
47
48@dataclass
49class KunitParseRequest:
50	raw_output: Optional[str]
51	build_dir: str
52	json: Optional[str]
53
54@dataclass
55class KunitExecRequest(KunitParseRequest):
56	timeout: int
57	alltests: bool
58	filter_glob: str
59	kernel_args: Optional[List[str]]
60	run_isolated: Optional[str]
61
62@dataclass
63class KunitRequest(KunitExecRequest, KunitBuildRequest):
64	pass
65
66
67KernelDirectoryPath = sys.argv[0].split('tools/testing/kunit/')[0]
68
69def get_kernel_root_path() -> str:
70	path = sys.argv[0] if not __file__ else __file__
71	parts = os.path.realpath(path).split('tools/testing/kunit')
72	if len(parts) != 2:
73		sys.exit(1)
74	return parts[0]
75
76def config_tests(linux: kunit_kernel.LinuxSourceTree,
77		 request: KunitConfigRequest) -> KunitResult:
78	kunit_parser.print_with_timestamp('Configuring KUnit Kernel ...')
79
80	config_start = time.time()
81	success = linux.build_reconfig(request.build_dir, request.make_options)
82	config_end = time.time()
83	if not success:
84		return KunitResult(KunitStatus.CONFIG_FAILURE,
85				   'could not configure kernel',
86				   config_end - config_start)
87	return KunitResult(KunitStatus.SUCCESS,
88			   'configured kernel successfully',
89			   config_end - config_start)
90
91def build_tests(linux: kunit_kernel.LinuxSourceTree,
92		request: KunitBuildRequest) -> KunitResult:
93	kunit_parser.print_with_timestamp('Building KUnit Kernel ...')
94
95	build_start = time.time()
96	success = linux.build_kernel(request.alltests,
97				     request.jobs,
98				     request.build_dir,
99				     request.make_options)
100	build_end = time.time()
101	if not success:
102		return KunitResult(KunitStatus.BUILD_FAILURE,
103				   'could not build kernel',
104				   build_end - build_start)
105	if not success:
106		return KunitResult(KunitStatus.BUILD_FAILURE,
107				   'could not build kernel',
108				   build_end - build_start)
109	return KunitResult(KunitStatus.SUCCESS,
110			   'built kernel successfully',
111			   build_end - build_start)
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		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(result.result.test.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, result=result.result, 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]) -> KunitResult:
193	parse_start = time.time()
194
195	test_result = kunit_parser.TestResult(kunit_parser.TestStatus.SUCCESS,
196					      kunit_parser.Test(),
197					      'Tests not Parsed.')
198
199	if request.raw_output:
200		# Treat unparsed results as one passing test.
201		test_result.test.status = kunit_parser.TestStatus.SUCCESS
202		test_result.test.counts.passed = 1
203
204		output: Iterable[str] = input_data
205		if request.raw_output == 'all':
206			pass
207		elif request.raw_output == 'kunit':
208			output = kunit_parser.extract_tap_lines(output)
209		else:
210			print(f'Unknown --raw_output option "{request.raw_output}"', file=sys.stderr)
211		for line in output:
212			print(line.rstrip())
213
214	else:
215		test_result = kunit_parser.parse_run_tests(input_data)
216	parse_end = time.time()
217
218	if request.json:
219		json_obj = kunit_json.get_json_result(
220					test_result=test_result,
221					def_config='kunit_defconfig',
222					build_dir=request.build_dir,
223					json_path=request.json)
224		if request.json == 'stdout':
225			print(json_obj)
226
227	if test_result.status != kunit_parser.TestStatus.SUCCESS:
228		return KunitResult(KunitStatus.TEST_FAILURE, test_result,
229				   parse_end - parse_start)
230
231	return KunitResult(KunitStatus.SUCCESS, test_result,
232				parse_end - parse_start)
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 add_common_opts(parser) -> None:
280	parser.add_argument('--build_dir',
281			    help='As in the make command, it specifies the build '
282			    'directory.',
283			    type=str, default='.kunit', metavar='build_dir')
284	parser.add_argument('--make_options',
285			    help='X=Y make option, can be repeated.',
286			    action='append')
287	parser.add_argument('--alltests',
288			    help='Run all KUnit tests through allyesconfig',
289			    action='store_true')
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.',
294			     metavar='kunitconfig')
295	parser.add_argument('--kconfig_add',
296			     help='Additional Kconfig options to append to the '
297			     '.kunitconfig, e.g. CONFIG_KASAN=y. Can be repeated.',
298			    action='append')
299
300	parser.add_argument('--arch',
301			    help=('Specifies the architecture to run tests under. '
302				  'The architecture specified here must match the '
303				  'string passed to the ARCH make param, '
304				  'e.g. i386, x86_64, arm, um, etc. Non-UML '
305				  'architectures run on QEMU.'),
306			    type=str, default='um', metavar='arch')
307
308	parser.add_argument('--cross_compile',
309			    help=('Sets make\'s CROSS_COMPILE variable; it should '
310				  'be set to a toolchain path prefix (the prefix '
311				  'of gcc and other tools in your toolchain, for '
312				  'example `sparc64-linux-gnu-` if you have the '
313				  'sparc toolchain installed on your system, or '
314				  '`$HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux-` '
315				  'if you have downloaded the microblaze toolchain '
316				  'from the 0-day website to a directory in your '
317				  'home directory called `toolchains`).'),
318			    metavar='cross_compile')
319
320	parser.add_argument('--qemu_config',
321			    help=('Takes a path to a path to a file containing '
322				  'a QemuArchParams object.'),
323			    type=str, metavar='qemu_config')
324
325def add_build_opts(parser) -> None:
326	parser.add_argument('--jobs',
327			    help='As in the make command, "Specifies  the number of '
328			    'jobs (commands) to run simultaneously."',
329			    type=int, default=8, metavar='jobs')
330
331def add_exec_opts(parser) -> None:
332	parser.add_argument('--timeout',
333			    help='maximum number of seconds to allow for all tests '
334			    'to run. This does not include time taken to build the '
335			    'tests.',
336			    type=int,
337			    default=300,
338			    metavar='timeout')
339	parser.add_argument('filter_glob',
340			    help='Filter which KUnit test suites/tests run at '
341			    'boot-time, e.g. list* or list*.*del_test',
342			    type=str,
343			    nargs='?',
344			    default='',
345			    metavar='filter_glob')
346	parser.add_argument('--kernel_args',
347			    help='Kernel command-line parameters. Maybe be repeated',
348			     action='append')
349	parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
350			    'individual suite/test. This is can be useful for debugging '
351			    'a non-hermetic test, one that might pass/fail based on '
352			    'what ran before it.',
353			    type=str,
354			    choices=['suite', 'test']),
355
356def add_parse_opts(parser) -> None:
357	parser.add_argument('--raw_output', help='If set don\'t format output from kernel. '
358			    'If set to --raw_output=kunit, filters to just KUnit output.',
359			    type=str, nargs='?', const='all', default=None)
360	parser.add_argument('--json',
361			    nargs='?',
362			    help='Stores test results in a JSON, and either '
363			    'prints to stdout or saves to file if a '
364			    'filename is specified',
365			    type=str, const='stdout', default=None)
366
367def main(argv, linux=None):
368	parser = argparse.ArgumentParser(
369			description='Helps writing and running KUnit tests.')
370	subparser = parser.add_subparsers(dest='subcommand')
371
372	# The 'run' command will config, build, exec, and parse in one go.
373	run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
374	add_common_opts(run_parser)
375	add_build_opts(run_parser)
376	add_exec_opts(run_parser)
377	add_parse_opts(run_parser)
378
379	config_parser = subparser.add_parser('config',
380						help='Ensures that .config contains all of '
381						'the options in .kunitconfig')
382	add_common_opts(config_parser)
383
384	build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
385	add_common_opts(build_parser)
386	add_build_opts(build_parser)
387
388	exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
389	add_common_opts(exec_parser)
390	add_exec_opts(exec_parser)
391	add_parse_opts(exec_parser)
392
393	# The 'parse' option is special, as it doesn't need the kernel source
394	# (therefore there is no need for a build_dir, hence no add_common_opts)
395	# and the '--file' argument is not relevant to 'run', so isn't in
396	# add_parse_opts()
397	parse_parser = subparser.add_parser('parse',
398					    help='Parses KUnit results from a file, '
399					    'and parses formatted results.')
400	add_parse_opts(parse_parser)
401	parse_parser.add_argument('file',
402				  help='Specifies the file to read results from.',
403				  type=str, nargs='?', metavar='input_file')
404
405	cli_args = parser.parse_args(massage_argv(argv))
406
407	if get_kernel_root_path():
408		os.chdir(get_kernel_root_path())
409
410	if cli_args.subcommand == 'run':
411		if not os.path.exists(cli_args.build_dir):
412			os.mkdir(cli_args.build_dir)
413
414		if not linux:
415			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
416					kunitconfig_path=cli_args.kunitconfig,
417					kconfig_add=cli_args.kconfig_add,
418					arch=cli_args.arch,
419					cross_compile=cli_args.cross_compile,
420					qemu_config_path=cli_args.qemu_config)
421
422		request = KunitRequest(build_dir=cli_args.build_dir,
423				       make_options=cli_args.make_options,
424				       jobs=cli_args.jobs,
425				       alltests=cli_args.alltests,
426				       raw_output=cli_args.raw_output,
427				       json=cli_args.json,
428				       timeout=cli_args.timeout,
429				       filter_glob=cli_args.filter_glob,
430				       kernel_args=cli_args.kernel_args,
431				       run_isolated=cli_args.run_isolated)
432		result = run_tests(linux, request)
433		if result.status != KunitStatus.SUCCESS:
434			sys.exit(1)
435	elif cli_args.subcommand == 'config':
436		if cli_args.build_dir and (
437				not os.path.exists(cli_args.build_dir)):
438			os.mkdir(cli_args.build_dir)
439
440		if not linux:
441			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
442					kunitconfig_path=cli_args.kunitconfig,
443					kconfig_add=cli_args.kconfig_add,
444					arch=cli_args.arch,
445					cross_compile=cli_args.cross_compile,
446					qemu_config_path=cli_args.qemu_config)
447
448		request = KunitConfigRequest(build_dir=cli_args.build_dir,
449					     make_options=cli_args.make_options)
450		result = config_tests(linux, request)
451		kunit_parser.print_with_timestamp((
452			'Elapsed time: %.3fs\n') % (
453				result.elapsed_time))
454		if result.status != KunitStatus.SUCCESS:
455			sys.exit(1)
456	elif cli_args.subcommand == 'build':
457		if not linux:
458			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
459					kunitconfig_path=cli_args.kunitconfig,
460					kconfig_add=cli_args.kconfig_add,
461					arch=cli_args.arch,
462					cross_compile=cli_args.cross_compile,
463					qemu_config_path=cli_args.qemu_config)
464
465		request = KunitBuildRequest(build_dir=cli_args.build_dir,
466					    make_options=cli_args.make_options,
467					    jobs=cli_args.jobs,
468					    alltests=cli_args.alltests)
469		result = build_tests(linux, request)
470		kunit_parser.print_with_timestamp((
471			'Elapsed time: %.3fs\n') % (
472				result.elapsed_time))
473		if result.status != KunitStatus.SUCCESS:
474			sys.exit(1)
475	elif cli_args.subcommand == 'exec':
476		if not linux:
477			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir,
478					kunitconfig_path=cli_args.kunitconfig,
479					kconfig_add=cli_args.kconfig_add,
480					arch=cli_args.arch,
481					cross_compile=cli_args.cross_compile,
482					qemu_config_path=cli_args.qemu_config)
483
484		exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
485						build_dir=cli_args.build_dir,
486						json=cli_args.json,
487						timeout=cli_args.timeout,
488						alltests=cli_args.alltests,
489						filter_glob=cli_args.filter_glob,
490						kernel_args=cli_args.kernel_args,
491						run_isolated=cli_args.run_isolated)
492		result = exec_tests(linux, exec_request)
493		kunit_parser.print_with_timestamp((
494			'Elapsed time: %.3fs\n') % (result.elapsed_time))
495		if result.status != KunitStatus.SUCCESS:
496			sys.exit(1)
497	elif cli_args.subcommand == 'parse':
498		if cli_args.file == None:
499			sys.stdin.reconfigure(errors='backslashreplace')  # pytype: disable=attribute-error
500			kunit_output = sys.stdin
501		else:
502			with open(cli_args.file, 'r', errors='backslashreplace') as f:
503				kunit_output = f.read().splitlines()
504		request = KunitParseRequest(raw_output=cli_args.raw_output,
505					    build_dir='',
506					    json=cli_args.json)
507		result = parse_tests(request, kunit_output)
508		if result.status != KunitStatus.SUCCESS:
509			sys.exit(1)
510	else:
511		parser.print_help()
512
513if __name__ == '__main__':
514	main(sys.argv[1:])
515