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