|
| 1 | +"""Show what assertion rewriting does to a snippet, as a diff. |
| 2 | +
|
| 3 | +Each side is one of ``plain`` (the source as written), ``worktree`` (this |
| 4 | +checkout's ``src/``) or a released pytest version, which is fetched on demand |
| 5 | +with ``uv run --with pytest==VERSION``. Sides are dumped as rewritten source |
| 6 | +(``ast.unparse``) or as an AST, then diffed. |
| 7 | +
|
| 8 | +Every side runs on one interpreter -- the one running this script, or the one |
| 9 | +``--python`` names. Pin it whenever the comparison is about pytest versions: |
| 10 | +an unpinned ``uv run`` is free to pick a different Python for a released |
| 11 | +pytest than the worktree runs on, and the grammar differences between the two |
| 12 | +then show up in the diff as if the rewriter had changed. |
| 13 | +
|
| 14 | +Usage:: |
| 15 | +
|
| 16 | + # what rewriting does to a snippet -- plain vs worktree, as source: |
| 17 | + python scripts/diff-assert-rewrite.py -c 'assert (x := f()) and (x := False)' |
| 18 | +
|
| 19 | + # a behaviour change against a release, over a whole file: |
| 20 | + python scripts/diff-assert-rewrite.py --left 8.3.4 testing/example.py |
| 21 | +
|
| 22 | + # same, as AST, when the source form hides the difference: |
| 23 | + python scripts/diff-assert-rewrite.py --left 8.3.4 --format ast -c 'assert a == b' |
| 24 | +
|
| 25 | + # both sides on one interpreter, whatever this script runs on: |
| 26 | + python scripts/diff-assert-rewrite.py --left 8.3.4 --python 3.14 example.py |
| 27 | +
|
| 28 | +Exits 1 when the two sides differ, 0 when they do not. |
| 29 | +""" |
| 30 | + |
| 31 | +from __future__ import annotations |
| 32 | + |
| 33 | +import argparse |
| 34 | +import difflib |
| 35 | +import os |
| 36 | +from pathlib import Path |
| 37 | +import subprocess |
| 38 | +import sys |
| 39 | +import tempfile |
| 40 | + |
| 41 | + |
| 42 | +# Runs inside the environment of the pytest version under inspection: reads |
| 43 | +# the source file named on its command line, writes the dump to stdout. |
| 44 | +_WORKER = """ |
| 45 | +import ast, sys |
| 46 | +fmt, mode, path = sys.argv[1:4] |
| 47 | +source = open(path, "rb").read() |
| 48 | +tree = ast.parse(source) |
| 49 | +if mode == "rewrite": |
| 50 | + from _pytest.assertion.rewrite import rewrite_asserts |
| 51 | + rewrite_asserts(tree, source) |
| 52 | + ast.fix_missing_locations(tree) |
| 53 | +print(ast.unparse(tree) if fmt == "source" else ast.dump(tree, indent=2)) |
| 54 | +""" |
| 55 | + |
| 56 | +_COLORS = {"-": "\033[31m", "+": "\033[32m", "@": "\033[36m"} |
| 57 | + |
| 58 | + |
| 59 | +def spawn( |
| 60 | + spec: str, fmt: str, path: Path, python: str | None |
| 61 | +) -> subprocess.Popen[bytes]: |
| 62 | + """Start the dump of one side -- callers start both, then collect.""" |
| 63 | + args = [fmt, "plain" if spec == "plain" else "rewrite", str(path)] |
| 64 | + repo = Path(__file__).parent.parent |
| 65 | + # src/ ahead of whatever is installed, so 'worktree' means this checkout. |
| 66 | + env = os.environ | {"PYTHONPATH": str(repo / "src")} if spec == "worktree" else None |
| 67 | + if python is None and spec in ("plain", "worktree"): |
| 68 | + cmd = [sys.executable, "-c", _WORKER, *args] |
| 69 | + else: |
| 70 | + cmd = ["uv", "run"] |
| 71 | + if python is not None: |
| 72 | + cmd += ["--python", python] |
| 73 | + # The worktree needs pytest's dependencies; the other sides need none. |
| 74 | + cmd += ["--project", str(repo)] if spec == "worktree" else ["--no-project"] |
| 75 | + if spec not in ("plain", "worktree"): |
| 76 | + cmd += ["--with", f"pytest=={spec}"] |
| 77 | + cmd += ["--", "python", "-c", _WORKER, *args] |
| 78 | + try: |
| 79 | + return subprocess.Popen( |
| 80 | + cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE |
| 81 | + ) |
| 82 | + except FileNotFoundError as exc: |
| 83 | + raise SystemExit( |
| 84 | + f"{exc.filename} not found (uv: https://docs.astral.sh/uv/)" |
| 85 | + ) from None |
| 86 | + |
| 87 | + |
| 88 | +def collect(procs: list[tuple[str, subprocess.Popen[bytes]]]) -> list[list[str]]: |
| 89 | + """Wait for every side before reporting, so no worker outlives the source.""" |
| 90 | + done = [(spec, *proc.communicate(), proc.returncode) for spec, proc in procs] |
| 91 | + for spec, _, err, code in done: |
| 92 | + if code: |
| 93 | + sys.stderr.buffer.write(err) |
| 94 | + raise SystemExit(f"dumping {spec} failed") |
| 95 | + return [out.decode().splitlines() for _, out, _, _ in done] |
| 96 | + |
| 97 | + |
| 98 | +def main(argv: list[str] | None = None) -> None: |
| 99 | + parser = argparse.ArgumentParser( |
| 100 | + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter |
| 101 | + ) |
| 102 | + parser.add_argument( |
| 103 | + "file", type=Path, nargs="?", help="file to rewrite (default: stdin)" |
| 104 | + ) |
| 105 | + parser.add_argument("-c", "--code", help="snippet to rewrite instead of a file") |
| 106 | + parser.add_argument( |
| 107 | + "--left", |
| 108 | + default="plain", |
| 109 | + metavar="SPEC", |
| 110 | + help="'plain', 'worktree' or a pytest version", |
| 111 | + ) |
| 112 | + parser.add_argument( |
| 113 | + "--right", default="worktree", metavar="SPEC", help="the same, other side" |
| 114 | + ) |
| 115 | + parser.add_argument("--format", choices=("source", "ast"), default="source") |
| 116 | + parser.add_argument( |
| 117 | + "--python", |
| 118 | + metavar="X.Y", |
| 119 | + help="run both sides on this Python (default: the current one)", |
| 120 | + ) |
| 121 | + parser.add_argument("--no-color", action="store_true") |
| 122 | + args = parser.parse_args(argv) |
| 123 | + |
| 124 | + if args.code is not None: |
| 125 | + source = args.code.encode() |
| 126 | + elif args.file is not None: |
| 127 | + source = args.file.read_bytes() |
| 128 | + else: |
| 129 | + source = sys.stdin.buffer.read() |
| 130 | + |
| 131 | + with tempfile.TemporaryDirectory() as tmp: |
| 132 | + path = Path(tmp, "snippet.py") |
| 133 | + path.write_bytes(source) |
| 134 | + left, right = collect( |
| 135 | + [ |
| 136 | + (side, spawn(side, args.format, path, args.python)) |
| 137 | + for side in (args.left, args.right) |
| 138 | + ] |
| 139 | + ) |
| 140 | + diff = list( |
| 141 | + difflib.unified_diff( |
| 142 | + left, right, fromfile=args.left, tofile=args.right, lineterm="" |
| 143 | + ) |
| 144 | + ) |
| 145 | + if not diff: |
| 146 | + print(f"{args.left} and {args.right} agree on the {args.format} form") |
| 147 | + return |
| 148 | + |
| 149 | + color = not args.no_color and sys.stdout.isatty() |
| 150 | + for line in diff: |
| 151 | + prefix = _COLORS.get(line[:1], "") if color else "" |
| 152 | + print(f"{prefix}{line}\033[0m" if prefix else line) |
| 153 | + raise SystemExit(1) |
| 154 | + |
| 155 | + |
| 156 | +if __name__ == "__main__": |
| 157 | + main() |
0 commit comments