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