#!/usr/bin/env python3 """Point a test brought from the reference at the example Workflow. scripts/repoint.py tests/execution/test_x.py [...] The reference's tests call its engine with no Workflow, because it has only one. Here every such call names the example: `Ledger(...)`, `Ledger.from_dict(...)` and `specialist_tools(...)` gain `WORKFLOW` as their first argument, the engine is built with `workflow=WORKFLOW`, and the sample data and sample submissions are taken from the example. Running it twice changes nothing more. """ from __future__ import annotations import re import sys from pathlib import Path EXAMPLE = "tests.reference_workflow.workflow" _CALLS = ( (re.compile(r"\bLedger\.from_dict\((?!WORKFLOW)"), "Ledger.from_dict(WORKFLOW, "), (re.compile(r"(? str: """Take the example's own names out of an import from the scripted runtime, and import them from the example.""" match = _FAKE_IMPORT.search(text) if not match: return text items = [ item.strip() for item in match.group(1).strip("()").split(",") if item.strip() ] moved = [item for item in items if item.split(" as ")[0] in _EXAMPLES_OWN] if not moved: return text kept = [item for item in items if item not in moved] lines = ( f"from execution_engine.adk.fake_runtime import {', '.join(kept)}\n" if kept else "" ) lines += f"from {EXAMPLE} import {', '.join(moved)}\n" return text[: match.start()] + lines + text[match.end() :] def _end_of_statement(text: str, start: int) -> int: """Where the import statement starting at `start` ends.""" line_end = text.index("\n", start) if "(" in text[start:line_end] and ")" not in text[start:line_end]: return text.index("\n", text.index(")", start)) return line_end def repoint(text: str) -> str: for pattern, replacement in _CALLS: text = pattern.sub(replacement, text) text = text.replace("(WORKFLOW, )", "(WORKFLOW)") for pattern, replacement in _MOVED: text = pattern.sub(replacement, text) text = _move_examples_own(text) imported = " ".join(_FROM_EXAMPLE.findall(text)) missing = [ name for name in ("WORKFLOW",) if re.search(rf"\b{name}\b", text) and not re.search(rf"\b{name}\b", imported) ] if missing: line = f"from {EXAMPLE} import {', '.join(missing)}\n" imports = list(_TOP_IMPORT.finditer(text)) at = _end_of_statement(text, imports[-1].start()) + 1 if imports else 0 text = text[:at] + line + text[at:] return text if __name__ == "__main__": for name in sys.argv[1:]: path = Path(name) path.write_text(repoint(path.read_text(encoding="utf-8")), encoding="utf-8")