fork/rust
git clone https://git.julia.blue/fork/rust
3bcad65fbf6
master
1#!/usr/bin/env python3 2 3""" 4The Rust toolchain test runner for Fuchsia. 5 6For instructions on running the compiler test suite, see 7https://doc.rust-lang.org/stable/rustc/platform-support/fuchsia.html#aarch64-unknown-fuchsia-and-x86_64-unknown-fuchsia 8""" 9 10import argparse 11from dataclasses import dataclass 12import fcntl 13import glob 14import hashlib 15import json 16import os 17import platform 18import shutil 19import subprocess 20import sys 21from typing import ClassVar, List 22 23 24@dataclass 25class TestEnvironment: 26 rust_build_dir: str 27 sdk_dir: str 28 target: str 29 verbose: bool = False 30 31 @staticmethod 32 def tmp_dir(): 33 tmp_dir = os.environ.get("TEST_TOOLCHAIN_TMP_DIR") 34 if tmp_dir is not None: 35 return os.path.abspath(tmp_dir) 36 return os.path.join(os.path.dirname(__file__), "tmp~") 37 38 @staticmethod 39 def triple_to_arch(triple): 40 if "x86_64" in triple: 41 return "x64" 42 elif "aarch64" in triple: 43 return "arm64" 44 else: 45 raise Exception(f"Unrecognized target triple {triple}") 46 47 @classmethod 48 def env_file_path(cls): 49 return os.path.join(cls.tmp_dir(), "test_env.json") 50 51 @classmethod 52 def from_args(cls, args): 53 return cls( 54 os.path.abspath(args.rust_build), 55 os.path.abspath(args.sdk), 56 args.target, 57 verbose=args.verbose, 58 ) 59 60 @classmethod 61 def read_from_file(cls): 62 with open(cls.env_file_path(), encoding="utf-8") as f: 63 test_env = json.loads(f.read()) 64 return cls( 65 test_env["rust_build_dir"], 66 test_env["sdk_dir"], 67 test_env["target"], 68 verbose=test_env["verbose"], 69 ) 70 71 def write_to_file(self): 72 with open(self.env_file_path(), "w", encoding="utf-8") as f: 73 f.write(json.dumps(self.__dict__)) 74 75 def package_server_log_path(self): 76 return os.path.join(self.tmp_dir(), "package_server_log") 77 78 def emulator_log_path(self): 79 return os.path.join(self.tmp_dir(), "emulator_log") 80 81 def packages_dir(self): 82 return os.path.join(self.tmp_dir(), "packages") 83 84 def output_dir(self): 85 return os.path.join(self.tmp_dir(), "output") 86 87 TEST_REPO_NAME: ClassVar[str] = "rust-testing" 88 89 def repo_dir(self): 90 return os.path.join(self.tmp_dir(), self.TEST_REPO_NAME) 91 92 def libs_dir(self): 93 return os.path.join( 94 self.rust_build_dir, 95 "host", 96 "stage2", 97 "lib", 98 ) 99 100 def rustlibs_dir(self): 101 return os.path.join( 102 self.libs_dir(), 103 "rustlib", 104 self.target, 105 "lib", 106 ) 107 108 def sdk_arch(self): 109 machine = platform.machine() 110 if machine == "x86_64": 111 return "x64" 112 if machine == "arm": 113 return "a64" 114 raise Exception(f"Unrecognized host architecture {machine}") 115 116 def tool_path(self, tool): 117 return os.path.join(self.sdk_dir, "tools", self.sdk_arch(), tool) 118 119 def host_arch_triple(self): 120 machine = platform.machine() 121 if machine == "x86_64": 122 return "x86_64-unknown-linux-gnu" 123 if machine == "arm": 124 return "aarch64-unknown-linux-gnu" 125 raise Exception(f"Unrecognized host architecture {machine}") 126 127 def zxdb_script_path(self): 128 return os.path.join(self.tmp_dir(), "zxdb_script") 129 130 def pm_lockfile_path(self): 131 return os.path.join(self.tmp_dir(), "pm.lock") 132 133 def log_info(self, msg): 134 print(msg) 135 136 def log_debug(self, msg): 137 if self.verbose: 138 print(msg) 139 140 def subprocess_output(self): 141 if self.verbose: 142 return sys.stdout 143 return subprocess.DEVNULL 144 145 def ffx_daemon_log_path(self): 146 return os.path.join(self.tmp_dir(), "ffx_daemon_log") 147 148 def ffx_isolate_dir(self): 149 return os.path.join(self.tmp_dir(), "ffx_isolate") 150 151 def home_dir(self): 152 return os.path.join(self.tmp_dir(), "user-home") 153 154 def start_ffx_isolation(self): 155 # Most of this is translated directly from ffx's isolate library 156 os.mkdir(self.ffx_isolate_dir()) 157 os.mkdir(self.home_dir()) 158 159 ffx_path = self.tool_path("ffx") 160 ffx_env = self.ffx_cmd_env() 161 162 # Start ffx daemon 163 # We want this to be a long-running process that persists after the script finishes 164 # pylint: disable=consider-using-with 165 with open( 166 self.ffx_daemon_log_path(), "w", encoding="utf-8" 167 ) as ffx_daemon_log_file: 168 subprocess.Popen( 169 [ 170 ffx_path, 171 "daemon", 172 "start", 173 ], 174 env=ffx_env, 175 stdout=ffx_daemon_log_file, 176 stderr=ffx_daemon_log_file, 177 ) 178 179 # Disable analytics 180 subprocess.check_call( 181 [ 182 ffx_path, 183 "config", 184 "analytics", 185 "disable", 186 ], 187 env=ffx_env, 188 stdout=self.subprocess_output(), 189 stderr=self.subprocess_output(), 190 ) 191 192 # Set configs 193 configs = { 194 "log.enabled": "true", 195 "test.is_isolated": "true", 196 "test.experimental_structured_output": "true", 197 } 198 for key, value in configs.items(): 199 subprocess.check_call( 200 [ 201 ffx_path, 202 "config", 203 "set", 204 key, 205 value, 206 ], 207 env=ffx_env, 208 stdout=self.subprocess_output(), 209 stderr=self.subprocess_output(), 210 ) 211 212 def ffx_cmd_env(self): 213 return { 214 "HOME": self.home_dir(), 215 "FFX_ISOLATE_DIR": self.ffx_isolate_dir(), 216 # We want to use our own specified temp directory 217 "TMP": self.tmp_dir(), 218 "TEMP": self.tmp_dir(), 219 "TMPDIR": self.tmp_dir(), 220 "TEMPDIR": self.tmp_dir(), 221 } 222 223 def stop_ffx_isolation(self): 224 subprocess.check_call( 225 [ 226 self.tool_path("ffx"), 227 "daemon", 228 "stop", 229 "-w", 230 ], 231 env=self.ffx_cmd_env(), 232 stdout=self.subprocess_output(), 233 stderr=self.subprocess_output(), 234 ) 235 236 def start(self): 237 """Sets up the testing environment and prepares to run tests. 238 239 Args: 240 args: The command-line arguments to this command. 241 242 During setup, this function will: 243 - Locate necessary shared libraries 244 - Create a new temp directory (this is where all temporary files are stored) 245 - Start an emulator 246 - Start an update server 247 - Create a new package repo and register it with the emulator 248 - Write test environment settings to a temporary file 249 """ 250 251 # Initialize temp directory 252 if not os.path.exists(self.tmp_dir()): 253 os.mkdir(self.tmp_dir()) 254 elif len(os.listdir(self.tmp_dir())) != 0: 255 raise Exception(f"Temp directory is not clean (in {self.tmp_dir()})") 256 257 os.mkdir(self.output_dir()) 258 259 ffx_path = self.tool_path("ffx") 260 ffx_env = self.ffx_cmd_env() 261 262 # Start ffx isolation 263 self.log_info("Starting ffx isolation...") 264 self.start_ffx_isolation() 265 266 # Stop any running emulators (there shouldn't be any) 267 subprocess.check_call( 268 [ 269 ffx_path, 270 "emu", 271 "stop", 272 "--all", 273 ], 274 env=ffx_env, 275 stdout=self.subprocess_output(), 276 stderr=self.subprocess_output(), 277 ) 278 279 # Start emulator 280 self.log_info("Starting emulator...") 281 product_bundle = "terminal.qemu-" + self.triple_to_arch(self.target) 282 subprocess.check_call( 283 [ 284 ffx_path, 285 "product-bundle", 286 "get", 287 product_bundle, 288 ], 289 env=ffx_env, 290 stdout=self.subprocess_output(), 291 stderr=self.subprocess_output(), 292 ) 293 # FIXME: condition --accel hyper on target arch matching host arch 294 subprocess.check_call( 295 [ 296 ffx_path, 297 "emu", 298 "start", 299 product_bundle, 300 "--headless", 301 "--log", 302 self.emulator_log_path(), 303 "--net", 304 "tap", 305 "--accel", 306 "hyper", 307 ], 308 env=ffx_env, 309 stdout=self.subprocess_output(), 310 stderr=self.subprocess_output(), 311 ) 312 313 # Create new package repo 314 self.log_info("Creating package repo...") 315 subprocess.check_call( 316 [ 317 self.tool_path("pm"), 318 "newrepo", 319 "-repo", 320 self.repo_dir(), 321 ], 322 stdout=self.subprocess_output(), 323 stderr=self.subprocess_output(), 324 ) 325 326 # Add repo 327 subprocess.check_call( 328 [ 329 ffx_path, 330 "repository", 331 "add-from-pm", 332 self.repo_dir(), 333 "--repository", 334 self.TEST_REPO_NAME, 335 ], 336 env=ffx_env, 337 stdout=self.subprocess_output(), 338 stderr=self.subprocess_output(), 339 ) 340 341 # Start repository server 342 subprocess.check_call( 343 [ffx_path, "repository", "server", "start", "--address", "[::]:0"], 344 env=ffx_env, 345 stdout=self.subprocess_output(), 346 stderr=self.subprocess_output(), 347 ) 348 349 # Register with newly-started emulator 350 subprocess.check_call( 351 [ 352 ffx_path, 353 "target", 354 "repository", 355 "register", 356 "--repository", 357 self.TEST_REPO_NAME, 358 ], 359 env=ffx_env, 360 stdout=self.subprocess_output(), 361 stderr=self.subprocess_output(), 362 ) 363 364 # Create lockfiles 365 open(self.pm_lockfile_path(), "a").close() 366 367 # Write to file 368 self.write_to_file() 369 370 self.log_info("Success! Your environment is ready to run tests.") 371 372 # FIXME: shardify this 373 # `facet` statement required for TCP testing via 374 # protocol `fuchsia.posix.socket.Provider`. See 375 # https://fuchsia.dev/fuchsia-src/development/testing/components/test_runner_framework?hl=en#legacy_non-hermetic_tests 376 CML_TEMPLATE: ClassVar[ 377 str 378 ] = """ 379 {{ 380 program: {{ 381 runner: "elf_test_runner", 382 binary: "bin/{exe_name}", 383 forward_stderr_to: "log", 384 forward_stdout_to: "log", 385 environ: [{env_vars} 386 ] 387 }}, 388 capabilities: [ 389 {{ protocol: "fuchsia.test.Suite" }}, 390 ], 391 expose: [ 392 {{ 393 protocol: "fuchsia.test.Suite", 394 from: "self", 395 }}, 396 ], 397 use: [ 398 {{ storage: "data", path: "/data" }}, 399 {{ storage: "tmp", path: "/tmp" }}, 400 {{ protocol: [ "fuchsia.process.Launcher" ] }}, 401 {{ protocol: [ "fuchsia.posix.socket.Provider" ] }} 402 ], 403 facets: {{ 404 "fuchsia.test": {{ type: "system" }}, 405 }}, 406 }} 407 """ 408 409 MANIFEST_TEMPLATE = """ 410 meta/package={package_dir}/meta/package 411 meta/{package_name}.cm={package_dir}/meta/{package_name}.cm 412 bin/{exe_name}={bin_path} 413 lib/{libstd_name}={libstd_path} 414 lib/{libtest_name}={libtest_path} 415 lib/ld.so.1={sdk_dir}/arch/{target_arch}/sysroot/dist/lib/ld.so.1 416 lib/libfdio.so={sdk_dir}/arch/{target_arch}/dist/libfdio.so 417 """ 418 419 TEST_ENV_VARS: ClassVar[List[str]] = [ 420 "TEST_EXEC_ENV", 421 "RUST_MIN_STACK", 422 "RUST_BACKTRACE", 423 "RUST_NEWRT", 424 "RUST_LOG", 425 "RUST_TEST_THREADS", 426 ] 427 428 def run(self, args): 429 """Runs the requested test in the testing environment. 430 431 Args: 432 args: The command-line arguments to this command. 433 Returns: 434 The return code of the test (0 for success, else failure). 435 436 To run a test, this function will: 437 - Create, compile, archive, and publish a test package 438 - Run the test package on the emulator 439 - Forward the test's stdout and stderr as this script's stdout and stderr 440 """ 441 442 bin_path = os.path.abspath(args.bin_path) 443 444 # Find libstd and libtest 445 libstd_paths = glob.glob(os.path.join(self.rustlibs_dir(), "libstd-*.so")) 446 libtest_paths = glob.glob(os.path.join(self.rustlibs_dir(), "libtest-*.so")) 447 448 if not libstd_paths: 449 raise Exception(f"Failed to locate libstd (in {self.rustlibs_dir()})") 450 451 if not libtest_paths: 452 raise Exception(f"Failed to locate libtest (in {self.rustlibs_dir()})") 453 454 # Build a unique, deterministic name for the test using the name of the 455 # binary and the last 6 hex digits of the hash of the full path 456 def path_checksum(path): 457 m = hashlib.sha256() 458 m.update(path.encode("utf-8")) 459 return m.hexdigest()[0:6] 460 461 base_name = os.path.basename(os.path.dirname(args.bin_path)) 462 exe_name = base_name.lower().replace(".", "_") 463 package_name = f"{exe_name}_{path_checksum(bin_path)}" 464 465 package_dir = os.path.join(self.packages_dir(), package_name) 466 cml_path = os.path.join(package_dir, "meta", f"{package_name}.cml") 467 cm_path = os.path.join(package_dir, "meta", f"{package_name}.cm") 468 manifest_path = os.path.join(package_dir, f"{package_name}.manifest") 469 far_path = os.path.join(package_dir, f"{package_name}-0.far") 470 471 shared_libs = args.shared_libs[: args.n] 472 arguments = args.shared_libs[args.n :] 473 474 test_output_dir = os.path.join(self.output_dir(), package_name) 475 476 # Clean and create temporary output directory 477 if os.path.exists(test_output_dir): 478 shutil.rmtree(test_output_dir) 479 480 os.mkdir(test_output_dir) 481 482 # Open log file 483 log_path = os.path.join(test_output_dir, "log") 484 with open(log_path, "w", encoding="utf-8") as log_file: 485 486 def log(msg): 487 print(msg, file=log_file) 488 log_file.flush() 489 490 log(f"Bin path: {bin_path}") 491 492 log("Setting up package...") 493 494 # Set up package 495 subprocess.check_call( 496 [ 497 self.tool_path("pm"), 498 "-o", 499 package_dir, 500 "-n", 501 package_name, 502 "init", 503 ], 504 stdout=log_file, 505 stderr=log_file, 506 ) 507 508 log("Writing CML...") 509 510 # Write and compile CML 511 with open(cml_path, "w", encoding="utf-8") as cml: 512 # Collect environment variables 513 env_vars = "" 514 for var_name in self.TEST_ENV_VARS: 515 var_value = os.getenv(var_name) 516 if var_value is not None: 517 env_vars += f'\n "{var_name}={var_value}",' 518 519 # Default to no backtrace for test suite 520 if os.getenv("RUST_BACKTRACE") is None: 521 env_vars += '\n "RUST_BACKTRACE=0",' 522 523 # Use /tmp as the test temporary directory 524 env_vars += '\n "RUST_TEST_TMPDIR=/tmp",' 525 526 cml.write( 527 self.CML_TEMPLATE.format(env_vars=env_vars, exe_name=exe_name) 528 ) 529 530 log("Compiling CML...") 531 532 subprocess.check_call( 533 [ 534 self.tool_path("cmc"), 535 "compile", 536 cml_path, 537 "--includepath", 538 ".", 539 "--output", 540 cm_path, 541 ], 542 stdout=log_file, 543 stderr=log_file, 544 ) 545 546 log("Writing manifest...") 547 548 # Write, build, and archive manifest 549 with open(manifest_path, "w", encoding="utf-8") as manifest: 550 manifest.write( 551 self.MANIFEST_TEMPLATE.format( 552 bin_path=bin_path, 553 exe_name=exe_name, 554 package_dir=package_dir, 555 package_name=package_name, 556 target=self.target, 557 sdk_dir=self.sdk_dir, 558 libstd_name=os.path.basename(libstd_paths[0]), 559 libtest_name=os.path.basename(libtest_paths[0]), 560 libstd_path=libstd_paths[0], 561 libtest_path=libtest_paths[0], 562 target_arch=self.triple_to_arch(self.target), 563 ) 564 ) 565 for shared_lib in shared_libs: 566 manifest.write(f"lib/{os.path.basename(shared_lib)}={shared_lib}\n") 567 568 log("Compiling and archiving manifest...") 569 570 subprocess.check_call( 571 [ 572 self.tool_path("pm"), 573 "-o", 574 package_dir, 575 "-m", 576 manifest_path, 577 "build", 578 ], 579 stdout=log_file, 580 stderr=log_file, 581 ) 582 subprocess.check_call( 583 [ 584 self.tool_path("pm"), 585 "-o", 586 package_dir, 587 "-m", 588 manifest_path, 589 "archive", 590 ], 591 stdout=log_file, 592 stderr=log_file, 593 ) 594 595 log("Publishing package to repo...") 596 597 # Publish package to repo 598 with open(self.pm_lockfile_path(), "w") as pm_lockfile: 599 fcntl.lockf(pm_lockfile.fileno(), fcntl.LOCK_EX) 600 subprocess.check_call( 601 [ 602 self.tool_path("pm"), 603 "publish", 604 "-a", 605 "-repo", 606 self.repo_dir(), 607 "-f", 608 far_path, 609 ], 610 stdout=log_file, 611 stderr=log_file, 612 ) 613 # This lock should be released automatically when the pm 614 # lockfile is closed, but we'll be polite and unlock it now 615 # since the spec leaves some wiggle room. 616 fcntl.lockf(pm_lockfile.fileno(), fcntl.LOCK_UN) 617 618 log("Running ffx test...") 619 620 # Run test on emulator 621 subprocess.run( 622 [ 623 self.tool_path("ffx"), 624 "test", 625 "run", 626 f"fuchsia-pkg://{self.TEST_REPO_NAME}/{package_name}#meta/{package_name}.cm", 627 "--min-severity-logs", 628 "TRACE", 629 "--output-directory", 630 test_output_dir, 631 "--", 632 ] 633 + arguments, 634 env=self.ffx_cmd_env(), 635 check=False, 636 stdout=log_file, 637 stderr=log_file, 638 ) 639 640 log("Reporting test suite output...") 641 642 # Read test suite output 643 run_summary_path = os.path.join(test_output_dir, "run_summary.json") 644 if os.path.exists(run_summary_path): 645 with open(run_summary_path, encoding="utf-8") as f: 646 run_summary = json.loads(f.read()) 647 648 suite = run_summary["data"]["suites"][0] 649 case = suite["cases"][0] 650 651 return_code = 0 if case["outcome"] == "PASSED" else 1 652 653 artifacts = case["artifacts"] 654 artifact_dir = case["artifact_dir"] 655 stdout_path = None 656 stderr_path = None 657 658 for path, artifact in artifacts.items(): 659 artifact_path = os.path.join(test_output_dir, artifact_dir, path) 660 artifact_type = artifact["artifact_type"] 661 662 if artifact_type == "STDERR": 663 stderr_path = artifact_path 664 elif artifact_type == "STDOUT": 665 stdout_path = artifact_path 666 667 if stdout_path is not None and os.path.exists(stdout_path): 668 with open(stdout_path, encoding="utf-8") as f: 669 print(f.read(), file=sys.stdout, end="") 670 671 if stderr_path is not None and os.path.exists(stderr_path): 672 with open(stderr_path, encoding="utf-8") as f: 673 print(f.read(), file=sys.stderr, end="") 674 else: 675 log("Failed to open test run summary") 676 return_code = 254 677 678 log("Done!") 679 680 return return_code 681 682 def stop(self): 683 """Shuts down and cleans up the testing environment. 684 685 Args: 686 args: The command-line arguments to this command. 687 Returns: 688 The return code of the test (0 for success, else failure). 689 690 During cleanup, this function will stop the emulator, package server, and 691 update server, then delete all temporary files. If an error is encountered 692 while stopping any running processes, the temporary files will not be deleted. 693 Passing --delete-tmp will force the process to delete the files anyway. 694 """ 695 696 self.log_debug("Reporting logs...") 697 698 # Print test log files 699 for test_dir in os.listdir(self.output_dir()): 700 log_path = os.path.join(self.output_dir(), test_dir, "log") 701 self.log_debug(f"\n---- Logs for test '{test_dir}' ----\n") 702 if os.path.exists(log_path): 703 with open(log_path, encoding="utf-8") as log: 704 self.log_debug(log.read()) 705 else: 706 self.log_debug("No logs found") 707 708 # Print the emulator log 709 self.log_debug("\n---- Emulator logs ----\n") 710 if os.path.exists(self.emulator_log_path()): 711 with open(self.emulator_log_path(), encoding="utf-8") as log: 712 self.log_debug(log.read()) 713 else: 714 self.log_debug("No emulator logs found") 715 716 # Print the package server log 717 self.log_debug("\n---- Package server log ----\n") 718 if os.path.exists(self.package_server_log_path()): 719 with open(self.package_server_log_path(), encoding="utf-8") as log: 720 self.log_debug(log.read()) 721 else: 722 self.log_debug("No package server log found") 723 724 # Print the ffx daemon log 725 self.log_debug("\n---- ffx daemon log ----\n") 726 if os.path.exists(self.ffx_daemon_log_path()): 727 with open(self.ffx_daemon_log_path(), encoding="utf-8") as log: 728 self.log_debug(log.read()) 729 else: 730 self.log_debug("No ffx daemon log found") 731 732 # Shut down the emulator 733 self.log_info("Stopping emulator...") 734 subprocess.check_call( 735 [ 736 self.tool_path("ffx"), 737 "emu", 738 "stop", 739 ], 740 env=self.ffx_cmd_env(), 741 stdout=self.subprocess_output(), 742 stderr=self.subprocess_output(), 743 ) 744 745 # Stop ffx isolation 746 self.log_info("Stopping ffx isolation...") 747 self.stop_ffx_isolation() 748 749 def delete_tmp(self): 750 # Remove temporary files 751 self.log_info("Deleting temporary files...") 752 shutil.rmtree(self.tmp_dir(), ignore_errors=True) 753 754 def debug(self, args): 755 command = [ 756 self.tool_path("ffx"), 757 "debug", 758 "connect", 759 "--", 760 "--build-id-dir", 761 os.path.join(self.sdk_dir, ".build-id"), 762 ] 763 764 libs_build_id_path = os.path.join(self.libs_dir(), ".build-id") 765 if os.path.exists(libs_build_id_path): 766 # Add .build-id symbols if installed libs have been stripped into a 767 # .build-id directory 768 command += [ 769 "--build-id-dir", 770 libs_build_id_path, 771 ] 772 else: 773 # If no .build-id directory is detected, then assume that the shared 774 # libs contain their debug symbols 775 command += [ 776 f"--symbol-path={self.rust_dir}/lib/rustlib/{self.target}/lib", 777 ] 778 779 # Add rust source if it's available 780 rust_src_map = None 781 if args.rust_src is not None: 782 # This matches the remapped prefix used by compiletest. There's no 783 # clear way that we can determine this, so it's hard coded. 784 rust_src_map = f"/rustc/FAKE_PREFIX={args.rust_src}" 785 786 # Add fuchsia source if it's available 787 fuchsia_src_map = None 788 if args.fuchsia_src is not None: 789 fuchsia_src_map = f"./../..={args.fuchsia_src}" 790 791 # Load debug symbols for the test binary and automatically attach 792 if args.test is not None: 793 if args.rust_src is None: 794 raise Exception( 795 "A Rust source path is required with the `test` argument" 796 ) 797 798 test_name = os.path.splitext(os.path.basename(args.test))[0] 799 800 build_dir = os.path.join( 801 args.rust_src, 802 "fuchsia-build", 803 self.host_arch_triple(), 804 ) 805 test_dir = os.path.join( 806 build_dir, 807 "test", 808 os.path.dirname(args.test), 809 test_name, 810 ) 811 812 # The fake-test-src-base directory maps to the suite directory 813 # e.g. tests/ui/foo.rs has a path of rust/fake-test-src-base/foo.rs 814 fake_test_src_base = os.path.join( 815 args.rust_src, 816 "fake-test-src-base", 817 ) 818 real_test_src_base = os.path.join( 819 args.rust_src, 820 "tests", 821 args.test.split(os.path.sep)[0], 822 ) 823 test_src_map = f"{fake_test_src_base}={real_test_src_base}" 824 825 with open(self.zxdb_script_path(), mode="w", encoding="utf-8") as f: 826 print(f"set source-map += {test_src_map}", file=f) 827 828 if rust_src_map is not None: 829 print(f"set source-map += {rust_src_map}", file=f) 830 831 if fuchsia_src_map is not None: 832 print(f"set source-map += {fuchsia_src_map}", file=f) 833 834 print(f"attach {test_name[:31]}", file=f) 835 836 command += [ 837 "--symbol-path", 838 test_dir, 839 "-S", 840 self.zxdb_script_path(), 841 ] 842 843 # Add any other zxdb arguments the user passed 844 if args.zxdb_args is not None: 845 command += args.zxdb_args 846 847 # Connect to the running emulator with zxdb 848 subprocess.run(command, env=self.ffx_cmd_env(), check=False) 849 850 def syslog(self, args): 851 subprocess.run( 852 [ 853 self.tool_path("ffx"), 854 "log", 855 "--since", 856 "now", 857 ], 858 env=self.ffx_cmd_env(), 859 check=False, 860 ) 861 862 863def start(args): 864 test_env = TestEnvironment.from_args(args) 865 test_env.start() 866 return 0 867 868 869def run(args): 870 test_env = TestEnvironment.read_from_file() 871 return test_env.run(args) 872 873 874def stop(args): 875 test_env = TestEnvironment.read_from_file() 876 test_env.stop() 877 if not args.no_delete: 878 test_env.delete_tmp() 879 return 0 880 881 882def delete_tmp(args): 883 del args 884 test_env = TestEnvironment.read_from_file() 885 test_env.delete_tmp() 886 return 0 887 888 889def debug(args): 890 test_env = TestEnvironment.read_from_file() 891 test_env.debug(args) 892 return 0 893 894 895def syslog(args): 896 test_env = TestEnvironment.read_from_file() 897 test_env.syslog(args) 898 return 0 899 900 901def main(): 902 parser = argparse.ArgumentParser() 903 904 def print_help(args): 905 del args 906 parser.print_help() 907 return 0 908 909 parser.set_defaults(func=print_help) 910 911 subparsers = parser.add_subparsers(help="valid sub-commands") 912 913 start_parser = subparsers.add_parser( 914 "start", help="initializes the testing environment" 915 ) 916 start_parser.add_argument( 917 "--rust-build", 918 help="the current compiler build directory (`$RUST_SRC/build` by default)", 919 required=True, 920 ) 921 start_parser.add_argument( 922 "--sdk", 923 help="the directory of the fuchsia SDK", 924 required=True, 925 ) 926 start_parser.add_argument( 927 "--verbose", 928 help="prints more output from executed processes", 929 action="store_true", 930 ) 931 start_parser.add_argument( 932 "--target", 933 help="the target platform to test", 934 required=True, 935 ) 936 start_parser.set_defaults(func=start) 937 938 run_parser = subparsers.add_parser( 939 "run", help="run a test in the testing environment" 940 ) 941 run_parser.add_argument( 942 "n", help="the number of shared libs passed along with the executable", type=int 943 ) 944 run_parser.add_argument("bin_path", help="path to the binary to run") 945 run_parser.add_argument( 946 "shared_libs", 947 help="the shared libs passed along with the binary", 948 nargs=argparse.REMAINDER, 949 ) 950 run_parser.set_defaults(func=run) 951 952 stop_parser = subparsers.add_parser( 953 "stop", help="shuts down and cleans up the testing environment" 954 ) 955 stop_parser.add_argument( 956 "--no-delete", 957 default=False, 958 action="store_true", 959 help="don't delete temporary files after stopping", 960 ) 961 stop_parser.set_defaults(func=stop) 962 963 delete_parser = subparsers.add_parser( 964 "delete-tmp", 965 help="deletes temporary files after the testing environment has been manually cleaned up", 966 ) 967 delete_parser.set_defaults(func=delete_tmp) 968 969 debug_parser = subparsers.add_parser( 970 "debug", 971 help="connect to the active testing environment with zxdb", 972 ) 973 debug_parser.add_argument( 974 "--rust-src", 975 default=None, 976 help="the path to the Rust source being tested", 977 ) 978 debug_parser.add_argument( 979 "--fuchsia-src", 980 default=None, 981 help="the path to the Fuchsia source", 982 ) 983 debug_parser.add_argument( 984 "--test", 985 default=None, 986 help="the path to the test to debug (e.g. ui/box/new.rs)", 987 ) 988 debug_parser.add_argument( 989 "zxdb_args", 990 default=None, 991 nargs=argparse.REMAINDER, 992 help="any additional arguments to pass to zxdb", 993 ) 994 debug_parser.set_defaults(func=debug) 995 996 syslog_parser = subparsers.add_parser("syslog", help="prints the device syslog") 997 syslog_parser.set_defaults(func=syslog) 998 999 args = parser.parse_args() 1000 return args.func(args) 1001 1002 1003if __name__ == "__main__": 1004 sys.exit(main())