scripts/dev/extract_tests.py moves a trailing cfg(test) mod tests block into foo/tests.rs for 118 files of leleka-runtime, cuda-driver, control-plane, gateway-text, deploy and nine smaller crates (31,000 lines), leaving production code and test ids untouched; 22 files that are themselves loaded through a path attribute carry an explicit path to their tests file. Not touched: the files the kar-off-ab branch edits (backend.rs, backend_original_serve.rs, backend_original_serve_replay.rs, qwen4exp_resident_expert_source.rs and seven deploy files). Verified: cargo check --all-targets for the whole workspace on x86_64 Linux and on the Windows host; the 2429 library unit-test ids of the workspace are identical before and after (Linux listing diff empty); the loadable sections of leleka-inference, leleka-daemon, leleka-cli and strata-next are byte-identical between a release build before and after (scripts/dev/elf-sections-equal.sh), so the shipped code is the same. The architecture ratchets exclude tests.rs from the path-include count; the baseline drops from 329 to 311 oversize files and from 302,000 to 273,600 lines.
107 lines
4.2 KiB
Python
107 lines
4.2 KiB
Python
#!/usr/bin/env python3
|
|
"""Move a trailing inline `#[cfg(test)] mod tests { ... }` of a Rust module file into its own file (STRA-338).
|
|
|
|
`foo.rs` gets `#[cfg(test)]` and `mod tests;`; the body moves, dedented, to `foo/tests.rs`, so the test ids
|
|
(`foo::tests::name`) and the production code stay exactly as they were. A file that was itself loaded through
|
|
`#[path]` looks for `tests.rs` beside it instead: the compiler reports those, add `#[path = "foo/tests.rs"]` by hand.
|
|
Crate roots (lib.rs, main.rs, bin/*, examples/*) are skipped. Relative `include_str!` / `include_bytes!` paths inside
|
|
the moved body get one more `../` (the file sits one directory deeper). The compiler is the judge of the rest.
|
|
|
|
Usage: scripts/dev/extract_tests.py [--dry-run] FILE.rs... prints "moved|skipped <file> <detail>" per file
|
|
"""
|
|
import argparse
|
|
import pathlib
|
|
import re
|
|
import sys
|
|
|
|
OPEN = re.compile(r"^(?:pub(?:\(crate\))? )?mod tests \{$")
|
|
INCLUDE = re.compile(r'(include_(?:str|bytes)!\(\s*")(?=[^/])')
|
|
HEADER = "//! Unit tests of this module (moved out of the file by STRA-338; the test ids are unchanged).\n\n"
|
|
|
|
|
|
def read(path):
|
|
with open(path, encoding="utf-8", newline="") as handle:
|
|
return handle.read().replace("\r\n", "\n")
|
|
|
|
|
|
def write(path, text):
|
|
with open(path, "w", encoding="utf-8", newline="\n") as handle:
|
|
handle.write(text)
|
|
|
|
|
|
def find_block(lines):
|
|
"""Index of the one `#[cfg(test)]` line that opens a `mod tests {` at column 0, or None."""
|
|
hits = [i for i, row in enumerate(lines[:-1]) if row == "#[cfg(test)]" and OPEN.match(lines[i + 1])]
|
|
return hits[0] if len(hits) == 1 else None
|
|
|
|
|
|
def block_end(lines, start):
|
|
"""Index of the column-0 `}` that closes the tests module, or None when code follows it."""
|
|
end = next((i for i in range(start + 2, len(lines)) if lines[i] == "}"), None)
|
|
return end if end is not None and not any(row.strip() for row in lines[end + 1:]) else None
|
|
|
|
|
|
def is_plain_module(path):
|
|
"""False for crate roots, bins, examples and benches."""
|
|
parts = path.parts
|
|
if path.name in ("lib.rs", "main.rs") or any(d in parts for d in ("bin", "examples", "benches")):
|
|
return False
|
|
return "tests" not in parts[:-1]
|
|
|
|
|
|
def dedent(rows):
|
|
return [row[4:] if row.startswith(" ") else row for row in rows]
|
|
|
|
|
|
def deepen_includes(text):
|
|
"""One more `../` before every relative include path; the macro and its string may sit on different lines."""
|
|
return INCLUDE.sub(lambda m: m.group(1) + "../", text)
|
|
|
|
|
|
def target_path(path):
|
|
"""`foo.rs` -> `foo/tests.rs`; `foo/mod.rs` -> `foo/tests.rs`."""
|
|
return path.with_name("tests.rs") if path.name == "mod.rs" else path.with_suffix("") / "tests.rs"
|
|
|
|
|
|
def split_text(text):
|
|
"""(new source, tests file text), or a reason string when the file has no single trailing tests module."""
|
|
lines = text.split("\n")
|
|
start = find_block(lines)
|
|
end = block_end(lines, start) if start is not None else None
|
|
if end is None:
|
|
return "no single trailing mod tests block that ends the file"
|
|
body = deepen_includes("\n".join(dedent(lines[start + 2:end])))
|
|
declaration = ["#[cfg(test)]", "mod tests;", ""]
|
|
return "\n".join(lines[:start] + declaration), HEADER + body.rstrip("\n") + "\n"
|
|
|
|
|
|
def process(path, dry_run):
|
|
if not is_plain_module(path):
|
|
return "skipped", "crate root, bin, example or bench"
|
|
result = split_text(read(path))
|
|
if isinstance(result, str):
|
|
return "skipped", result
|
|
destination = target_path(path)
|
|
if destination.exists():
|
|
return "skipped", f"{destination} already exists"
|
|
if not dry_run:
|
|
destination.parent.mkdir(parents=True, exist_ok=True)
|
|
write(destination, result[1])
|
|
write(path, result[0])
|
|
return "moved", str(destination)
|
|
|
|
|
|
def main(argv):
|
|
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
parser.add_argument("--dry-run", action="store_true")
|
|
parser.add_argument("files", nargs="+")
|
|
args = parser.parse_args(argv)
|
|
for name in args.files:
|
|
verdict, detail = process(pathlib.Path(name), args.dry_run)
|
|
print(f"{verdict} {name} {detail}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main(sys.argv[1:]))
|