From 1f08a8abb1c74943f541df5274d06773e4424f91 Mon Sep 17 00:00:00 2001 From: TheGeogeo <57634077+TheGeogeo@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:52:48 +0100 Subject: [PATCH] scripts: red_green.py checks a pull request red and green locally (TEST-RED-GREEN-LOCAL) Green is current main with the pull request merged. Red is current main plus only the pull request's tests: its test files, and the hunks of other Rust files that change only #[cfg(test)] items, committed on the merge base and cherry-picked with a 3-way merge. It runs the touched D3D12 crates' cargo test and the changed tests/**/test*.py on both sides, in one worktree and one target dir under the git common dir, and prints per test: red then green, pass on red and fail on green, fail on both, on one side only, with a verdict and an exit code. docs/testing.md has it next to the fork-CI recipe. --- docs/testing.md | 30 +++ scripts/red_green.py | 487 ++++++++++++++++++++++++++++++++++++++++ tests/test_red_green.py | 253 +++++++++++++++++++++ 3 files changed, 770 insertions(+) create mode 100644 scripts/red_green.py create mode 100644 tests/test_red_green.py diff --git a/docs/testing.md b/docs/testing.md index dbf9b05af9..635c700a65 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -129,6 +129,36 @@ on a shared runner: rerun that side before calling it a regression. Other jobs ( Comment on the pull request with the two run links, the `main` commit, and per side the test's own line and the summary (red: ...; green: ...). +#### A D3D12 or Python pull request, red and green on your machine + +`scripts/red_green.py` does the same locally for the D3D12 crates' `cargo test` and the Python tests under +`tests/`: + +``` +python -I scripts/red_green.py +``` + +- **Green** is current `main` (it fetches `origin/main`) with the pull request merged. +- **Red** is current `main` plus only the pull request's tests. That means its test files (under a `tests` folder, + `*_tests.rs`, `tests.rs`), and, in other Rust files, the hunks that change only `#[cfg(test)]` items. Those are + cherry-picked with a 3-way merge. A conflict, or a pull request that changes no test, is "red not constructible". + A hunk that mixes test and other code stays on the green side only. +- It runs `cargo test --no-fail-fast` for the crates under `d3d12/crates` and `d3d12/apps` the pull request touches, + from `d3d12/` so the pinned toolchain applies. It also runs each changed `tests/**/test*.py` with unittest. Both + sides run in one worktree with one cargo target dir, red first, under `/red-green` (`--work-dir` + to move it). The worktree and the target dir stay for the next run, which then builds only what changed. The + target dir takes several GB; delete the folder (and run `git worktree prune`) when done. +- It prints the tests that go from red to green, those that pass on red and fail on green, those that fail on both + (failing on `main` too), and those found on one side only. The verdict is one of: `red then green` (exit 0), + `no red`, `red does not build`, `green fails`, `red not constructible`, `green not constructible`, `no tests ran` + (exit 1). `--json` prints all of it. +- `red does not build` is the case the fork-CI steps above call "does not build without the pull request's new + file": the test needs the new code, which does not show that it catches the bug. +- `--crate ` adds a crate, `--no-cargo` or `--no-python` leaves one kind out, `--base ` tests on another + base, and `--no-fetch` uses the refs as they are. + +C++ `runtime/` tests are not run by it; use the fork's CI as above. + ## What you need - **Python 3.12+**, which `make_game.py` requires (it stops with "Python 3.12 or newer is needed" on an older one, so diff --git a/scripts/red_green.py b/scripts/red_green.py new file mode 100644 index 0000000000..1af2fd1677 --- /dev/null +++ b/scripts/red_green.py @@ -0,0 +1,487 @@ +#!/usr/bin/env python3 +"""Checks a pull request red and green on this machine (docs/testing.md, "Red and green on your machine"). + + python -I scripts/red_green.py [--base REF] [--remote NAME] [--no-fetch] + [--work-dir DIR] [--crate NAME ...] [--no-cargo] [--no-python] [--cargo PATH] [--json] + +Green is the base (`/main` after a fetch, by default) with the pull request merged. Red is the base with +only the pull request's tests. A test that fails on red and passes on green shows that the change is what makes it +pass; a test that passes on both proves nothing about the change. + +The red side comes from the pull request's diff against its merge base with the base: +- test files, whole: a file under a `tests` folder (`tests/**`, a crate's `tests/`, `src/tests/`), `*_tests.rs`, + `tests.rs`; +- in other Rust files, the hunks that change only `#[cfg(test)]` items (a `#[cfg(test)] mod x { ... }` block, a + `#[cfg(test)] mod x_tests;` line, a `#[cfg(test)]` function), blank lines and comments around them allowed. +That change is committed on the merge base, then cherry-picked onto the base. A conflict, or a pull request with no +test, is "red not constructible". + +It runs `cargo test --no-fail-fast` for the D3D12 crates the pull request touches (from `d3d12/`, so the pinned +toolchain applies) and the changed `tests/**/test*.py` files with unittest, on both sides, in one worktree and one +cargo target dir under --work-dir (default `/red-green`), red first. It keeps both between runs: the +second run on the same crates builds only what changed. C++ `runtime/` tests are not run here (docs/testing.md has +the fork-CI way). + +Exit 0: at least one test went from red to green and no test that passes on red fails on green. 1: any other +verdict. 2: a usage or git error. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +IDENTITY = { + "GIT_AUTHOR_NAME": "red_green", "GIT_AUTHOR_EMAIL": "red_green@localhost", + "GIT_COMMITTER_NAME": "red_green", "GIT_COMMITTER_EMAIL": "red_green@localhost", +} + + +class Failure(Exception): + """A usage or git error: the command exits 2 with its message.""" + + +def run(args: list[str], cwd: Path, env: dict | None = None, data: bytes | None = None) -> subprocess.CompletedProcess: + return subprocess.run(args, cwd=cwd, env=env, input=data, capture_output=True) + + +def git(cwd: Path, *args: str, env: dict | None = None, data: bytes | None = None, check: bool = True) -> str: + r = run(["git", *args], cwd, env, data) + if check and r.returncode != 0: + why = (r.stderr or r.stdout).decode("utf-8", "replace").strip().splitlines() + raise Failure(f"git {' '.join(args)}: {why[-1] if why else 'exit ' + str(r.returncode)}") + return r.stdout.decode("utf-8", "replace").strip() + + +def blob(cwd: Path, rev: str, path: str) -> bytes | None: + r = run(["git", "cat-file", "blob", f"{rev}:{path}"], cwd) + return r.stdout if r.returncode == 0 else None + + +def lines_of(data: bytes) -> list[bytes]: + """Lines as git counts them (on \\n only), each with its end.""" + parts = data.split(b"\n") + out = [p + b"\n" for p in parts[:-1]] + if parts[-1]: + out.append(parts[-1]) + return out + + +# --- which files and hunks are tests --------------------------------------------------------------------------- + +def is_test_file(path: str) -> bool: + parts = path.split("/") + return "tests" in parts[:-1] or parts[-1].endswith("_tests.rs") or parts[-1] == "tests.rs" + + +CFG = re.compile(r"^\s*#\[cfg\((.*)\)\]\s*$") +RAW_OPEN = re.compile(r'b?r(#*)"') +CHAR = re.compile(r"b?'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F]+\}|.)|[^\\'])'") + + +def is_test_cfg(expr: str) -> bool: + expr = expr.replace(" ", "") + if "not(test" in expr: + return False + return expr == "test" or (expr.startswith("all(") and re.search(r"[(,]test[,)]", expr) is not None) + + +def item_end(lines: list[str], start: int) -> int | None: + """The last line of the Rust item that starts at `start`: its `;` before any brace, or its closing brace.""" + depth, opened, state = 0, False, None + for i in range(start, len(lines)): + s, k = lines[i], 0 + while k < len(s): + c = s[k] + if state == "str": + if c == "\\": + k += 2 + continue + if c == '"': + state = None + elif isinstance(state, int): # a raw string with `state` hashes + close = '"' + "#" * state + if s.startswith(close, k): + state, k = None, k + len(close) + continue + elif state == "comment": + if s.startswith("*/", k): + state, k = None, k + 2 + continue + else: + if s.startswith("//", k): + break + if s.startswith("/*", k): + state, k = "comment", k + 2 + continue + m = RAW_OPEN.match(s, k) + if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): + state, k = len(m.group(1)), m.end() + continue + m = CHAR.match(s, k) + if m and (k == 0 or not (s[k - 1].isalnum() or s[k - 1] == "_")): + k = m.end() + continue + if c == '"': + state = "str" + elif c == "{": + depth, opened = depth + 1, True + elif c == "}": + depth -= 1 + if opened and depth == 0: + return i + elif c == ";" and not opened and depth == 0: + return i + k += 1 + return None + + +def test_lines(data: bytes) -> set[int]: + """0-based indexes of the lines that belong to `#[cfg(test)]` items.""" + lines = [line.decode("utf-8", "replace") for line in lines_of(data)] + out: set[int] = set() + i = 0 + while i < len(lines): + m = CFG.match(lines[i]) + if m and is_test_cfg(m.group(1)): + j = i + 1 + while j < len(lines) and (not lines[j].strip() or lines[j].lstrip().startswith(("#[", "//"))): + j += 1 + end = item_end(lines, j) if j < len(lines) else None + if end is not None: + out.update(range(i, end + 1)) + i = end + 1 + continue + i += 1 + return out + + +def neutral(line: bytes) -> bool: + text = line.decode("utf-8", "replace").strip() + return not text or text.startswith("//") + + +HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") + + +def hunks(diff: str) -> list[tuple[int, int, int, int]]: + out = [] + for line in diff.splitlines(): + m = HUNK.match(line) + if m: + a, b, c, d = m.group(1), m.group(2), m.group(3), m.group(4) + out.append((int(a), 1 if b is None else int(b), int(c), 1 if d is None else int(d))) + return out + + +def test_hunks(old: bytes, new: bytes, diff: str) -> bytes | None: + """`old` with only the hunks of `diff` (made with -U0) that change test code; None when there is none.""" + old_lines, new_lines = lines_of(old), lines_of(new) + old_tests, new_tests = test_lines(old), test_lines(new) + keep = [] + for a, b, c, d in hunks(diff): + removed = range(a - 1, a - 1 + b) + added = range(c - 1, c - 1 + d) + lines = [(i in old_tests, old_lines[i]) for i in removed] + [(i in new_tests, new_lines[i]) for i in added] + if lines and all(t or neutral(line) for t, line in lines) and any(t for t, _ in lines): + keep.append((a, b, c, d)) + if not keep: + return None + out = list(old_lines) + for a, b, c, d in sorted(keep, reverse=True): + at = a if b == 0 else a - 1 + out[at:at + b] = new_lines[c - 1:c - 1 + d] + return b"".join(out) + + +# --- the two sides ------------------------------------------------------------------------------------------------ + +def red_commit(repo: Path, merge_base: str, head: str) -> tuple[str | None, list[str]]: + """A commit on the merge base with only the pull request's tests, and the files it takes them from.""" + changed = git(repo, "diff", "--name-status", "--no-renames", "-z", merge_base, head).split("\0") + pairs = [(changed[i], changed[i + 1]) for i in range(0, len(changed) - 1, 2)] + plan: list[tuple[str, tuple[str, bytes] | None]] = [] + for status, path in pairs: + if is_test_file(path): + if status == "D": + plan.append((path, None)) + continue + mode = git(repo, "ls-tree", head, "--", path).split(" ", 1)[0] + plan.append((path, (mode, blob(repo, head, path) or b""))) + elif path.endswith(".rs") and status == "M": + diff = git(repo, "diff", "-U0", "--no-color", "--no-ext-diff", merge_base, head, "--", path) + merged = test_hunks(blob(repo, merge_base, path) or b"", blob(repo, head, path) or b"", diff) + if merged is not None: + mode = git(repo, "ls-tree", merge_base, "--", path).split(" ", 1)[0] + plan.append((path, (mode, merged))) + if not plan: + return None, [] + with tempfile.TemporaryDirectory(prefix="red-green-index-") as tmp: + env = dict(os.environ, GIT_INDEX_FILE=str(Path(tmp) / "index"), **IDENTITY) + git(repo, "read-tree", merge_base, env=env) + for path, change in plan: + if change is None: + git(repo, "update-index", "--force-remove", "--", path, env=env) + else: + mode, data = change + sha = git(repo, "hash-object", "-w", "--stdin", data=data) + git(repo, "update-index", "--add", "--cacheinfo", f"{mode},{sha},{path}", env=env) + tree = git(repo, "write-tree", env=env) + commit = git(repo, "commit-tree", tree, "-p", merge_base, "-m", f"red_green: the tests of {head[:12]} only", + env=env) + return commit, [path for path, _ in plan] + + +def checkout(repo: Path, tree: Path, base: str) -> None: + if not (tree / ".git").exists(): + git(repo, "worktree", "add", "--detach", "--force", str(tree), base) + return + git(tree, "cherry-pick", "--quit", check=False) + git(tree, "merge", "--quit", check=False) + git(tree, "reset", "--hard", "-q") + git(tree, "clean", "-fdq") + git(tree, "checkout", "--detach", "--force", "-q", base) + + +def conflicts(tree: Path) -> list[str]: + return [p for p in git(tree, "diff", "--name-only", "--diff-filter=U").splitlines() if p] + + +# --- running the tests -------------------------------------------------------------------------------------------- + +UNIT = re.compile(r"^\s*(?:Running\s.*?([\w-]+?)-[0-9a-f]{16}(?:\.exe)?\)|Doc-tests\s+(\S+))\s*$") +CARGO_TEST = re.compile(r"^test (.+?) \.\.\. (ok|FAILED|ignored)\b") +CARGO_ERROR = re.compile(r"^error(?:\[E\d+\])?: ") + + +def crates_of(tree: Path, paths: list[str]) -> list[str]: + names = [] + for path in paths: + parts = path.split("/") + if len(parts) > 3 and parts[0] == "d3d12" and parts[1] in ("crates", "apps"): + manifest = tree / "d3d12" / parts[1] / parts[2] / "Cargo.toml" + if manifest.is_file(): + m = re.search(r'^\s*name\s*=\s*"([^"]+)"', manifest.read_text(encoding="utf-8"), re.M) + if m and m.group(1) not in names: + names.append(m.group(1)) + return names + + +def cargo_tests(tree: Path, crates: list[str], cargo: str, target: Path) -> dict: + cmd = [sys.executable, cargo] if cargo.endswith(".py") else [cargo] + cmd += ["test", "--locked", "--no-fail-fast"] + [a for c in crates for a in ("-p", c)] + env = dict(os.environ, CARGO_TARGET_DIR=str(target)) + r = subprocess.run(cmd, cwd=tree / "d3d12", env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out = r.stdout.decode("utf-8", "replace") + tests, unit, error = {}, "?", None + for line in out.splitlines(): + m = UNIT.match(line) + if m: + unit = m.group(1) or "doc:" + m.group(2) + continue + m = CARGO_TEST.match(line) + if m: + tests[f"{unit}::{m.group(1)}"] = {"ok": "ok", "FAILED": "failed", "ignored": "ignored"}[m.group(2)] + elif error is None and CARGO_ERROR.match(line): + error = line.strip() + no_build = r.returncode != 0 and not tests + return {"tests": tests, "no_build": (error or f"cargo exit {r.returncode}") if no_build else None} + + +PY_TEST = re.compile(r"^(\w+) \(([\w.]+)\)(?:\n[^\n]*?)? \.\.\. (ok|FAIL|ERROR|skipped|expected failure|unexpected success)", + re.M) + + +def python_tests(tree: Path, files: list[str]) -> dict: + tests, no_build = {}, [] + for f in files: + start = "tests/semantic" if f.startswith("tests/semantic/") else str(Path(f).parent) + r = subprocess.run([sys.executable, "-I", "-m", "unittest", "discover", "-s", start, "-p", Path(f).name, "-v"], + cwd=tree, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + out = r.stdout.decode("utf-8", "replace") + found = 0 + for name, where, status in PY_TEST.findall(out): + if "_FailedTest" in where: + no_build.append(f"{f}: does not import") + continue + key = where if where.endswith("." + name) else f"{where}.{name}" + tests[f"{f}::{key}"] = {"ok": "ok", "skipped": "ignored", "expected failure": "ok"}.get(status, "failed") + found += 1 + if not found and r.returncode != 0 and f"{f}: does not import" not in no_build: + no_build.append(f"{f}: exit {r.returncode}") + return {"tests": tests, "no_build": "; ".join(no_build) or None} + + +def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target: Path) -> dict: + result = {"tests": {}, "no_build": []} + for part in ([cargo_tests(tree, crates, cargo, target)] if crates else []) + \ + ([python_tests(tree, py_files)] if py_files else []): + result["tests"].update(part["tests"]) + if part["no_build"]: + result["no_build"].append(part["no_build"]) + return result + + +# --- reading the two sides ---------------------------------------------------------------------------------------- + +def compare(red: dict | None, green: dict | None) -> dict: + r = red["tests"] if red else {} + g = green["tests"] if green else {} + rows = {"red_to_green": [], "regressions": [], "fail_on_both": [], "only_on_green": [], "only_on_red": []} + both_ok = 0 + for key in sorted(set(r) | set(g)): + a, b = r.get(key), g.get(key) + if a == "failed" and b == "ok": + rows["red_to_green"].append(key) + elif a == "ok" and b == "failed": + rows["regressions"].append(key) + elif a == "failed" and b == "failed": + rows["fail_on_both"].append(key) + elif a is None and b is not None: + rows["only_on_green"].append(f"{key} ({b})") + elif b is None and a is not None: + rows["only_on_red"].append(f"{key} ({a})") + elif a == "ok" and b == "ok": + both_ok += 1 + rows["pass_on_both"] = both_ok + return rows + + +def verdict(red_why: str | None, green_why: str | None, red: dict | None, green: dict | None, rows: dict) -> str: + if green_why: + return "green not constructible" + green_failed = rows["regressions"] or any(r.endswith("(failed)") for r in rows["only_on_green"]) + if green and green["no_build"] or green_failed: + return "green fails" + if red_why: + return "red not constructible" + if not (red and red["tests"]) and not (green and green["tests"]): + return "no tests ran" + if rows["red_to_green"]: + return "red then green" + if red and red["no_build"] and rows["only_on_green"]: + return "red does not build" + return "no red" + + +def report(r: dict) -> str: + out = [f"base {r['base']} {r['base_commit'][:9]}, head {r['head']} {r['head_commit'][:9]}, " + f"merge base {r['merge_base'][:9]}"] + out.append("red: " + (r["red_why"] or "the base plus the tests of " + ", ".join(r["red_files"]))) + out.append("green: " + (r["green_why"] or "the base with the pull request merged")) + out.append("ran: " + ", ".join([f"cargo -p {c}" for c in r["crates"]] + r["python_files"] or ["nothing"])) + for name in ("red", "green"): + s = r[name] + if s and s["no_build"]: + out.append(f"{name} does not build: " + "; ".join(s["no_build"])) + rows = r["rows"] + labels = {"red_to_green": "red then green", "regressions": "pass on red, FAIL on green", + "fail_on_both": "fail on both (failing on the base too?)", "only_on_green": "only on green", + "only_on_red": "only on red"} + for key, label in labels.items(): + if rows[key]: + out.append(f"{label} ({len(rows[key])}):") + out += [f" {t}" for t in rows[key][:40]] + if len(rows[key]) > 40: + out.append(f" ... {len(rows[key]) - 40} more") + out.append(f"pass on both: {rows['pass_on_both']}") + out.append(f"verdict: {r['verdict']}") + return "\n".join(out) + + +def main(argv: list[str] | None = None) -> int: + p = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + p.add_argument("pr", help="a pull request number (fetched from --remote) or a git ref") + p.add_argument("--base", help="the base to test on (default /main, fetched)") + p.add_argument("--remote", default="origin", help="where main and pull requests are fetched from (origin)") + p.add_argument("--no-fetch", action="store_true", help="use the refs as they are") + p.add_argument("--work-dir", type=Path, help="the worktree and cargo target dir (/red-green)") + p.add_argument("--crate", action="append", default=[], help="a cargo package to test as well (repeatable)") + p.add_argument("--no-cargo", action="store_true", help="skip the cargo tests") + p.add_argument("--no-python", action="store_true", help="skip the Python tests") + p.add_argument("--cargo", default="cargo", help="the cargo to run (a .py file runs with this Python)") + p.add_argument("--json", action="store_true", help="print the result as JSON") + a = p.parse_args(argv) + try: + repo = Path(git(Path.cwd(), "rev-parse", "--show-toplevel")) + common = Path(git(repo, "rev-parse", "--path-format=absolute", "--git-common-dir")) + base = a.base or f"{a.remote}/main" + if not a.no_fetch: + if not a.base: + git(repo, "fetch", "-q", a.remote, "main") + if a.pr.isdigit(): + git(repo, "fetch", "-q", a.remote, f"pull/{a.pr}/head") + head = git(repo, "rev-parse", "FETCH_HEAD" if a.pr.isdigit() and not a.no_fetch else a.pr + "^{commit}") + base_commit = git(repo, "rev-parse", base + "^{commit}") + merge_base = git(repo, "merge-base", base_commit, head) + work = (a.work_dir or common / "red-green").resolve() + work.mkdir(parents=True, exist_ok=True) + lock = work / "lock" + try: + fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY) + except FileExistsError: + raise Failure(f"{lock} exists: another run is going, or delete it if none is") from None + os.write(fd, str(os.getpid()).encode()) + os.close(fd) + try: + result = check(repo, work, a, base, base_commit, head, merge_base) + finally: + lock.unlink(missing_ok=True) + except Failure as e: + print(f"red_green: {e}", file=sys.stderr) + return 2 + print(json.dumps(result, indent=1) if a.json else report(result)) + return 0 if result["verdict"] == "red then green" else 1 + + +def check(repo: Path, work: Path, a, base: str, base_commit: str, head: str, merge_base: str) -> dict: + tree, target = work / "tree", work / "target" + changed = [p for p in git(repo, "diff", "--name-only", "--no-renames", merge_base, head).splitlines() if p] + checkout(repo, tree, base_commit) + crates = [] if a.no_cargo else crates_of(tree, changed) + [c for c in a.crate if c not in crates_of(tree, changed)] + py_files = [] if a.no_python else [ + f for f in changed if f.startswith("tests/") and re.fullmatch(r"test\w*\.py", f.rsplit("/", 1)[-1])] + env = dict(os.environ, **IDENTITY) + + red, red_why = None, None + commit, red_files = red_commit(repo, merge_base, head) + if commit is None: + red_why = "not constructible: the pull request changes no test" + else: + git(tree, "cherry-pick", "--no-commit", commit, env=env, check=False) + stuck = conflicts(tree) + if stuck: + red_why = "not constructible: the tests conflict with the base in " + ", ".join(stuck) + else: + print("red_green: red side...", file=sys.stderr) + red = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) + + green, green_why = None, None + checkout(repo, tree, base_commit) + git(tree, "merge", "--no-commit", "--no-ff", head, env=env, check=False) + stuck = conflicts(tree) + if stuck: + green_why = "not constructible: the pull request conflicts with the base in " + ", ".join(stuck) + else: + print("red_green: green side...", file=sys.stderr) + green = side(tree, crates, [f for f in py_files if (tree / f).is_file()], a.cargo, target) + checkout(repo, tree, base_commit) + + rows = compare(red, green) + return {"base": base, "base_commit": base_commit, "head": a.pr, "head_commit": head, "merge_base": merge_base, + "red_files": red_files, "red_why": red_why, "green_why": green_why, "crates": crates, + "python_files": py_files, "red": red, "green": green, "rows": rows, + "verdict": verdict(red_why, green_why, red, green, rows)} + + +if __name__ == "__main__": + try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode + sys.stdout.reconfigure(errors="replace") + except (AttributeError, ValueError, OSError): + pass + sys.exit(main()) diff --git a/tests/test_red_green.py b/tests/test_red_green.py new file mode 100644 index 0000000000..4d20e5c902 --- /dev/null +++ b/tests/test_red_green.py @@ -0,0 +1,253 @@ +"""scripts/red_green.py on throwaway git repositories, with a stub cargo (standard library only, no game data).""" +import io +import json +import os +import subprocess +import sys +import tempfile +import unittest +from contextlib import redirect_stderr, redirect_stdout + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "scripts")) +import red_green as rg # noqa: E402 + +LIB = """pub fn value() -> u32 { + 1 +} + +#[cfg(test)] +mod tests { + #[test] + fn value_is_one() { + assert_eq!(super::value(), 1); + } +} +""" + +# Reads crates/foo/src/lib.rs as cargo would build it, and "runs" its tests: `pub fn () -> u32 { N }` returns N, +# and a test `fn () { assert_eq!(super::(), M) }` passes when N == M. A test calling a missing function does +# not build. +STUB_CARGO = r''' +import re, sys +text = open("crates/foo/src/lib.rs", encoding="utf-8").read() +fns = dict(re.findall(r"pub fn (\w+)\(\) -> u32 \{\s*(\d+)", text)) +tests = re.findall(r"fn (\w+)\(\) \{\s*assert_eq!\(super::(\w+)\(\), (\d+)", text) +for name, fn, want in tests: + if fn not in fns: + print(f"error[E0425]: cannot find function `{fn}` in module `super`") + sys.exit(101) +print(" Running unittests src/lib.rs (target/debug/deps/foo-0123456789abcdef.exe)") +failed = False +for name, fn, want in tests: + ok = fns[fn] == want + failed |= not ok + print(f"test tests::{name} ... {'ok' if ok else 'FAILED'}") +sys.exit(101 if failed else 0) +''' + + +class Repo: + def __init__(self, test): + self.tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True) + test.addCleanup(self.tmp.cleanup) + self.dir = os.path.join(self.tmp.name, "repo") + os.makedirs(self.dir) + self.git("init", "-q", "-b", "main") + self.git("config", "user.name", "test") + self.git("config", "user.email", "test@localhost") + self.git("config", "core.autocrlf", "false") + self.stub = os.path.join(self.tmp.name, "cargo_stub.py") + with open(self.stub, "w", encoding="utf-8") as f: + f.write(STUB_CARGO) + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.dir, check=True, capture_output=True, text=True).stdout + + def write(self, path, text): + full = os.path.join(self.dir, path) + os.makedirs(os.path.dirname(full), exist_ok=True) + with open(full, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + def commit(self, message, files): + for path, text in files.items(): + self.write(path, text) + self.git("add", "-A") + self.git("commit", "-q", "-m", message) + + def run(self, *args): + out, err = io.StringIO(), io.StringIO() + here = os.getcwd() + os.chdir(self.dir) + try: + with redirect_stdout(out), redirect_stderr(err): + code = rg.main(["pr", "--base", "main", "--no-fetch", "--cargo", self.stub, "--json", *args]) + finally: + os.chdir(here) + return code, (json.loads(out.getvalue()) if out.getvalue().strip() else None), err.getvalue() + + +def crate_repo(test): + repo = Repo(test) + repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', + "d3d12/crates/foo/src/lib.rs": LIB, "README.md": "base\n"}) + repo.git("switch", "-q", "-c", "pr") + return repo + + +class Sides(unittest.TestCase): + def test_a_fix_with_its_test_goes_red_then_green(self): + repo = crate_repo(self) + repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": LIB.replace(" 1\n", " 2\n").replace( + "fn value_is_one() {\n assert_eq!(super::value(), 1);", + "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) + repo.git("switch", "-q", "main") + repo.commit("main moves on", {"README.md": "main moved\n"}) + code, r, _ = repo.run() + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual(code, 0) + self.assertEqual(r["rows"]["red_to_green"], ["foo::tests::value_is_two"]) + self.assertEqual(r["red_files"], ["d3d12/crates/foo/src/lib.rs"]) + self.assertEqual(r["crates"], ["foo"]) + # The red side had the new test without the fix: value() still 1 there. + self.assertEqual(r["red"]["tests"], {"foo::tests::value_is_two": "failed"}) + # The worktree is kept for the next run, back on the base. + tree = os.path.join(repo.dir, ".git", "red-green", "tree") + self.assertTrue(os.path.isdir(tree)) + with open(os.path.join(tree, "README.md"), encoding="utf-8") as f: + self.assertEqual(f.read(), "main moved\n") + # A second run reuses it. + code, r, _ = repo.run() + self.assertEqual((code, r["verdict"]), (0, "red then green")) + + def test_a_test_that_passes_on_both_is_no_red(self): + repo = crate_repo(self) + repo.commit("test only", {"d3d12/crates/foo/src/lib.rs": LIB.replace( + " assert_eq!(super::value(), 1);\n }\n", + " assert_eq!(super::value(), 1);\n }\n\n #[test]\n fn value_again() {\n" + " assert_eq!(super::value(), 1);\n }\n")}) + code, r, _ = repo.run() + self.assertEqual((code, r["verdict"]), (1, "no red")) + self.assertEqual(r["rows"]["pass_on_both"], 2) + + def test_a_change_with_no_test_has_no_red_side(self): + repo = crate_repo(self) + repo.commit("docs", {"README.md": "changed\n"}) + code, r, _ = repo.run() + self.assertEqual(r["verdict"], "red not constructible") + self.assertIn("changes no test", r["red_why"]) + self.assertEqual(code, 1) + + def test_a_pull_request_that_breaks_a_test_is_green_fails(self): + repo = crate_repo(self) + repo.commit("break", {"d3d12/crates/foo/src/lib.rs": LIB.replace(" 1\n", " 3\n").replace( + "#[cfg(test)]\nmod tests {\n", "#[cfg(test)]\nmod tests {\n // a comment in the tests\n")}) + code, r, _ = repo.run() + self.assertEqual(r["verdict"], "green fails") + self.assertEqual(r["rows"]["regressions"], ["foo::tests::value_is_one"]) + + def test_a_test_that_needs_new_code_to_build_is_said_so(self): + repo = crate_repo(self) + repo.commit("new fn", {"d3d12/crates/foo/src/lib.rs": LIB.replace( + "pub fn value", "pub fn other() -> u32 {\n 2\n}\n\npub fn value").replace( + "mod tests {\n", "mod tests {\n #[test]\n fn other_is_two() {\n" + " assert_eq!(super::other(), 2);\n }\n\n")}) + code, r, _ = repo.run() + # Red has the new test without other(): it does not build, which shows the test needs the new code, not + # that it catches a bug. + self.assertEqual(r["verdict"], "red does not build", r) + self.assertIn("E0425", r["red"]["no_build"][0]) + self.assertEqual(r["rows"]["only_on_green"], ["foo::tests::other_is_two (ok)", "foo::tests::value_is_one (ok)"]) + self.assertEqual(code, 1) + + def test_a_pull_request_that_conflicts_with_the_base(self): + repo = crate_repo(self) + repo.commit("pr", {"d3d12/crates/foo/src/lib.rs": LIB.replace("assert_eq!(super::value(), 1);", + "assert_eq!(super::value(), 1, \"pr\");")}) + repo.git("switch", "-q", "main") + repo.commit("main", {"d3d12/crates/foo/src/lib.rs": LIB.replace("assert_eq!(super::value(), 1);", + "assert_eq!(super::value(), 1, \"main\");")}) + code, r, _ = repo.run() + self.assertEqual(r["verdict"], "green not constructible") + self.assertIn("conflict", r["red_why"]) + self.assertIn("lib.rs", r["green_why"]) + self.assertEqual(code, 1) + + def test_a_second_run_at_the_same_time_is_refused(self): + repo = crate_repo(self) + os.makedirs(os.path.join(repo.dir, ".git", "red-green")) + with open(os.path.join(repo.dir, ".git", "red-green", "lock"), "w") as f: + f.write("1") + code, r, err = repo.run() + self.assertEqual((code, r), (2, None)) + self.assertIn("another run is going", err) + + +class Python(unittest.TestCase): + TEST = ("import os, sys, unittest\n" + "sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools'))\n" + "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + " self.assertEqual(bar.two(), 2)\n") + + def test_a_python_fix_with_its_test_goes_red_then_green(self): + repo = Repo(self) + repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.TEST}) + code, r, _ = repo.run("--no-cargo") + self.assertEqual(r["verdict"], "red then green", r) + self.assertEqual(r["rows"]["red_to_green"], ["tests/test_bar.py::test_bar.T.test_two"]) + self.assertEqual(code, 0) + + def test_a_test_of_a_new_tool_does_not_import_on_red(self): + repo = Repo(self) + repo.commit("base", {"README.md": "base\n"}) + repo.git("switch", "-q", "-c", "pr") + repo.commit("new tool", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.TEST}) + code, r, _ = repo.run("--no-cargo") + self.assertEqual(r["verdict"], "red does not build", r) + self.assertIn("does not import", r["red"]["no_build"][0]) + self.assertEqual(code, 1) + + +class Hunks(unittest.TestCase): + def diff(self, old, new): + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + a, b = os.path.join(tmp, "a.rs"), os.path.join(tmp, "b.rs") + for path, text in ((a, old), (b, new)): + with open(path, "w", encoding="utf-8", newline="\n") as f: + f.write(text) + d = subprocess.run(["git", "diff", "--no-index", "-U0", "--no-color", a, b], capture_output=True, text=True) + return rg.test_hunks(old.encode(), new.encode(), d.stdout) + + def test_only_the_test_hunk_is_kept(self): + new = LIB.replace(" 1\n", " 2\n").replace("value(), 1);", "value(), 2);") + self.assertEqual(self.diff(LIB, new).decode(), LIB.replace("value(), 1);", "value(), 2);")) + + def test_a_test_module_line_is_kept_and_not_test_is_not(self): + old = "pub fn a() {}\n\npub fn c() {}\n" + new = "pub fn a() {}\n\n#[cfg(test)]\nmod a_tests;\n\npub fn c() {}\n\n#[cfg(not(test))]\nfn b() {}\n" + self.assertEqual(self.diff(old, new).decode(), "pub fn a() {}\n\n#[cfg(test)]\nmod a_tests;\n\npub fn c() {}\n") + # A hunk that mixes test and other code is left out whole. + mixed = "pub fn a() {}\n\n#[cfg(test)]\nmod a_tests;\nfn b() {}\n\npub fn c() {}\n" + self.assertIsNone(self.diff(old, mixed)) + + def test_braces_in_strings_and_comments_do_not_end_the_module(self): + old = 'pub fn a() {}\n\n#[cfg(test)]\nmod tests {\n const S: &str = r#"}"#;\n // }\n fn x() {}\n}\n\nfn c() {}\n' + new = old.replace(" fn x() {}\n}", " fn x() {}\n fn y() { let _ = '}'; }\n}") + self.assertEqual(self.diff(old, new).decode(), new) + + def test_all_with_test_counts_and_test_files_are_whole(self): + self.assertTrue(rg.is_test_cfg("all(test, windows)")) + self.assertFalse(rg.is_test_cfg("all(not(test), windows)")) + self.assertFalse(rg.is_test_cfg("feature = \"test-utils\"")) + for path in ("tests/test_x.py", "d3d12/crates/a/tests/b.rs", "d3d12/crates/a/src/x_tests.rs", + "d3d12/crates/a/src/tests.rs"): + self.assertTrue(rg.is_test_file(path), path) + for path in ("tools/tests_helper.py", "d3d12/crates/a/src/lib.rs", "runtime/test/a.cpp"): + self.assertFalse(rg.is_test_file(path), path) + + +if __name__ == "__main__": + unittest.main()