xref: /linux/tools/testing/kunit/kunit.py (revision 23b0f90ba871f096474e1c27c3d14f455189d2d9)
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 shlex
14import sys
15import time
16
17assert sys.version_info >= (3, 7), "Python version is too old"
18
19from dataclasses import dataclass
20from enum import Enum, auto
21from typing import Iterable, List, Optional, Sequence, Tuple
22
23import kunit_json
24import kunit_kernel
25import kunit_parser
26from kunit_printer import stdout, null_printer
27
28class KunitStatus(Enum):
29	SUCCESS = auto()
30	CONFIG_FAILURE = auto()
31	BUILD_FAILURE = auto()
32	TEST_FAILURE = auto()
33
34@dataclass
35class KunitResult:
36	status: KunitStatus
37	elapsed_time: float
38
39@dataclass
40class KunitConfigRequest:
41	build_dir: str
42	make_options: Optional[List[str]]
43
44@dataclass
45class KunitBuildRequest(KunitConfigRequest):
46	jobs: int
47
48@dataclass
49class KunitParseRequest:
50	raw_output: Optional[str]
51	json: Optional[str]
52	summary: bool
53	failed: bool
54
55@dataclass
56class KunitExecRequest(KunitParseRequest):
57	build_dir: str
58	timeout: int
59	filter_glob: str
60	filter: str
61	filter_action: Optional[str]
62	kernel_args: Optional[List[str]]
63	run_isolated: Optional[str]
64	list_tests: bool
65	list_tests_attr: bool
66
67@dataclass
68class KunitRequest(KunitExecRequest, KunitBuildRequest):
69	pass
70
71
72def get_kernel_root_path() -> str:
73	path = sys.argv[0] if not __file__ else __file__
74	parts = os.path.realpath(path).split('tools/testing/kunit')
75	if len(parts) != 2:
76		sys.exit(1)
77	return parts[0]
78
79def config_tests(linux: kunit_kernel.LinuxSourceTree,
80		 request: KunitConfigRequest) -> KunitResult:
81	stdout.print_with_timestamp('Configuring KUnit Kernel ...')
82
83	config_start = time.time()
84	success = linux.build_reconfig(request.build_dir, request.make_options)
85	config_end = time.time()
86	status = KunitStatus.SUCCESS if success else KunitStatus.CONFIG_FAILURE
87	return KunitResult(status, config_end - config_start)
88
89def build_tests(linux: kunit_kernel.LinuxSourceTree,
90		request: KunitBuildRequest) -> KunitResult:
91	stdout.print_with_timestamp('Building KUnit Kernel ...')
92
93	build_start = time.time()
94	success = linux.build_kernel(request.jobs,
95				     request.build_dir,
96				     request.make_options)
97	build_end = time.time()
98	status = KunitStatus.SUCCESS if success else KunitStatus.BUILD_FAILURE
99	return KunitResult(status, build_end - build_start)
100
101def config_and_build_tests(linux: kunit_kernel.LinuxSourceTree,
102			   request: KunitBuildRequest) -> KunitResult:
103	config_result = config_tests(linux, request)
104	if config_result.status != KunitStatus.SUCCESS:
105		return config_result
106
107	return build_tests(linux, request)
108
109def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]:
110	args = ['kunit.action=list']
111
112	if request.kernel_args:
113		args.extend(request.kernel_args)
114
115	output = linux.run_kernel(args=args,
116			   timeout=request.timeout,
117			   filter_glob=request.filter_glob,
118			   filter=request.filter,
119			   filter_action=request.filter_action,
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.
123	lines.pop()
124
125	# Filter out any extraneous non-test output that might have gotten mixed in.
126	return [l for l in output if re.match(r'^[^\s.]+\.[^\s.]+$', l)]
127
128def _list_tests_attr(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> Iterable[str]:
129	args = ['kunit.action=list_attr']
130
131	if request.kernel_args:
132		args.extend(request.kernel_args)
133
134	output = linux.run_kernel(args=args,
135			   timeout=request.timeout,
136			   filter_glob=request.filter_glob,
137			   filter=request.filter,
138			   filter_action=request.filter_action,
139			   build_dir=request.build_dir)
140	lines = kunit_parser.extract_tap_lines(output)
141	# Hack! Drop the dummy TAP version header that the executor prints out.
142	lines.pop()
143
144	# Filter out any extraneous non-test output that might have gotten mixed in.
145	return lines
146
147def _suites_from_test_list(tests: List[str]) -> List[str]:
148	"""Extracts all the suites from an ordered list of tests."""
149	suites = []  # type: List[str]
150	for t in tests:
151		parts = t.split('.', maxsplit=2)
152		if len(parts) != 2:
153			raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"')
154		suite, _ = parts
155		if not suites or suites[-1] != suite:
156			suites.append(suite)
157	return suites
158
159def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult:
160	filter_globs = [request.filter_glob]
161	if request.list_tests:
162		output = _list_tests(linux, request)
163		for line in output:
164			print(line.rstrip())
165		return KunitResult(status=KunitStatus.SUCCESS, elapsed_time=0.0)
166	if request.list_tests_attr:
167		attr_output = _list_tests_attr(linux, request)
168		for line in attr_output:
169			print(line.rstrip())
170		return KunitResult(status=KunitStatus.SUCCESS, elapsed_time=0.0)
171	if request.run_isolated:
172		tests = _list_tests(linux, request)
173		if request.run_isolated == 'test':
174			filter_globs = tests
175		elif request.run_isolated == 'suite':
176			filter_globs = _suites_from_test_list(tests)
177			# Apply the test-part of the user's glob, if present.
178			if '.' in request.filter_glob:
179				test_glob = request.filter_glob.split('.', maxsplit=2)[1]
180				filter_globs = [g + '.'+ test_glob for g in filter_globs]
181
182	metadata = kunit_json.Metadata(arch=linux.arch(), build_dir=request.build_dir, def_config='kunit_defconfig')
183
184	test_counts = kunit_parser.TestCounts()
185	exec_time = 0.0
186	for i, filter_glob in enumerate(filter_globs):
187		stdout.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs)))
188
189		test_start = time.time()
190		run_result = linux.run_kernel(
191			args=request.kernel_args,
192			timeout=request.timeout,
193			filter_glob=filter_glob,
194			filter=request.filter,
195			filter_action=request.filter_action,
196			build_dir=request.build_dir)
197
198		_, test_result = parse_tests(request, metadata, run_result)
199		# run_kernel() doesn't block on the kernel exiting.
200		# That only happens after we get the last line of output from `run_result`.
201		# So exec_time here actually contains parsing + execution time, which is fine.
202		test_end = time.time()
203		exec_time += test_end - test_start
204
205		test_counts.add_subtest_counts(test_result.counts)
206
207	if len(filter_globs) == 1 and test_counts.crashed > 0:
208		bd = request.build_dir
209		print('The kernel seems to have crashed; you can decode the stack traces with:')
210		print('$ scripts/decode_stacktrace.sh {}/vmlinux {} < {} | tee {}/decoded.log | {} parse'.format(
211				bd, bd, kunit_kernel.get_outfile_path(bd), bd, sys.argv[0]))
212
213	kunit_status = _map_to_overall_status(test_counts.get_status())
214	return KunitResult(status=kunit_status, elapsed_time=exec_time)
215
216def _map_to_overall_status(test_status: kunit_parser.TestStatus) -> KunitStatus:
217	if test_status in (kunit_parser.TestStatus.SUCCESS, kunit_parser.TestStatus.SKIPPED):
218		return KunitStatus.SUCCESS
219	return KunitStatus.TEST_FAILURE
220
221def parse_tests(request: KunitParseRequest, metadata: kunit_json.Metadata, input_data: Iterable[str]) -> Tuple[KunitResult, kunit_parser.Test]:
222	parse_start = time.time()
223
224	if request.raw_output:
225		# Treat unparsed results as one passing test.
226		fake_test = kunit_parser.Test()
227		fake_test.status = kunit_parser.TestStatus.SUCCESS
228		fake_test.counts.passed = 1
229
230		output: Iterable[str] = input_data
231		if request.raw_output == 'all' or request.raw_output == 'full':
232			pass
233		elif request.raw_output == 'kunit':
234			output = kunit_parser.extract_tap_lines(output)
235		for line in output:
236			print(line.rstrip())
237		parse_time = time.time() - parse_start
238		return KunitResult(KunitStatus.SUCCESS, parse_time), fake_test
239
240	default_printer = stdout
241	if request.summary or request.failed:
242		default_printer = null_printer
243
244	# Actually parse the test results.
245	test = kunit_parser.parse_run_tests(input_data, default_printer)
246	parse_time = time.time() - parse_start
247
248	if request.failed:
249		kunit_parser.print_test(test, request.failed, stdout)
250	kunit_parser.print_summary_line(test, stdout)
251
252	if request.json:
253		json_str = kunit_json.get_json_result(
254					test=test,
255					metadata=metadata)
256		if request.json == 'stdout':
257			print(json_str)
258		else:
259			with open(request.json, 'w') as f:
260				f.write(json_str)
261			stdout.print_with_timestamp("Test results stored in %s" %
262				os.path.abspath(request.json))
263
264	if test.status != kunit_parser.TestStatus.SUCCESS:
265		return KunitResult(KunitStatus.TEST_FAILURE, parse_time), test
266
267	return KunitResult(KunitStatus.SUCCESS, parse_time), test
268
269def run_tests(linux: kunit_kernel.LinuxSourceTree,
270	      request: KunitRequest) -> KunitResult:
271	run_start = time.time()
272
273	config_result = config_tests(linux, request)
274	if config_result.status != KunitStatus.SUCCESS:
275		return config_result
276
277	build_result = build_tests(linux, request)
278	if build_result.status != KunitStatus.SUCCESS:
279		return build_result
280
281	exec_result = exec_tests(linux, request)
282
283	run_end = time.time()
284
285	stdout.print_with_timestamp((
286		'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
287		'building, %.3fs running\n') % (
288				run_end - run_start,
289				config_result.elapsed_time,
290				build_result.elapsed_time,
291				exec_result.elapsed_time))
292	return exec_result
293
294# Problem:
295# $ kunit.py run --json
296# works as one would expect and prints the parsed test results as JSON.
297# $ kunit.py run --json suite_name
298# would *not* pass suite_name as the filter_glob and print as json.
299# argparse will consider it to be another way of writing
300# $ kunit.py run --json=suite_name
301# i.e. it would run all tests, and dump the json to a `suite_name` file.
302# So we hackily automatically rewrite --json => --json=stdout
303pseudo_bool_flag_defaults = {
304		'--json': 'stdout',
305		'--raw_output': 'kunit',
306}
307def massage_argv(argv: Sequence[str]) -> Sequence[str]:
308	def massage_arg(arg: str) -> str:
309		if arg not in pseudo_bool_flag_defaults:
310			return arg
311		return  f'{arg}={pseudo_bool_flag_defaults[arg]}'
312	return list(map(massage_arg, argv))
313
314def get_default_jobs() -> int:
315	if sys.version_info >= (3, 13):
316		if (ncpu := os.process_cpu_count()) is not None:
317			return ncpu
318		raise RuntimeError("os.process_cpu_count() returned None")
319	 # See https://github.com/python/cpython/blob/b61fece/Lib/os.py#L1175-L1186.
320	if sys.platform != "darwin":
321		return len(os.sched_getaffinity(0))
322	if (ncpu := os.cpu_count()) is not None:
323		return ncpu
324	raise RuntimeError("os.cpu_count() returned None")
325
326def get_default_build_dir() -> str:
327	if 'KBUILD_OUTPUT' in os.environ:
328		return os.path.join(os.environ['KBUILD_OUTPUT'], '.kunit')
329	return '.kunit'
330
331def add_completion_opts(parser: argparse.ArgumentParser) -> None:
332	parser.add_argument('--list-opts',
333			    help=argparse.SUPPRESS,
334			    action='store_true')
335
336def add_root_opts(parser: argparse.ArgumentParser) -> None:
337	parser.add_argument('--list-cmds',
338			    help=argparse.SUPPRESS,
339			    action='store_true')
340	add_completion_opts(parser)
341
342def add_common_opts(parser: argparse.ArgumentParser) -> None:
343	parser.add_argument('--build_dir',
344			    help='As in the make command, it specifies the build '
345			    'directory.',
346			    type=str, default=get_default_build_dir(), metavar='DIR')
347	parser.add_argument('--make_options',
348			    help='X=Y make option, can be repeated.',
349			    action='append', metavar='X=Y')
350	parser.add_argument('--alltests',
351			    help='Run all KUnit tests via tools/testing/kunit/configs/all_tests.config',
352			    action='store_true')
353	parser.add_argument('--kunitconfig',
354			     help='Path to Kconfig fragment that enables KUnit tests.'
355			     ' If given a directory, (e.g. lib/kunit), "/.kunitconfig" '
356			     'will get  automatically appended. If repeated, the files '
357			     'blindly concatenated, which might not work in all cases.',
358			     action='append', metavar='PATHS')
359	parser.add_argument('--kconfig_add',
360			     help='Additional Kconfig options to append to the '
361			     '.kunitconfig, e.g. CONFIG_KASAN=y. Can be repeated.',
362			    action='append', metavar='CONFIG_X=Y')
363
364	parser.add_argument('--arch',
365			    help=('Specifies the architecture to run tests under. '
366				  'The architecture specified here must match the '
367				  'string passed to the ARCH make param, '
368				  'e.g. i386, x86_64, arm, um, etc. Non-UML '
369				  'architectures run on QEMU.'),
370			    type=str, default='um', metavar='ARCH')
371
372	parser.add_argument('--cross_compile',
373			    help=('Sets make\'s CROSS_COMPILE variable; it should '
374				  'be set to a toolchain path prefix (the prefix '
375				  'of gcc and other tools in your toolchain, for '
376				  'example `sparc64-linux-gnu-` if you have the '
377				  'sparc toolchain installed on your system, or '
378				  '`$HOME/toolchains/microblaze/gcc-9.2.0-nolibc/microblaze-linux/bin/microblaze-linux-` '
379				  'if you have downloaded the microblaze toolchain '
380				  'from the 0-day website to a directory in your '
381				  'home directory called `toolchains`).'),
382			    metavar='PREFIX')
383
384	parser.add_argument('--qemu_config',
385			    help=('Takes a path to a path to a file containing '
386				  'a QemuArchParams object.'),
387			    type=str, metavar='FILE')
388
389	parser.add_argument('--qemu_args',
390			    help='Additional QEMU arguments, e.g. "-smp 8"',
391			    action='append', metavar='')
392
393	add_completion_opts(parser)
394
395def add_build_opts(parser: argparse.ArgumentParser) -> None:
396	parser.add_argument('--jobs',
397			    help='As in the make command, "Specifies  the number of '
398			    'jobs (commands) to run simultaneously."',
399			    type=int, default=get_default_jobs(), metavar='N')
400
401def add_exec_opts(parser: argparse.ArgumentParser) -> None:
402	parser.add_argument('--timeout',
403			    help='maximum number of seconds to allow for all tests '
404			    'to run. This does not include time taken to build the '
405			    'tests.',
406			    type=int,
407			    default=300,
408			    metavar='SECONDS')
409	parser.add_argument('filter_glob',
410			    help='Filter which KUnit test suites/tests run at '
411			    'boot-time, e.g. list* or list*.*del_test',
412			    type=str,
413			    nargs='?',
414			    default='',
415			    metavar='filter_glob')
416	parser.add_argument('--filter',
417			    help='Filter KUnit tests with attributes, '
418			    'e.g. module=example or speed>slow',
419			    type=str,
420				default='')
421	parser.add_argument('--filter_action',
422			    help='If set to skip, filtered tests will be skipped, '
423				'e.g. --filter_action=skip. Otherwise they will not run.',
424			    type=str,
425				choices=['skip'])
426	parser.add_argument('--kernel_args',
427			    help='Kernel command-line parameters. Maybe be repeated',
428			     action='append', metavar='')
429	parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
430			    'individual suite/test. This is can be useful for debugging '
431			    'a non-hermetic test, one that might pass/fail based on '
432			    'what ran before it.',
433			    type=str,
434			    choices=['suite', 'test'])
435	parser.add_argument('--list_tests', help='If set, list all tests that will be '
436			    'run.',
437			    action='store_true')
438	parser.add_argument('--list_tests_attr', help='If set, list all tests and test '
439			    'attributes.',
440			    action='store_true')
441
442def add_parse_opts(parser: argparse.ArgumentParser) -> None:
443	parser.add_argument('--raw_output', help='If set don\'t parse output from kernel. '
444			    'By default, filters to just KUnit output. Use '
445			    '--raw_output=all to show everything',
446			     type=str, nargs='?', const='all', default=None, choices=['all', 'full', 'kunit'])
447	parser.add_argument('--json',
448			    nargs='?',
449			    help='Prints parsed test results as JSON to stdout or a file if '
450			    'a filename is specified. Does nothing if --raw_output is set.',
451			    type=str, const='stdout', default=None, metavar='FILE')
452	parser.add_argument('--summary',
453			    help='Prints only the summary line for parsed test results.'
454				'Does nothing if --raw_output is set.',
455			    action='store_true')
456	parser.add_argument('--failed',
457			    help='Prints only the failed parsed test results and summary line.'
458				'Does nothing if --raw_output is set.',
459			    action='store_true')
460
461
462def tree_from_args(cli_args: argparse.Namespace) -> kunit_kernel.LinuxSourceTree:
463	"""Returns a LinuxSourceTree based on the user's arguments."""
464	# Allow users to specify multiple arguments in one string, e.g. '-smp 8'
465	qemu_args: List[str] = []
466	if cli_args.qemu_args:
467		for arg in cli_args.qemu_args:
468			qemu_args.extend(shlex.split(arg))
469
470	kunitconfigs = cli_args.kunitconfig if cli_args.kunitconfig else []
471	if cli_args.alltests:
472		# Prepend so user-specified options take prio if we ever allow
473		# --kunitconfig options to have differing options.
474		kunitconfigs = [kunit_kernel.ALL_TESTS_CONFIG_PATH] + kunitconfigs
475
476	return kunit_kernel.LinuxSourceTree(cli_args.build_dir,
477			kunitconfig_paths=kunitconfigs,
478			kconfig_add=cli_args.kconfig_add,
479			arch=cli_args.arch,
480			cross_compile=cli_args.cross_compile,
481			qemu_config_path=cli_args.qemu_config,
482			extra_qemu_args=qemu_args)
483
484
485def run_handler(cli_args: argparse.Namespace) -> None:
486	if not os.path.exists(cli_args.build_dir):
487		os.mkdir(cli_args.build_dir)
488
489	linux = tree_from_args(cli_args)
490	request = KunitRequest(build_dir=cli_args.build_dir,
491					make_options=cli_args.make_options,
492					jobs=cli_args.jobs,
493					raw_output=cli_args.raw_output,
494					json=cli_args.json,
495					summary=cli_args.summary,
496					failed=cli_args.failed,
497					timeout=cli_args.timeout,
498					filter_glob=cli_args.filter_glob,
499					filter=cli_args.filter,
500					filter_action=cli_args.filter_action,
501					kernel_args=cli_args.kernel_args,
502					run_isolated=cli_args.run_isolated,
503					list_tests=cli_args.list_tests,
504					list_tests_attr=cli_args.list_tests_attr)
505	result = run_tests(linux, request)
506	if result.status != KunitStatus.SUCCESS:
507		sys.exit(1)
508
509
510def config_handler(cli_args: argparse.Namespace) -> None:
511	if cli_args.build_dir and (
512			not os.path.exists(cli_args.build_dir)):
513		os.mkdir(cli_args.build_dir)
514
515	linux = tree_from_args(cli_args)
516	request = KunitConfigRequest(build_dir=cli_args.build_dir,
517						make_options=cli_args.make_options)
518	result = config_tests(linux, request)
519	stdout.print_with_timestamp((
520		'Elapsed time: %.3fs\n') % (
521			result.elapsed_time))
522	if result.status != KunitStatus.SUCCESS:
523		sys.exit(1)
524
525
526def build_handler(cli_args: argparse.Namespace) -> None:
527	linux = tree_from_args(cli_args)
528	request = KunitBuildRequest(build_dir=cli_args.build_dir,
529					make_options=cli_args.make_options,
530					jobs=cli_args.jobs)
531	result = config_and_build_tests(linux, request)
532	stdout.print_with_timestamp((
533		'Elapsed time: %.3fs\n') % (
534			result.elapsed_time))
535	if result.status != KunitStatus.SUCCESS:
536		sys.exit(1)
537
538
539def exec_handler(cli_args: argparse.Namespace) -> None:
540	linux = tree_from_args(cli_args)
541	exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
542					build_dir=cli_args.build_dir,
543					json=cli_args.json,
544					summary=cli_args.summary,
545					failed=cli_args.failed,
546					timeout=cli_args.timeout,
547					filter_glob=cli_args.filter_glob,
548					filter=cli_args.filter,
549					filter_action=cli_args.filter_action,
550					kernel_args=cli_args.kernel_args,
551					run_isolated=cli_args.run_isolated,
552					list_tests=cli_args.list_tests,
553					list_tests_attr=cli_args.list_tests_attr)
554	result = exec_tests(linux, exec_request)
555	stdout.print_with_timestamp((
556		'Elapsed time: %.3fs\n') % (result.elapsed_time))
557	if result.status != KunitStatus.SUCCESS:
558		sys.exit(1)
559
560
561def parse_handler(cli_args: argparse.Namespace) -> None:
562	if cli_args.file is None:
563		sys.stdin.reconfigure(errors='backslashreplace')  # type: ignore
564		kunit_output = sys.stdin  # type: Iterable[str]
565	else:
566		with open(cli_args.file, 'r', errors='backslashreplace') as f:
567			kunit_output = f.read().splitlines()
568	# We know nothing about how the result was created!
569	metadata = kunit_json.Metadata()
570	request = KunitParseRequest(raw_output=cli_args.raw_output,
571					json=cli_args.json, summary=cli_args.summary,
572					failed=cli_args.failed)
573	result, _ = parse_tests(request, metadata, kunit_output)
574	if result.status != KunitStatus.SUCCESS:
575		sys.exit(1)
576
577
578subcommand_handlers_map = {
579	'run': run_handler,
580	'config': config_handler,
581	'build': build_handler,
582	'exec': exec_handler,
583	'parse': parse_handler
584}
585
586
587def main(argv: Sequence[str]) -> None:
588	parser = argparse.ArgumentParser(
589			description='Helps writing and running KUnit tests.')
590	add_root_opts(parser)
591	subparser = parser.add_subparsers(dest='subcommand')
592
593	# The 'run' command will config, build, exec, and parse in one go.
594	run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
595	add_common_opts(run_parser)
596	add_build_opts(run_parser)
597	add_exec_opts(run_parser)
598	add_parse_opts(run_parser)
599
600	config_parser = subparser.add_parser('config',
601						help='Ensures that .config contains all of '
602						'the options in .kunitconfig')
603	add_common_opts(config_parser)
604
605	build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
606	add_common_opts(build_parser)
607	add_build_opts(build_parser)
608
609	exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
610	add_common_opts(exec_parser)
611	add_exec_opts(exec_parser)
612	add_parse_opts(exec_parser)
613
614	# The 'parse' option is special, as it doesn't need the kernel source
615	# (therefore there is no need for a build_dir, hence no add_common_opts)
616	# and the '--file' argument is not relevant to 'run', so isn't in
617	# add_parse_opts()
618	parse_parser = subparser.add_parser('parse',
619					    help='Parses KUnit results from a file, '
620					    'and parses formatted results.')
621	add_parse_opts(parse_parser)
622	parse_parser.add_argument('file',
623				  help='Specifies the file to read results from.',
624				  type=str, nargs='?', metavar='input_file')
625	add_completion_opts(parse_parser)
626
627	cli_args = parser.parse_args(massage_argv(argv))
628
629	if get_kernel_root_path():
630		os.chdir(get_kernel_root_path())
631
632	if cli_args.list_cmds:
633		print(" ".join(subparser.choices.keys()))
634		return
635
636	if cli_args.list_opts:
637		target_parser = subparser.choices.get(cli_args.subcommand)
638		if not target_parser:
639			target_parser = parser
640
641		# Accessing private attribute _option_string_actions to get
642		# the list of options. This is not a public API, but argparse
643		# does not provide a way to inspect options programmatically.
644		print(' '.join(target_parser._option_string_actions.keys()))
645		return
646
647	subcomand_handler = subcommand_handlers_map.get(cli_args.subcommand, None)
648
649	if subcomand_handler is None:
650		parser.print_help()
651		return
652
653	subcomand_handler(cli_args)
654
655
656if __name__ == '__main__':
657	main(sys.argv[1:])
658