-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathfuchsia-test-runner.py
executable file
·1280 lines (1103 loc) · 41.2 KB
/
fuchsia-test-runner.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
The Rust toolchain test runner for Fuchsia.
For instructions on running the compiler test suite, see
https://doc.rust-lang.org/stable/rustc/platform-support/fuchsia.html#aarch64-unknown-fuchsia-and-x86_64-unknown-fuchsia
"""
import argparse
import glob
import io
import json
import logging
import os
import platform
import shlex
import shutil
import subprocess
import sys
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import ClassVar, List, Optional
def check_call_with_logging(
args, *, stdout_handler, stderr_handler, check=True, text=True, **kwargs
):
stdout_handler(f"Subprocess: {shlex.join(str(arg) for arg in args)}")
with subprocess.Popen(
args,
text=text,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs,
) as process:
with ThreadPoolExecutor(max_workers=2) as executor:
def exhaust_pipe(handler, pipe):
for line in pipe:
handler(line.rstrip())
executor_out = executor.submit(exhaust_pipe, stdout_handler, process.stdout)
executor_err = executor.submit(exhaust_pipe, stderr_handler, process.stderr)
executor_out.result()
executor_err.result()
retcode = process.poll()
if check and retcode:
raise subprocess.CalledProcessError(retcode, process.args)
return subprocess.CompletedProcess(process.args, retcode)
def check_output_with_logging(
args, *, stdout_handler, stderr_handler, check=True, text=True, **kwargs
):
stdout_handler(f"Subprocess: {shlex.join(str(arg) for arg in args)}")
buf = io.StringIO()
with subprocess.Popen(
args,
text=text,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs,
) as process:
with ThreadPoolExecutor(max_workers=2) as executor:
def exhaust_stdout(handler, buf, pipe):
for line in pipe:
handler(line.rstrip())
buf.write(line)
buf.write("\n")
def exhaust_stderr(handler, pipe):
for line in pipe:
handler(line.rstrip())
executor_out = executor.submit(
exhaust_stdout, stdout_handler, buf, process.stdout
)
executor_err = executor.submit(
exhaust_stderr, stderr_handler, process.stderr
)
executor_out.result()
executor_err.result()
retcode = process.poll()
if check and retcode:
raise subprocess.CalledProcessError(retcode, process.args)
return buf.getvalue()
def atomic_link(link: Path, target: Path):
link_dir = link.parent
os.makedirs(link_dir, exist_ok=True)
link_file = link.name
tmp_file = link_dir.joinpath(link_file + "_tmp")
os.link(target, tmp_file)
try:
os.rename(tmp_file, link)
except Exception as e:
raise e
finally:
if tmp_file.exists():
os.remove(tmp_file)
@dataclass
class TestEnvironment:
rust_build_dir: Path
sdk_dir: Path
target: str
toolchain_dir: Path
local_pb_path: Optional[Path]
use_local_pb: bool
verbose: bool = False
env_logger = logging.getLogger("env")
subprocess_logger = logging.getLogger("env.subprocess")
__tmp_dir = None
@staticmethod
def tmp_dir() -> Path:
if TestEnvironment.__tmp_dir:
return TestEnvironment.__tmp_dir
tmp_dir = os.environ.get("TEST_TOOLCHAIN_TMP_DIR")
if tmp_dir is not None:
TestEnvironment.__tmp_dir = Path(tmp_dir).absolute()
else:
TestEnvironment.__tmp_dir = Path(__file__).parent.joinpath("tmp~")
return TestEnvironment.__tmp_dir
@staticmethod
def triple_to_arch(triple) -> str:
if "x86_64" in triple:
return "x64"
elif "aarch64" in triple:
return "arm64"
else:
raise Exception(f"Unrecognized target triple {triple}")
@classmethod
def env_file_path(cls) -> Path:
return cls.tmp_dir().joinpath("test_env.json")
@classmethod
def from_args(cls, args):
local_pb_path = args.local_product_bundle_path
if local_pb_path is not None:
local_pb_path = Path(local_pb_path).absolute()
return cls(
rust_build_dir=Path(args.rust_build).absolute(),
sdk_dir=Path(args.sdk).absolute(),
target=args.target,
toolchain_dir=Path(args.toolchain_dir).absolute(),
local_pb_path=local_pb_path,
use_local_pb=args.use_local_product_bundle_if_exists,
verbose=args.verbose,
)
@classmethod
def read_from_file(cls):
with open(cls.env_file_path(), encoding="utf-8") as f:
test_env = json.load(f)
local_pb_path = test_env["local_pb_path"]
if local_pb_path is not None:
local_pb_path = Path(local_pb_path)
return cls(
rust_build_dir=Path(test_env["rust_build_dir"]),
sdk_dir=Path(test_env["sdk_dir"]),
target=test_env["target"],
toolchain_dir=Path(test_env["toolchain_dir"]),
local_pb_path=local_pb_path,
use_local_pb=test_env["use_local_pb"],
verbose=test_env["verbose"],
)
def build_id(self, binary):
llvm_readelf = Path(self.toolchain_dir).joinpath("bin", "llvm-readelf")
process = subprocess.run(
args=[
llvm_readelf,
"-n",
"--elf-output-style=JSON",
binary,
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
if process.returncode:
e = f"llvm-readelf failed for binary {binary} with output {process.stdout}"
self.env_logger.error(e)
raise Exception(e)
try:
elf_output = json.loads(process.stdout)
except Exception as e:
e.add_note(f"Failed to read JSON from llvm-readelf for binary {binary}")
e.add_note(f"stdout: {process.stdout}")
raise
try:
note_sections = elf_output[0]["NoteSections"]
except Exception as e:
e.add_note(
f'Failed to read "NoteSections" from llvm-readelf for binary {binary}'
)
e.add_note(f"elf_output: {elf_output}")
raise
for entry in note_sections:
try:
note_section = entry["NoteSection"]
if note_section["Name"] == ".note.gnu.build-id":
return note_section["Notes"][0]["Build ID"]
except Exception as e:
e.add_note(
f'Failed to read ".note.gnu.build-id" from NoteSections \
entry in llvm-readelf for binary {binary}'
)
e.add_note(f"NoteSections: {note_sections}")
raise
raise Exception(f"Build ID not found for binary {binary}")
def generate_buildid_dir(
self,
binary: Path,
build_id_dir: Path,
build_id: str,
log_handler: logging.Logger,
):
os.makedirs(build_id_dir, exist_ok=True)
suffix = ".debug"
# Hardlink the original binary
build_id_prefix_dir = build_id_dir.joinpath(build_id[:2])
unstripped_binary = build_id_prefix_dir.joinpath(build_id[2:] + suffix)
build_id_prefix_dir.mkdir(parents=True, exist_ok=True)
atomic_link(unstripped_binary, binary)
assert unstripped_binary.exists()
stripped_binary = unstripped_binary.with_suffix("")
llvm_objcopy = Path(self.toolchain_dir).joinpath("bin", "llvm-objcopy")
strip_mode = "--strip-sections"
check_call_with_logging(
[
llvm_objcopy,
strip_mode,
unstripped_binary,
stripped_binary,
],
stdout_handler=log_handler.info,
stderr_handler=log_handler.error,
)
return stripped_binary
def write_to_file(self):
with open(self.env_file_path(), "w", encoding="utf-8") as f:
local_pb_path = self.local_pb_path
if local_pb_path is not None:
local_pb_path = str(local_pb_path)
json.dump(
{
"rust_build_dir": str(self.rust_build_dir),
"sdk_dir": str(self.sdk_dir),
"target": self.target,
"toolchain_dir": str(self.toolchain_dir),
"local_pb_path": local_pb_path,
"use_local_pb": self.use_local_pb,
"verbose": self.verbose,
},
f,
)
def setup_logging(self, log_to_file=False):
fs = logging.Formatter("%(asctime)s %(levelname)s:%(name)s:%(message)s")
if log_to_file:
logfile_handler = logging.FileHandler(self.tmp_dir().joinpath("log"))
logfile_handler.setLevel(logging.DEBUG)
logfile_handler.setFormatter(fs)
logging.getLogger().addHandler(logfile_handler)
logging.getLogger().setLevel(logging.DEBUG)
@property
def package_server_log_path(self) -> Path:
return self.tmp_dir().joinpath(f"repo_{self.TEST_REPO_NAME}.log")
@property
def emulator_log_path(self) -> Path:
return self.tmp_dir().joinpath("emulator_log")
@property
def packages_dir(self) -> Path:
return self.tmp_dir().joinpath("packages")
@property
def output_dir(self) -> Path:
return self.tmp_dir().joinpath("output")
def read_sdk_version(self):
meta_json_path = Path(self.sdk_dir).joinpath("meta", "manifest.json")
with open(meta_json_path, encoding="utf-8") as f:
meta_json = json.load(f)
return meta_json["id"]
TEST_REPO_NAME: ClassVar[str] = "rust-testing"
def repo_dir(self) -> Path:
return self.tmp_dir().joinpath(self.TEST_REPO_NAME)
def libs_dir(self) -> Path:
return self.rust_build_dir.joinpath(
"host",
"stage2",
"lib",
)
def rustlibs_dir(self) -> Path:
return self.libs_dir().joinpath(
"rustlib",
self.target,
"lib",
)
def sdk_arch(self):
machine = platform.machine()
if machine == "x86_64":
return "x64"
if machine == "arm":
return "a64"
raise Exception(f"Unrecognized host architecture {machine}")
def tool_path(self, tool) -> Path:
return Path(self.sdk_dir).joinpath("tools", self.sdk_arch(), tool)
def host_arch_triple(self):
machine = platform.machine()
if machine == "x86_64":
return "x86_64-unknown-linux-gnu"
if machine == "arm":
return "aarch64-unknown-linux-gnu"
raise Exception(f"Unrecognized host architecture {machine}")
def zxdb_script_path(self) -> Path:
return Path(self.tmp_dir(), "zxdb_script")
@property
def ffx_daemon_log_path(self):
return self.tmp_dir().joinpath("ffx_daemon_log")
@property
def ffx_isolate_dir(self):
return self.tmp_dir().joinpath("ffx_isolate")
@property
def home_dir(self):
return self.tmp_dir().joinpath("user-home")
def start_ffx_isolation(self):
# Most of this is translated directly from ffx's isolate library
os.mkdir(self.ffx_isolate_dir)
os.mkdir(self.home_dir)
ffx_path = self.tool_path("ffx")
ffx_env = self.ffx_cmd_env()
# Start ffx daemon
# We want this to be a long-running process that persists after the script finishes
# pylint: disable=consider-using-with
with open(
self.ffx_daemon_log_path, "w", encoding="utf-8"
) as ffx_daemon_log_file:
subprocess.Popen(
[
ffx_path,
"daemon",
"start",
],
env=ffx_env,
stdout=ffx_daemon_log_file,
stderr=ffx_daemon_log_file,
)
# Disable analytics
check_call_with_logging(
[
ffx_path,
"config",
"analytics",
"disable",
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
# Set configs
configs = {
"log.enabled": "true",
"log.dir": self.tmp_dir(),
"test.is_isolated": "true",
"test.experimental_structured_output": "true",
}
for key, value in configs.items():
check_call_with_logging(
[
ffx_path,
"config",
"set",
key,
value,
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
def ffx_cmd_env(self):
return {
"HOME": self.home_dir,
"FFX_ISOLATE_DIR": self.ffx_isolate_dir,
# We want to use our own specified temp directory
"TMP": self.tmp_dir(),
"TEMP": self.tmp_dir(),
"TMPDIR": self.tmp_dir(),
"TEMPDIR": self.tmp_dir(),
}
def stop_ffx_isolation(self):
check_call_with_logging(
[
self.tool_path("ffx"),
"daemon",
"stop",
],
env=self.ffx_cmd_env(),
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
def start(self):
"""Sets up the testing environment and prepares to run tests.
Args:
args: The command-line arguments to this command.
During setup, this function will:
- Locate necessary shared libraries
- Create a new temp directory (this is where all temporary files are stored)
- Start an emulator
- Start an update server
- Create a new package repo and register it with the emulator
- Write test environment settings to a temporary file
"""
# Initialize temp directory
os.makedirs(self.tmp_dir(), exist_ok=True)
if len(os.listdir(self.tmp_dir())) != 0:
raise Exception(f"Temp directory is not clean (in {self.tmp_dir()})")
self.setup_logging(log_to_file=True)
os.mkdir(self.output_dir)
ffx_path = self.tool_path("ffx")
ffx_env = self.ffx_cmd_env()
# Start ffx isolation
self.env_logger.info("Starting ffx isolation...")
self.start_ffx_isolation()
# Stop any running emulators (there shouldn't be any)
check_call_with_logging(
[
ffx_path,
"emu",
"stop",
"--all",
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
if not self.local_pb_path:
self.local_pb_path = os.path.join(self.tmp_dir(), "local_pb")
else:
self.local_pb_path = os.path.abspath(self.local_pb_path)
if self.use_local_pb and os.path.exists(self.local_pb_path):
self.env_logger.info(
'Using existing emulator image at "%s"' % self.local_pb_path
)
else:
shutil.rmtree(self.local_pb_path, ignore_errors=True)
# Look up the product bundle transfer manifest.
self.env_logger.info("Looking up the product bundle transfer manifest...")
product_name = "minimal." + self.triple_to_arch(self.target)
sdk_version = self.read_sdk_version()
output = check_output_with_logging(
[
ffx_path,
"--machine",
"json",
"product",
"lookup",
product_name,
sdk_version,
"--base-url",
"gs://fuchsia/development/" + sdk_version,
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
try:
transfer_manifest_url = json.loads(output)["transfer_manifest_url"]
except Exception as e:
print(e)
raise Exception("Unable to parse transfer manifest") from e
# Download the product bundle.
self.env_logger.info("Downloading the product bundle...")
check_call_with_logging(
[
ffx_path,
"product",
"download",
transfer_manifest_url,
self.local_pb_path,
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
# Start emulator
self.env_logger.info("Starting emulator...")
# FIXME: condition --accel hyper on target arch matching host arch
check_call_with_logging(
[
ffx_path,
"emu",
"start",
self.local_pb_path,
"--headless",
"--log",
self.emulator_log_path,
"--net",
"auto",
"--accel",
"auto",
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
# Create new package repo
self.env_logger.info("Creating package repo...")
check_call_with_logging(
[
ffx_path,
"repository",
"create",
self.repo_dir(),
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
check_call_with_logging(
[
ffx_path,
"repository",
"server",
"start",
"--background",
"--address",
"[::]:0",
"--repo-path",
self.repo_dir(),
"--repository",
self.TEST_REPO_NAME,
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
# Register with newly-started emulator
check_call_with_logging(
[
ffx_path,
"target",
"repository",
"register",
"--repository",
self.TEST_REPO_NAME,
],
env=ffx_env,
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
# Write to file
self.write_to_file()
self.env_logger.info("Success! Your environment is ready to run tests.")
# FIXME: shardify this
# `facet` statement required for TCP testing via
# protocol `fuchsia.posix.socket.Provider`. See
# https://fuchsia.dev/fuchsia-src/development/testing/components/test_runner_framework?hl=en#legacy_non-hermetic_tests
CML_TEMPLATE: ClassVar[str] = """
{{
program: {{
runner: "elf_test_runner",
binary: "bin/{exe_name}",
forward_stderr_to: "log",
forward_stdout_to: "log",
environ: [{env_vars}
]
}},
capabilities: [
{{ protocol: "fuchsia.test.Suite" }},
],
expose: [
{{
protocol: "fuchsia.test.Suite",
from: "self",
}},
],
use: [
{{ storage: "data", path: "/data" }},
{{ storage: "tmp", path: "/tmp" }},
{{ protocol: [ "fuchsia.process.Launcher" ] }},
{{ protocol: [ "fuchsia.posix.socket.Provider" ] }}
],
facets: {{
"fuchsia.test": {{ type: "system" }},
}},
}}
"""
MANIFEST_TEMPLATE = """
meta/package={package_dir}/meta/package
meta/{package_name}.cm={package_dir}/meta/{package_name}.cm
bin/{exe_name}={bin_path}
lib/{libstd_name}={libstd_path}
lib/ld.so.1={sdk_dir}/arch/{target_arch}/sysroot/dist/lib/ld.so.1
lib/libfdio.so={sdk_dir}/arch/{target_arch}/dist/libfdio.so
"""
TEST_ENV_VARS: ClassVar[List[str]] = [
"TEST_EXEC_ENV",
"RUST_MIN_STACK",
"RUST_BACKTRACE",
"RUST_NEWRT",
"RUST_LOG",
"RUST_TEST_THREADS",
]
def run(self, args):
"""Runs the requested test in the testing environment.
Args:
args: The command-line arguments to this command.
Returns:
The return code of the test (0 for success, else failure).
To run a test, this function will:
- Create, compile, archive, and publish a test package
- Run the test package on the emulator
- Forward the test's stdout and stderr as this script's stdout and stderr
"""
bin_path = Path(args.bin_path).absolute()
# Find libstd and libtest
libstd_paths = glob.glob(os.path.join(self.rustlibs_dir(), "libstd-*.so"))
libtest_paths = glob.glob(os.path.join(self.rustlibs_dir(), "libtest-*.so"))
if not libstd_paths:
raise Exception(f"Failed to locate libstd (in {self.rustlibs_dir()})")
base_name = os.path.basename(os.path.dirname(args.bin_path))
exe_name = base_name.lower().replace(".", "_")
build_id = self.build_id(bin_path)
package_name = f"{exe_name}_{build_id}"
package_dir = self.packages_dir.joinpath(package_name)
package_dir.mkdir(parents=True, exist_ok=True)
meta_dir = package_dir.joinpath("meta")
meta_dir.mkdir(parents=True, exist_ok=True)
meta_package_path = meta_dir.joinpath("package")
cml_path = meta_dir.joinpath(f"{package_name}.cml")
cm_path = meta_dir.joinpath(f"{package_name}.cm")
manifest_path = package_dir.joinpath(f"{package_name}.manifest")
shared_libs = args.shared_libs[: args.n]
arguments = args.shared_libs[args.n :]
test_output_dir = self.output_dir.joinpath(package_name)
# Clean and create temporary output directory
if test_output_dir.exists():
shutil.rmtree(test_output_dir)
test_output_dir.mkdir(parents=True)
# Open log file
runner_logger = logging.getLogger(f"env.package.{package_name}")
runner_logger.setLevel(logging.DEBUG)
logfile_handler = logging.FileHandler(test_output_dir.joinpath("log"))
logfile_handler.setLevel(logging.DEBUG)
logfile_handler.setFormatter(
logging.Formatter("%(levelname)s:%(name)s:%(message)s")
)
runner_logger.addHandler(logfile_handler)
runner_logger.info(f"Bin path: {bin_path}")
runner_logger.info("Setting up package...")
# Link binary to build-id dir and strip it.
build_id_dir = self.tmp_dir().joinpath(".build-id")
stripped_binary = self.generate_buildid_dir(
binary=bin_path,
build_id_dir=build_id_dir,
build_id=build_id,
log_handler=runner_logger,
)
runner_logger.info(f"Stripped Bin path: {stripped_binary}")
runner_logger.info("Writing CML...")
# Write and compile CML
with open(cml_path, "w", encoding="utf-8") as cml:
# Collect environment variables
env_vars = ""
for var_name in self.TEST_ENV_VARS:
var_value = os.getenv(var_name)
if var_value is not None:
env_vars += f'\n "{var_name}={var_value}",'
# Default to no backtrace for test suite
if os.getenv("RUST_BACKTRACE") is None:
env_vars += '\n "RUST_BACKTRACE=0",'
# Use /tmp as the test temporary directory
env_vars += '\n "RUST_TEST_TMPDIR=/tmp",'
cml.write(self.CML_TEMPLATE.format(env_vars=env_vars, exe_name=exe_name))
runner_logger.info("Compiling CML...")
check_call_with_logging(
[
self.tool_path("cmc"),
"compile",
cml_path,
"--includepath",
".",
"--output",
cm_path,
],
stdout_handler=runner_logger.info,
stderr_handler=runner_logger.warning,
)
runner_logger.info("Writing meta/package...")
with open(meta_package_path, "w", encoding="utf-8") as f:
json.dump({"name": package_name, "version": "0"}, f)
runner_logger.info("Writing manifest...")
# Write package manifest
with open(manifest_path, "w", encoding="utf-8") as manifest:
manifest.write(
self.MANIFEST_TEMPLATE.format(
bin_path=stripped_binary,
exe_name=exe_name,
package_dir=package_dir,
package_name=package_name,
target=self.target,
sdk_dir=self.sdk_dir,
libstd_name=os.path.basename(libstd_paths[0]),
libstd_path=libstd_paths[0],
target_arch=self.triple_to_arch(self.target),
)
)
# `libtest`` was historically a shared library, but now seems to be (sometimes?)
# statically linked. If we find it as a shared library, include it in the manifest.
if libtest_paths:
manifest.write(
f"lib/{os.path.basename(libtest_paths[0])}={libtest_paths[0]}\n"
)
for shared_lib in shared_libs:
manifest.write(f"lib/{os.path.basename(shared_lib)}={shared_lib}\n")
runner_logger.info("Determining API level...")
out = check_output_with_logging(
[
self.tool_path("ffx"),
"--machine",
"json",
"version",
],
env=self.ffx_cmd_env(),
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
api_level = json.loads(out)["tool_version"]["api_level"]
runner_logger.info("Compiling manifest...")
check_call_with_logging(
[
self.tool_path("ffx"),
"package",
"build",
manifest_path,
"-o",
package_dir,
"--api-level",
str(api_level),
],
env=self.ffx_cmd_env(),
stdout_handler=runner_logger.info,
stderr_handler=runner_logger.warning,
)
runner_logger.info("Publishing package to repo...")
# Publish package to repo
check_call_with_logging(
[
self.tool_path("ffx"),
"repository",
"publish",
"--package",
os.path.join(package_dir, "package_manifest.json"),
self.repo_dir(),
],
env=self.ffx_cmd_env(),
stdout_handler=runner_logger.info,
stderr_handler=runner_logger.warning,
)
runner_logger.info("Running ffx test...")
# Run test on emulator
check_call_with_logging(
[
self.tool_path("ffx"),
"test",
"run",
f"fuchsia-pkg://{self.TEST_REPO_NAME}/{package_name}#meta/{package_name}.cm",
"--min-severity-logs",
"TRACE",
"--output-directory",
test_output_dir,
"--",
]
+ arguments,
env=self.ffx_cmd_env(),
check=False,
stdout_handler=runner_logger.info,
stderr_handler=runner_logger.warning,
)
runner_logger.info("Reporting test suite output...")
# Read test suite output
run_summary_path = test_output_dir.joinpath("run_summary.json")
if not run_summary_path.exists():
runner_logger.error("Failed to open test run summary")
return 254
with open(run_summary_path, encoding="utf-8") as f:
run_summary = json.load(f)
suite = run_summary["data"]["suites"][0]
case = suite["cases"][0]
return_code = 0 if case["outcome"] == "PASSED" else 1
artifacts = case["artifacts"]
artifact_dir = case["artifact_dir"]
stdout_path = None
stderr_path = None
for path, artifact in artifacts.items():
artifact_path = os.path.join(test_output_dir, artifact_dir, path)
artifact_type = artifact["artifact_type"]
if artifact_type == "STDERR":
stderr_path = artifact_path
elif artifact_type == "STDOUT":
stdout_path = artifact_path
if stdout_path is not None:
if not os.path.exists(stdout_path):
runner_logger.error(f"stdout file {stdout_path} does not exist.")
else:
with open(stdout_path, encoding="utf-8", errors="ignore") as f:
sys.stdout.write(f.read())
if stderr_path is not None:
if not os.path.exists(stderr_path):
runner_logger.error(f"stderr file {stderr_path} does not exist.")
else:
with open(stderr_path, encoding="utf-8", errors="ignore") as f:
sys.stderr.write(f.read())
runner_logger.info("Done!")
return return_code
def stop(self):
"""Shuts down and cleans up the testing environment.
Args:
args: The command-line arguments to this command.
Returns:
The return code of the test (0 for success, else failure).
During cleanup, this function will stop the emulator, package server, and
update server, then delete all temporary files. If an error is encountered
while stopping any running processes, the temporary files will not be deleted.
Passing --cleanup will force the process to delete the files anyway.
"""
self.env_logger.debug("Reporting logs...")
# Print test log files
for test_dir in os.listdir(self.output_dir):
log_path = os.path.join(self.output_dir, test_dir, "log")
self.env_logger.debug(f"\n---- Logs for test '{test_dir}' ----\n")
if os.path.exists(log_path):
with open(log_path, encoding="utf-8", errors="ignore") as log:
self.env_logger.debug(log.read())
else:
self.env_logger.debug("No logs found")
# Print the emulator log
self.env_logger.debug("\n---- Emulator logs ----\n")
if os.path.exists(self.emulator_log_path):
with open(self.emulator_log_path, encoding="utf-8") as log:
self.env_logger.debug(log.read())
else:
self.env_logger.debug("No emulator logs found")
# Print the package server log
self.env_logger.debug("\n---- Package server log ----\n")
if os.path.exists(self.package_server_log_path):
with open(self.package_server_log_path, encoding="utf-8") as log:
self.env_logger.debug(log.read())
else:
self.env_logger.debug("No package server log found")
# Print the ffx daemon log
self.env_logger.debug("\n---- ffx daemon log ----\n")
if os.path.exists(self.ffx_daemon_log_path):
with open(self.ffx_daemon_log_path, encoding="utf-8") as log:
self.env_logger.debug(log.read())
else:
self.env_logger.debug("No ffx daemon log found")
# Shut down the emulator
self.env_logger.info("Stopping emulator...")
check_call_with_logging(
[
self.tool_path("ffx"),
"emu",
"stop",
],
env=self.ffx_cmd_env(),
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)
# Stop the package server
self.env_logger.info("Stopping package server...")
check_call_with_logging(
[
self.tool_path("ffx"),
"repository",
"server",
"stop",
self.TEST_REPO_NAME,
],
env=self.ffx_cmd_env(),
stdout_handler=self.subprocess_logger.debug,
stderr_handler=self.subprocess_logger.debug,
)