Loading...
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
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
53@dataclass
54class KunitExecRequest(KunitParseRequest):
55 build_dir: str
56 timeout: int
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 stdout.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 stdout.print_with_timestamp('Building KUnit Kernel ...')
89
90 build_start = time.time()
91 success = linux.build_kernel(request.jobs,
92 request.build_dir,
93 request.make_options)
94 build_end = time.time()
95 if not success:
96 return KunitResult(KunitStatus.BUILD_FAILURE,
97 build_end - build_start)
98 if not success:
99 return KunitResult(KunitStatus.BUILD_FAILURE,
100 build_end - build_start)
101 return KunitResult(KunitStatus.SUCCESS,
102 build_end - build_start)
103
104def config_and_build_tests(linux: kunit_kernel.LinuxSourceTree,
105 request: KunitBuildRequest) -> KunitResult:
106 config_result = config_tests(linux, request)
107 if config_result.status != KunitStatus.SUCCESS:
108 return config_result
109
110 return build_tests(linux, request)
111
112def _list_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> List[str]:
113 args = ['kunit.action=list']
114 if request.kernel_args:
115 args.extend(request.kernel_args)
116
117 output = linux.run_kernel(args=args,
118 timeout=request.timeout,
119 filter_glob=request.filter_glob,
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 lines if re.match(r'^[^\s.]+\.[^\s.]+$', l)]
127
128def _suites_from_test_list(tests: List[str]) -> List[str]:
129 """Extracts all the suites from an ordered list of tests."""
130 suites = [] # type: List[str]
131 for t in tests:
132 parts = t.split('.', maxsplit=2)
133 if len(parts) != 2:
134 raise ValueError(f'internal KUnit error, test name should be of the form "<suite>.<test>", got "{t}"')
135 suite, case = parts
136 if not suites or suites[-1] != suite:
137 suites.append(suite)
138 return suites
139
140
141
142def exec_tests(linux: kunit_kernel.LinuxSourceTree, request: KunitExecRequest) -> KunitResult:
143 filter_globs = [request.filter_glob]
144 if request.run_isolated:
145 tests = _list_tests(linux, request)
146 if request.run_isolated == 'test':
147 filter_globs = tests
148 if request.run_isolated == 'suite':
149 filter_globs = _suites_from_test_list(tests)
150 # Apply the test-part of the user's glob, if present.
151 if '.' in request.filter_glob:
152 test_glob = request.filter_glob.split('.', maxsplit=2)[1]
153 filter_globs = [g + '.'+ test_glob for g in filter_globs]
154
155 metadata = kunit_json.Metadata(arch=linux.arch(), build_dir=request.build_dir, def_config='kunit_defconfig')
156
157 test_counts = kunit_parser.TestCounts()
158 exec_time = 0.0
159 for i, filter_glob in enumerate(filter_globs):
160 stdout.print_with_timestamp('Starting KUnit Kernel ({}/{})...'.format(i+1, len(filter_globs)))
161
162 test_start = time.time()
163 run_result = linux.run_kernel(
164 args=request.kernel_args,
165 timeout=request.timeout,
166 filter_glob=filter_glob,
167 build_dir=request.build_dir)
168
169 _, test_result = parse_tests(request, metadata, run_result)
170 # run_kernel() doesn't block on the kernel exiting.
171 # That only happens after we get the last line of output from `run_result`.
172 # So exec_time here actually contains parsing + execution time, which is fine.
173 test_end = time.time()
174 exec_time += test_end - test_start
175
176 test_counts.add_subtest_counts(test_result.counts)
177
178 if len(filter_globs) == 1 and test_counts.crashed > 0:
179 bd = request.build_dir
180 print('The kernel seems to have crashed; you can decode the stack traces with:')
181 print('$ scripts/decode_stacktrace.sh {}/vmlinux {} < {} | tee {}/decoded.log | {} parse'.format(
182 bd, bd, kunit_kernel.get_outfile_path(bd), bd, sys.argv[0]))
183
184 kunit_status = _map_to_overall_status(test_counts.get_status())
185 return KunitResult(status=kunit_status, elapsed_time=exec_time)
186
187def _map_to_overall_status(test_status: kunit_parser.TestStatus) -> KunitStatus:
188 if test_status in (kunit_parser.TestStatus.SUCCESS, kunit_parser.TestStatus.SKIPPED):
189 return KunitStatus.SUCCESS
190 return KunitStatus.TEST_FAILURE
191
192def parse_tests(request: KunitParseRequest, metadata: kunit_json.Metadata, input_data: Iterable[str]) -> Tuple[KunitResult, kunit_parser.Test]:
193 parse_start = time.time()
194
195 if request.raw_output:
196 # Treat unparsed results as one passing test.
197 fake_test = kunit_parser.Test()
198 fake_test.status = kunit_parser.TestStatus.SUCCESS
199 fake_test.counts.passed = 1
200
201 output: Iterable[str] = input_data
202 if request.raw_output == 'all':
203 pass
204 elif request.raw_output == 'kunit':
205 output = kunit_parser.extract_tap_lines(output)
206 for line in output:
207 print(line.rstrip())
208 parse_time = time.time() - parse_start
209 return KunitResult(KunitStatus.SUCCESS, parse_time), fake_test
210
211
212 # Actually parse the test results.
213 test = kunit_parser.parse_run_tests(input_data)
214 parse_time = time.time() - parse_start
215
216 if request.json:
217 json_str = kunit_json.get_json_result(
218 test=test,
219 metadata=metadata)
220 if request.json == 'stdout':
221 print(json_str)
222 else:
223 with open(request.json, 'w') as f:
224 f.write(json_str)
225 stdout.print_with_timestamp("Test results stored in %s" %
226 os.path.abspath(request.json))
227
228 if test.status != kunit_parser.TestStatus.SUCCESS:
229 return KunitResult(KunitStatus.TEST_FAILURE, parse_time), test
230
231 return KunitResult(KunitStatus.SUCCESS, parse_time), test
232
233def run_tests(linux: kunit_kernel.LinuxSourceTree,
234 request: KunitRequest) -> KunitResult:
235 run_start = time.time()
236
237 config_result = config_tests(linux, request)
238 if config_result.status != KunitStatus.SUCCESS:
239 return config_result
240
241 build_result = build_tests(linux, request)
242 if build_result.status != KunitStatus.SUCCESS:
243 return build_result
244
245 exec_result = exec_tests(linux, request)
246
247 run_end = time.time()
248
249 stdout.print_with_timestamp((
250 'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
251 'building, %.3fs running\n') % (
252 run_end - run_start,
253 config_result.elapsed_time,
254 build_result.elapsed_time,
255 exec_result.elapsed_time))
256 return exec_result
257
258# Problem:
259# $ kunit.py run --json
260# works as one would expect and prints the parsed test results as JSON.
261# $ kunit.py run --json suite_name
262# would *not* pass suite_name as the filter_glob and print as json.
263# argparse will consider it to be another way of writing
264# $ kunit.py run --json=suite_name
265# i.e. it would run all tests, and dump the json to a `suite_name` file.
266# So we hackily automatically rewrite --json => --json=stdout
267pseudo_bool_flag_defaults = {
268 '--json': 'stdout',
269 '--raw_output': 'kunit',
270}
271def massage_argv(argv: Sequence[str]) -> Sequence[str]:
272 def massage_arg(arg: str) -> str:
273 if arg not in pseudo_bool_flag_defaults:
274 return arg
275 return f'{arg}={pseudo_bool_flag_defaults[arg]}'
276 return list(map(massage_arg, argv))
277
278def get_default_jobs() -> int:
279 return len(os.sched_getaffinity(0))
280
281def add_common_opts(parser) -> None:
282 parser.add_argument('--build_dir',
283 help='As in the make command, it specifies the build '
284 'directory.',
285 type=str, default='.kunit', metavar='DIR')
286 parser.add_argument('--make_options',
287 help='X=Y make option, can be repeated.',
288 action='append', metavar='X=Y')
289 parser.add_argument('--alltests',
290 help='Run all KUnit tests via tools/testing/kunit/configs/all_tests.config',
291 action='store_true')
292 parser.add_argument('--kunitconfig',
293 help='Path to Kconfig fragment that enables KUnit tests.'
294 ' If given a directory, (e.g. lib/kunit), "/.kunitconfig" '
295 'will get automatically appended. If repeated, the files '
296 'blindly concatenated, which might not work in all cases.',
297 action='append', metavar='PATHS')
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', metavar='CONFIG_X=Y')
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='PREFIX')
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='FILE')
327
328 parser.add_argument('--qemu_args',
329 help='Additional QEMU arguments, e.g. "-smp 8"',
330 action='append', metavar='')
331
332def add_build_opts(parser) -> None:
333 parser.add_argument('--jobs',
334 help='As in the make command, "Specifies the number of '
335 'jobs (commands) to run simultaneously."',
336 type=int, default=get_default_jobs(), metavar='N')
337
338def add_exec_opts(parser) -> None:
339 parser.add_argument('--timeout',
340 help='maximum number of seconds to allow for all tests '
341 'to run. This does not include time taken to build the '
342 'tests.',
343 type=int,
344 default=300,
345 metavar='SECONDS')
346 parser.add_argument('filter_glob',
347 help='Filter which KUnit test suites/tests run at '
348 'boot-time, e.g. list* or list*.*del_test',
349 type=str,
350 nargs='?',
351 default='',
352 metavar='filter_glob')
353 parser.add_argument('--kernel_args',
354 help='Kernel command-line parameters. Maybe be repeated',
355 action='append', metavar='')
356 parser.add_argument('--run_isolated', help='If set, boot the kernel for each '
357 'individual suite/test. This is can be useful for debugging '
358 'a non-hermetic test, one that might pass/fail based on '
359 'what ran before it.',
360 type=str,
361 choices=['suite', 'test'])
362
363def add_parse_opts(parser) -> None:
364 parser.add_argument('--raw_output', help='If set don\'t parse output from kernel. '
365 'By default, filters to just KUnit output. Use '
366 '--raw_output=all to show everything',
367 type=str, nargs='?', const='all', default=None, choices=['all', 'kunit'])
368 parser.add_argument('--json',
369 nargs='?',
370 help='Prints parsed test results as JSON to stdout or a file if '
371 'a filename is specified. Does nothing if --raw_output is set.',
372 type=str, const='stdout', default=None, metavar='FILE')
373
374
375def tree_from_args(cli_args: argparse.Namespace) -> kunit_kernel.LinuxSourceTree:
376 """Returns a LinuxSourceTree based on the user's arguments."""
377 # Allow users to specify multiple arguments in one string, e.g. '-smp 8'
378 qemu_args: List[str] = []
379 if cli_args.qemu_args:
380 for arg in cli_args.qemu_args:
381 qemu_args.extend(shlex.split(arg))
382
383 kunitconfigs = cli_args.kunitconfig if cli_args.kunitconfig else []
384 if cli_args.alltests:
385 # Prepend so user-specified options take prio if we ever allow
386 # --kunitconfig options to have differing options.
387 kunitconfigs = [kunit_kernel.ALL_TESTS_CONFIG_PATH] + kunitconfigs
388
389 return kunit_kernel.LinuxSourceTree(cli_args.build_dir,
390 kunitconfig_paths=kunitconfigs,
391 kconfig_add=cli_args.kconfig_add,
392 arch=cli_args.arch,
393 cross_compile=cli_args.cross_compile,
394 qemu_config_path=cli_args.qemu_config,
395 extra_qemu_args=qemu_args)
396
397
398def main(argv):
399 parser = argparse.ArgumentParser(
400 description='Helps writing and running KUnit tests.')
401 subparser = parser.add_subparsers(dest='subcommand')
402
403 # The 'run' command will config, build, exec, and parse in one go.
404 run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
405 add_common_opts(run_parser)
406 add_build_opts(run_parser)
407 add_exec_opts(run_parser)
408 add_parse_opts(run_parser)
409
410 config_parser = subparser.add_parser('config',
411 help='Ensures that .config contains all of '
412 'the options in .kunitconfig')
413 add_common_opts(config_parser)
414
415 build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
416 add_common_opts(build_parser)
417 add_build_opts(build_parser)
418
419 exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
420 add_common_opts(exec_parser)
421 add_exec_opts(exec_parser)
422 add_parse_opts(exec_parser)
423
424 # The 'parse' option is special, as it doesn't need the kernel source
425 # (therefore there is no need for a build_dir, hence no add_common_opts)
426 # and the '--file' argument is not relevant to 'run', so isn't in
427 # add_parse_opts()
428 parse_parser = subparser.add_parser('parse',
429 help='Parses KUnit results from a file, '
430 'and parses formatted results.')
431 add_parse_opts(parse_parser)
432 parse_parser.add_argument('file',
433 help='Specifies the file to read results from.',
434 type=str, nargs='?', metavar='input_file')
435
436 cli_args = parser.parse_args(massage_argv(argv))
437
438 if get_kernel_root_path():
439 os.chdir(get_kernel_root_path())
440
441 if cli_args.subcommand == 'run':
442 if not os.path.exists(cli_args.build_dir):
443 os.mkdir(cli_args.build_dir)
444
445 linux = tree_from_args(cli_args)
446 request = KunitRequest(build_dir=cli_args.build_dir,
447 make_options=cli_args.make_options,
448 jobs=cli_args.jobs,
449 raw_output=cli_args.raw_output,
450 json=cli_args.json,
451 timeout=cli_args.timeout,
452 filter_glob=cli_args.filter_glob,
453 kernel_args=cli_args.kernel_args,
454 run_isolated=cli_args.run_isolated)
455 result = run_tests(linux, request)
456 if result.status != KunitStatus.SUCCESS:
457 sys.exit(1)
458 elif cli_args.subcommand == 'config':
459 if cli_args.build_dir and (
460 not os.path.exists(cli_args.build_dir)):
461 os.mkdir(cli_args.build_dir)
462
463 linux = tree_from_args(cli_args)
464 request = KunitConfigRequest(build_dir=cli_args.build_dir,
465 make_options=cli_args.make_options)
466 result = config_tests(linux, request)
467 stdout.print_with_timestamp((
468 'Elapsed time: %.3fs\n') % (
469 result.elapsed_time))
470 if result.status != KunitStatus.SUCCESS:
471 sys.exit(1)
472 elif cli_args.subcommand == 'build':
473 linux = tree_from_args(cli_args)
474 request = KunitBuildRequest(build_dir=cli_args.build_dir,
475 make_options=cli_args.make_options,
476 jobs=cli_args.jobs)
477 result = config_and_build_tests(linux, request)
478 stdout.print_with_timestamp((
479 'Elapsed time: %.3fs\n') % (
480 result.elapsed_time))
481 if result.status != KunitStatus.SUCCESS:
482 sys.exit(1)
483 elif cli_args.subcommand == 'exec':
484 linux = tree_from_args(cli_args)
485 exec_request = KunitExecRequest(raw_output=cli_args.raw_output,
486 build_dir=cli_args.build_dir,
487 json=cli_args.json,
488 timeout=cli_args.timeout,
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 stdout.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 is 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 # We know nothing about how the result was created!
505 metadata = kunit_json.Metadata()
506 request = KunitParseRequest(raw_output=cli_args.raw_output,
507 json=cli_args.json)
508 result, _ = parse_tests(request, metadata, kunit_output)
509 if result.status != KunitStatus.SUCCESS:
510 sys.exit(1)
511 else:
512 parser.print_help()
513
514if __name__ == '__main__':
515 main(sys.argv[1:])
1#!/usr/bin/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
14import shutil
15
16from collections import namedtuple
17from enum import Enum, auto
18
19import kunit_config
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'])
32KunitParseRequest = namedtuple('KunitParseRequest',
33 ['raw_output', 'input_data'])
34KunitRequest = namedtuple('KunitRequest', ['raw_output','timeout', 'jobs',
35 'build_dir', 'alltests',
36 '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 create_default_kunitconfig():
47 if not os.path.exists(kunit_kernel.kunitconfig_path):
48 shutil.copyfile('arch/um/configs/kunit_defconfig',
49 kunit_kernel.kunitconfig_path)
50
51def get_kernel_root_path():
52 parts = sys.argv[0] if not __file__ else __file__
53 parts = os.path.realpath(parts).split('tools/testing/kunit')
54 if len(parts) != 2:
55 sys.exit(1)
56 return parts[0]
57
58def config_tests(linux: kunit_kernel.LinuxSourceTree,
59 request: KunitConfigRequest) -> KunitResult:
60 kunit_parser.print_with_timestamp('Configuring KUnit Kernel ...')
61
62 config_start = time.time()
63 create_default_kunitconfig()
64 success = linux.build_reconfig(request.build_dir, request.make_options)
65 config_end = time.time()
66 if not success:
67 return KunitResult(KunitStatus.CONFIG_FAILURE,
68 'could not configure kernel',
69 config_end - config_start)
70 return KunitResult(KunitStatus.SUCCESS,
71 'configured kernel successfully',
72 config_end - config_start)
73
74def build_tests(linux: kunit_kernel.LinuxSourceTree,
75 request: KunitBuildRequest) -> KunitResult:
76 kunit_parser.print_with_timestamp('Building KUnit Kernel ...')
77
78 build_start = time.time()
79 success = linux.build_um_kernel(request.alltests,
80 request.jobs,
81 request.build_dir,
82 request.make_options)
83 build_end = time.time()
84 if not success:
85 return KunitResult(KunitStatus.BUILD_FAILURE,
86 'could not build kernel',
87 build_end - build_start)
88 if not success:
89 return KunitResult(KunitStatus.BUILD_FAILURE,
90 'could not build kernel',
91 build_end - build_start)
92 return KunitResult(KunitStatus.SUCCESS,
93 'built kernel successfully',
94 build_end - build_start)
95
96def exec_tests(linux: kunit_kernel.LinuxSourceTree,
97 request: KunitExecRequest) -> KunitResult:
98 kunit_parser.print_with_timestamp('Starting KUnit Kernel ...')
99 test_start = time.time()
100 result = linux.run_kernel(
101 timeout=None if request.alltests else request.timeout,
102 build_dir=request.build_dir)
103
104 test_end = time.time()
105
106 return KunitResult(KunitStatus.SUCCESS,
107 result,
108 test_end - test_start)
109
110def parse_tests(request: KunitParseRequest) -> KunitResult:
111 parse_start = time.time()
112
113 test_result = kunit_parser.TestResult(kunit_parser.TestStatus.SUCCESS,
114 [],
115 'Tests not Parsed.')
116 if request.raw_output:
117 kunit_parser.raw_output(request.input_data)
118 else:
119 test_result = kunit_parser.parse_run_tests(request.input_data)
120 parse_end = time.time()
121
122 if test_result.status != kunit_parser.TestStatus.SUCCESS:
123 return KunitResult(KunitStatus.TEST_FAILURE, test_result,
124 parse_end - parse_start)
125
126 return KunitResult(KunitStatus.SUCCESS, test_result,
127 parse_end - parse_start)
128
129
130def run_tests(linux: kunit_kernel.LinuxSourceTree,
131 request: KunitRequest) -> KunitResult:
132 run_start = time.time()
133
134 config_request = KunitConfigRequest(request.build_dir,
135 request.make_options)
136 config_result = config_tests(linux, config_request)
137 if config_result.status != KunitStatus.SUCCESS:
138 return config_result
139
140 build_request = KunitBuildRequest(request.jobs, request.build_dir,
141 request.alltests,
142 request.make_options)
143 build_result = build_tests(linux, build_request)
144 if build_result.status != KunitStatus.SUCCESS:
145 return build_result
146
147 exec_request = KunitExecRequest(request.timeout, request.build_dir,
148 request.alltests)
149 exec_result = exec_tests(linux, exec_request)
150 if exec_result.status != KunitStatus.SUCCESS:
151 return exec_result
152
153 parse_request = KunitParseRequest(request.raw_output,
154 exec_result.result)
155 parse_result = parse_tests(parse_request)
156
157 run_end = time.time()
158
159 kunit_parser.print_with_timestamp((
160 'Elapsed time: %.3fs total, %.3fs configuring, %.3fs ' +
161 'building, %.3fs running\n') % (
162 run_end - run_start,
163 config_result.elapsed_time,
164 build_result.elapsed_time,
165 exec_result.elapsed_time))
166 return parse_result
167
168def add_common_opts(parser):
169 parser.add_argument('--build_dir',
170 help='As in the make command, it specifies the build '
171 'directory.',
172 type=str, default='.kunit', metavar='build_dir')
173 parser.add_argument('--make_options',
174 help='X=Y make option, can be repeated.',
175 action='append')
176 parser.add_argument('--alltests',
177 help='Run all KUnit tests through allyesconfig',
178 action='store_true')
179
180def add_build_opts(parser):
181 parser.add_argument('--jobs',
182 help='As in the make command, "Specifies the number of '
183 'jobs (commands) to run simultaneously."',
184 type=int, default=8, metavar='jobs')
185
186def add_exec_opts(parser):
187 parser.add_argument('--timeout',
188 help='maximum number of seconds to allow for all tests '
189 'to run. This does not include time taken to build the '
190 'tests.',
191 type=int,
192 default=300,
193 metavar='timeout')
194
195def add_parse_opts(parser):
196 parser.add_argument('--raw_output', help='don\'t format output from kernel',
197 action='store_true')
198
199
200def main(argv, linux=None):
201 parser = argparse.ArgumentParser(
202 description='Helps writing and running KUnit tests.')
203 subparser = parser.add_subparsers(dest='subcommand')
204
205 # The 'run' command will config, build, exec, and parse in one go.
206 run_parser = subparser.add_parser('run', help='Runs KUnit tests.')
207 add_common_opts(run_parser)
208 add_build_opts(run_parser)
209 add_exec_opts(run_parser)
210 add_parse_opts(run_parser)
211
212 config_parser = subparser.add_parser('config',
213 help='Ensures that .config contains all of '
214 'the options in .kunitconfig')
215 add_common_opts(config_parser)
216
217 build_parser = subparser.add_parser('build', help='Builds a kernel with KUnit tests')
218 add_common_opts(build_parser)
219 add_build_opts(build_parser)
220
221 exec_parser = subparser.add_parser('exec', help='Run a kernel with KUnit tests')
222 add_common_opts(exec_parser)
223 add_exec_opts(exec_parser)
224 add_parse_opts(exec_parser)
225
226 # The 'parse' option is special, as it doesn't need the kernel source
227 # (therefore there is no need for a build_dir, hence no add_common_opts)
228 # and the '--file' argument is not relevant to 'run', so isn't in
229 # add_parse_opts()
230 parse_parser = subparser.add_parser('parse',
231 help='Parses KUnit results from a file, '
232 'and parses formatted results.')
233 add_parse_opts(parse_parser)
234 parse_parser.add_argument('file',
235 help='Specifies the file to read results from.',
236 type=str, nargs='?', metavar='input_file')
237
238 cli_args = parser.parse_args(argv)
239
240 if cli_args.subcommand == 'run':
241 if not os.path.exists(cli_args.build_dir):
242 os.mkdir(cli_args.build_dir)
243
244 if not linux:
245 linux = kunit_kernel.LinuxSourceTree()
246
247 request = KunitRequest(cli_args.raw_output,
248 cli_args.timeout,
249 cli_args.jobs,
250 cli_args.build_dir,
251 cli_args.alltests,
252 cli_args.make_options)
253 result = run_tests(linux, request)
254 if result.status != KunitStatus.SUCCESS:
255 sys.exit(1)
256 elif cli_args.subcommand == 'config':
257 if cli_args.build_dir:
258 if not os.path.exists(cli_args.build_dir):
259 os.mkdir(cli_args.build_dir)
260
261 if not linux:
262 linux = kunit_kernel.LinuxSourceTree()
263
264 request = KunitConfigRequest(cli_args.build_dir,
265 cli_args.make_options)
266 result = config_tests(linux, request)
267 kunit_parser.print_with_timestamp((
268 'Elapsed time: %.3fs\n') % (
269 result.elapsed_time))
270 if result.status != KunitStatus.SUCCESS:
271 sys.exit(1)
272 elif cli_args.subcommand == 'build':
273 if cli_args.build_dir:
274 if not os.path.exists(cli_args.build_dir):
275 os.mkdir(cli_args.build_dir)
276
277 if not linux:
278 linux = kunit_kernel.LinuxSourceTree()
279
280 request = KunitBuildRequest(cli_args.jobs,
281 cli_args.build_dir,
282 cli_args.alltests,
283 cli_args.make_options)
284 result = build_tests(linux, request)
285 kunit_parser.print_with_timestamp((
286 'Elapsed time: %.3fs\n') % (
287 result.elapsed_time))
288 if result.status != KunitStatus.SUCCESS:
289 sys.exit(1)
290 elif cli_args.subcommand == 'exec':
291 if cli_args.build_dir:
292 if not os.path.exists(cli_args.build_dir):
293 os.mkdir(cli_args.build_dir)
294
295 if not linux:
296 linux = kunit_kernel.LinuxSourceTree()
297
298 exec_request = KunitExecRequest(cli_args.timeout,
299 cli_args.build_dir,
300 cli_args.alltests)
301 exec_result = exec_tests(linux, exec_request)
302 parse_request = KunitParseRequest(cli_args.raw_output,
303 exec_result.result)
304 result = parse_tests(parse_request)
305 kunit_parser.print_with_timestamp((
306 'Elapsed time: %.3fs\n') % (
307 exec_result.elapsed_time))
308 if result.status != KunitStatus.SUCCESS:
309 sys.exit(1)
310 elif cli_args.subcommand == 'parse':
311 if cli_args.file == None:
312 kunit_output = sys.stdin
313 else:
314 with open(cli_args.file, 'r') as f:
315 kunit_output = f.read().splitlines()
316 request = KunitParseRequest(cli_args.raw_output,
317 kunit_output)
318 result = parse_tests(request)
319 if result.status != KunitStatus.SUCCESS:
320 sys.exit(1)
321 else:
322 parser.print_help()
323
324if __name__ == '__main__':
325 main(sys.argv[1:])