xref: /openbmc/linux/tools/testing/kunit/kunit.py (revision 4ce94eab)
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 sys
12import os
13import time
14
15from collections import namedtuple
16from enum import Enum, auto
17
18import kunit_config
19import kunit_json
20import kunit_kernel
21import kunit_parser
22
23KunitResult = namedtuple('KunitResult', ['status','result','elapsed_time'])
24
25KunitConfigRequest = namedtuple('KunitConfigRequest',
26				['build_dir', 'make_options'])
27KunitBuildRequest = namedtuple('KunitBuildRequest',
28			       ['jobs', 'build_dir', 'alltests',
29				'make_options'])
30KunitExecRequest = namedtuple('KunitExecRequest',
31			      ['timeout', 'build_dir', 'alltests', 'filter_glob'])
32KunitParseRequest = namedtuple('KunitParseRequest',
33			       ['raw_output', 'input_data', 'build_dir', 'json'])
34KunitRequest = namedtuple('KunitRequest', ['raw_output','timeout', 'jobs',
35					   'build_dir', 'alltests', 'filter_glob',
36					   'json', 'make_options'])
37
38KernelDirectoryPath = sys.argv[0].split('tools/testing/kunit/')[0]
39
40class KunitStatus(Enum):
41	SUCCESS = auto()
42	CONFIG_FAILURE = auto()
43	BUILD_FAILURE = auto()
44	TEST_FAILURE = auto()
45
46def get_kernel_root_path() -> str:
47	path = sys.argv[0] if not __file__ else __file__
48	parts = os.path.realpath(path).split('tools/testing/kunit')
49	if len(parts) != 2:
50		sys.exit(1)
51	return parts[0]
52
53def config_tests(linux: kunit_kernel.LinuxSourceTree,
54		 request: KunitConfigRequest) -> KunitResult:
55	kunit_parser.print_with_timestamp('Configuring KUnit Kernel ...')
56
57	config_start = time.time()
58	success = linux.build_reconfig(request.build_dir, request.make_options)
59	config_end = time.time()
60	if not success:
61		return KunitResult(KunitStatus.CONFIG_FAILURE,
62				   'could not configure kernel',
63				   config_end - config_start)
64	return KunitResult(KunitStatus.SUCCESS,
65			   'configured kernel successfully',
66			   config_end - config_start)
67
68def build_tests(linux: kunit_kernel.LinuxSourceTree,
69		request: KunitBuildRequest) -> KunitResult:
70	kunit_parser.print_with_timestamp('Building KUnit Kernel ...')
71
72	build_start = time.time()
73	success = linux.build_um_kernel(request.alltests,
74					request.jobs,
75					request.build_dir,
76					request.make_options)
77	build_end = time.time()
78	if not success:
79		return KunitResult(KunitStatus.BUILD_FAILURE,
80				   'could not build kernel',
81				   build_end - build_start)
82	if not success:
83		return KunitResult(KunitStatus.BUILD_FAILURE,
84				   'could not build kernel',
85				   build_end - build_start)
86	return KunitResult(KunitStatus.SUCCESS,
87			   'built kernel successfully',
88			   build_end - build_start)
89
90def exec_tests(linux: kunit_kernel.LinuxSourceTree,
91	       request: KunitExecRequest) -> KunitResult:
92	kunit_parser.print_with_timestamp('Starting KUnit Kernel ...')
93	test_start = time.time()
94	result = linux.run_kernel(
95		timeout=None if request.alltests else request.timeout,
96                filter_glob=request.filter_glob,
97		build_dir=request.build_dir)
98
99	test_end = time.time()
100
101	return KunitResult(KunitStatus.SUCCESS,
102			   result,
103			   test_end - test_start)
104
105def parse_tests(request: KunitParseRequest) -> KunitResult:
106	parse_start = time.time()
107
108	test_result = kunit_parser.TestResult(kunit_parser.TestStatus.SUCCESS,
109					      [],
110					      'Tests not Parsed.')
111
112	if request.raw_output:
113		kunit_parser.raw_output(request.input_data)
114	else:
115		test_result = kunit_parser.parse_run_tests(request.input_data)
116	parse_end = time.time()
117
118	if request.json:
119		json_obj = kunit_json.get_json_result(
120					test_result=test_result,
121					def_config='kunit_defconfig',
122					build_dir=request.build_dir,
123					json_path=request.json)
124		if request.json == 'stdout':
125			print(json_obj)
126
127	if test_result.status != kunit_parser.TestStatus.SUCCESS:
128		return KunitResult(KunitStatus.TEST_FAILURE, test_result,
129				   parse_end - parse_start)
130
131	return KunitResult(KunitStatus.SUCCESS, test_result,
132				parse_end - parse_start)
133
134
135def run_tests(linux: kunit_kernel.LinuxSourceTree,
136	      request: KunitRequest) -> KunitResult:
137	run_start = time.time()
138
139	config_request = KunitConfigRequest(request.build_dir,
140					    request.make_options)
141	config_result = config_tests(linux, config_request)
142	if config_result.status != KunitStatus.SUCCESS:
143		return config_result
144
145	build_request = KunitBuildRequest(request.jobs, request.build_dir,
146					  request.alltests,
147					  request.make_options)
148	build_result = build_tests(linux, build_request)
149	if build_result.status != KunitStatus.SUCCESS:
150		return build_result
151
152	exec_request = KunitExecRequest(request.timeout, request.build_dir,
153					request.alltests, request.filter_glob)
154	exec_result = exec_tests(linux, exec_request)
155	if exec_result.status != KunitStatus.SUCCESS:
156		return exec_result
157
158	parse_request = KunitParseRequest(request.raw_output,
159					  exec_result.result,
160					  request.build_dir,
161					  request.json)
162	parse_result = parse_tests(parse_request)
163
164	run_end = time.time()
165
166	kunit_parser.print_with_timestamp((
167		'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
168		'building, %.3fs running\n') % (
169				run_end - run_start,
170				config_result.elapsed_time,
171				build_result.elapsed_time,
172				exec_result.elapsed_time))
173	return parse_result
174
175def add_common_opts(parser) -> None:
176	parser.add_argument('--build_dir',
177			    help='As in the make command, it specifies the build '
178			    'directory.',
179                            type=str, default='.kunit', metavar='build_dir')
180	parser.add_argument('--make_options',
181			    help='X=Y make option, can be repeated.',
182			    action='append')
183	parser.add_argument('--alltests',
184			    help='Run all KUnit tests through allyesconfig',
185			    action='store_true')
186	parser.add_argument('--kunitconfig',
187			     help='Path to Kconfig fragment that enables KUnit tests',
188			     metavar='kunitconfig')
189
190def add_build_opts(parser) -> None:
191	parser.add_argument('--jobs',
192			    help='As in the make command, "Specifies  the number of '
193			    'jobs (commands) to run simultaneously."',
194			    type=int, default=8, metavar='jobs')
195
196def add_exec_opts(parser) -> None:
197	parser.add_argument('--timeout',
198			    help='maximum number of seconds to allow for all tests '
199			    'to run. This does not include time taken to build the '
200			    'tests.',
201			    type=int,
202			    default=300,
203			    metavar='timeout')
204	parser.add_argument('filter_glob',
205			    help='maximum number of seconds to allow for all tests '
206			    'to run. This does not include time taken to build the '
207			    'tests.',
208			    type=str,
209			    nargs='?',
210			    default='',
211			    metavar='filter_glob')
212
213def add_parse_opts(parser) -> None:
214	parser.add_argument('--raw_output', help='don\'t format output from kernel',
215			    action='store_true')
216	parser.add_argument('--json',
217			    nargs='?',
218			    help='Stores test results in a JSON, and either '
219			    'prints to stdout or saves to file if a '
220			    'filename is specified',
221			    type=str, const='stdout', default=None)
222
223def main(argv, linux=None):
224	parser = argparse.ArgumentParser(
225			description='Helps writing and running KUnit tests.')
226	subparser = parser.add_subparsers(dest='subcommand')
227
228	# The 'run' command will config, build, exec, and parse in one go.
229	run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
230	add_common_opts(run_parser)
231	add_build_opts(run_parser)
232	add_exec_opts(run_parser)
233	add_parse_opts(run_parser)
234
235	config_parser = subparser.add_parser('config',
236						help='Ensures that .config contains all of '
237						'the options in .kunitconfig')
238	add_common_opts(config_parser)
239
240	build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
241	add_common_opts(build_parser)
242	add_build_opts(build_parser)
243
244	exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
245	add_common_opts(exec_parser)
246	add_exec_opts(exec_parser)
247	add_parse_opts(exec_parser)
248
249	# The 'parse' option is special, as it doesn't need the kernel source
250	# (therefore there is no need for a build_dir, hence no add_common_opts)
251	# and the '--file' argument is not relevant to 'run', so isn't in
252	# add_parse_opts()
253	parse_parser = subparser.add_parser('parse',
254					    help='Parses KUnit results from a file, '
255					    'and parses formatted results.')
256	add_parse_opts(parse_parser)
257	parse_parser.add_argument('file',
258				  help='Specifies the file to read results from.',
259				  type=str, nargs='?', metavar='input_file')
260
261	cli_args = parser.parse_args(argv)
262
263	if get_kernel_root_path():
264		os.chdir(get_kernel_root_path())
265
266	if cli_args.subcommand == 'run':
267		if not os.path.exists(cli_args.build_dir):
268			os.mkdir(cli_args.build_dir)
269
270		if not linux:
271			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir, kunitconfig_path=cli_args.kunitconfig)
272
273		request = KunitRequest(cli_args.raw_output,
274				       cli_args.timeout,
275				       cli_args.jobs,
276				       cli_args.build_dir,
277				       cli_args.alltests,
278				       cli_args.filter_glob,
279				       cli_args.json,
280				       cli_args.make_options)
281		result = run_tests(linux, request)
282		if result.status != KunitStatus.SUCCESS:
283			sys.exit(1)
284	elif cli_args.subcommand == 'config':
285		if cli_args.build_dir and (
286				not os.path.exists(cli_args.build_dir)):
287			os.mkdir(cli_args.build_dir)
288
289		if not linux:
290			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir, kunitconfig_path=cli_args.kunitconfig)
291
292		request = KunitConfigRequest(cli_args.build_dir,
293					     cli_args.make_options)
294		result = config_tests(linux, request)
295		kunit_parser.print_with_timestamp((
296			'Elapsed time: %.3fs\n') % (
297				result.elapsed_time))
298		if result.status != KunitStatus.SUCCESS:
299			sys.exit(1)
300	elif cli_args.subcommand == 'build':
301		if not linux:
302			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir, kunitconfig_path=cli_args.kunitconfig)
303
304		request = KunitBuildRequest(cli_args.jobs,
305					    cli_args.build_dir,
306					    cli_args.alltests,
307					    cli_args.make_options)
308		result = build_tests(linux, request)
309		kunit_parser.print_with_timestamp((
310			'Elapsed time: %.3fs\n') % (
311				result.elapsed_time))
312		if result.status != KunitStatus.SUCCESS:
313			sys.exit(1)
314	elif cli_args.subcommand == 'exec':
315		if not linux:
316			linux = kunit_kernel.LinuxSourceTree(cli_args.build_dir)
317
318		exec_request = KunitExecRequest(cli_args.timeout,
319						cli_args.build_dir,
320						cli_args.alltests,
321						cli_args.filter_glob)
322		exec_result = exec_tests(linux, exec_request)
323		parse_request = KunitParseRequest(cli_args.raw_output,
324						  exec_result.result,
325						  cli_args.build_dir,
326						  cli_args.json)
327		result = parse_tests(parse_request)
328		kunit_parser.print_with_timestamp((
329			'Elapsed time: %.3fs\n') % (
330				exec_result.elapsed_time))
331		if result.status != KunitStatus.SUCCESS:
332			sys.exit(1)
333	elif cli_args.subcommand == 'parse':
334		if cli_args.file == None:
335			kunit_output = sys.stdin
336		else:
337			with open(cli_args.file, 'r') as f:
338				kunit_output = f.read().splitlines()
339		request = KunitParseRequest(cli_args.raw_output,
340					    kunit_output,
341					    None,
342					    cli_args.json)
343		result = parse_tests(request)
344		if result.status != KunitStatus.SUCCESS:
345			sys.exit(1)
346	else:
347		parser.print_help()
348
349if __name__ == '__main__':
350	main(sys.argv[1:])
351