blob: 97169125a604655e05e1d30cc0010c76bd45f56d [file]
#!/usr/bin/env fuchsia-vendored-python
# Copyright 2026 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Host runner for recording usbfs golden traces in QEMU and generating scenarios.rs."""
import argparse
import os
import sys
def _rust_raw_str(content: str) -> str:
hashes_count = 1
while f'"{("#" * hashes_count)}' in content:
hashes_count += 1
hashes = "#" * hashes_count
return f'r{hashes}"{content}"{hashes}'
def generate_rs(
output_path: str,
trace_dir: str | None,
divergences_path: str | None,
names: list[str],
) -> None:
divergences_content = '{"divergences": []}'
if divergences_path and os.path.exists(divergences_path):
with open(divergences_path, "r", encoding="utf-8") as df:
divergences_content = df.read().strip()
sorted_names = sorted(names)
traces: list[tuple[str, str]] = []
for name in sorted_names:
trace_content = ""
if trace_dir:
trace_path = os.path.join(trace_dir, f"{name}.json")
if os.path.exists(trace_path):
with open(trace_path, "r", encoding="utf-8") as tf:
trace_content = tf.read().strip()
if not trace_content:
raise ValueError(
f"Trace content for scenario '{name}' is empty or missing. "
f"Did you forget to run trace_generator.py? "
f"See src/starnix/modules/usbfs/testing/README.md for instructions."
)
traces.append((name, trace_content))
os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write("// Copyright 2026 The Fuchsia Authors. All rights reserved.\n")
f.write(
"// Use of this source code is governed by a BSD-style license that can be\n"
)
f.write("// found in the LICENSE file.\n\n")
f.write("// Generated by trace_generator.py. DO NOT EDIT.\n\n")
f.write(
f"pub const DIVERGENCES_JSON: &str = {_rust_raw_str(divergences_content)};\n\n"
)
f.write("pub const SCENARIOS: &[(&str, &str)] = &[\n")
for name, trace_content in traces:
f.write(f' ("{name}", {_rust_raw_str(trace_content)}),\n')
f.write("];\n\n")
f.write("#[macro_export]\n")
f.write(
"/// Generates test cases replaying golden traces.\n"
"///\n"
"/// Optional caller test attributes must be fully qualified (e.g. `#[serial_test::serial]`).\n"
)
f.write("macro_rules! usbfs_trace_tests {\n")
f.write(" ($replayer:path $(, $(#[$attr:meta])* )* $(,)?) => {\n")
if traces:
f.write(" #[cfg(test)]\n")
f.write(" mod generated_usbfs_trace_tests {\n")
f.write(" use super::*;\n")
f.write(" use ::test_case::test_case;\n\n")
for name, _ in traces:
f.write(f' #[test_case("{name}"; "{name}")]\n')
f.write(" $( $(#[$attr])* )*\n")
f.write(" fn test_replay_trace(name: &str) {\n")
f.write(
" let (_, json_data) = $crate::scenarios::SCENARIOS\n"
" .iter()\n"
" .find(|(n, _)| *n == name)\n"
' .expect("scenario trace exists");\n'
" $replayer(name, json_data);\n"
)
f.write(" }\n")
f.write(" }\n")
else:
f.write(" use ::test_case::test_case as _;\n")
f.write(" const _: fn(&str, &str) = $replayer;\n")
f.write(" };\n")
f.write("}\n")
def main() -> int:
parser = argparse.ArgumentParser(
description="Record usbfs golden traces or generate scenarios.rs."
)
parser.add_argument(
"--generate-rs",
action="store_true",
help="Generate scenarios.rs for GN build.",
)
parser.add_argument(
"--output",
help="Output file path for --generate-rs.",
)
parser.add_argument(
"--trace-dir",
help="Directory containing generated/*.json golden trace files.",
)
parser.add_argument(
"--divergences",
help="Path to divergences.json.",
)
parser.add_argument(
"--names",
nargs="*",
default=[],
help="List of scenario names for --generate-rs.",
)
parser.add_argument(
"--scenarios",
nargs="*",
default=[],
help="Optional subset of scenarios to record in QEMU.",
)
args = parser.parse_args()
if args.generate_rs:
if not args.output:
parser.error("--output is required for --generate-rs")
generate_rs(
output_path=args.output,
trace_dir=args.trace_dir,
divergences_path=args.divergences,
names=args.names,
)
return 0
raise NotImplementedError(
"b/579597237: QEMU trace recording is not implemented yet"
)
if __name__ == "__main__":
sys.exit(main())