Files
mandy/tests/test_red_green.py
TheGeogeo bf65aa4505 scripts: red_green.py skips a folder it cannot list, stops with the tree put back on a __pycache__ it cannot remove, and four smaller fixes (review)
drop_bytecode skips a folder it may not list (Python cannot import from it either). A __pycache__ it cannot remove is now a usage error naming it (exit 2), and any such error during a run puts the tree back on the base, where before the undone hunk stayed. --mutate-timeout must also be finite. In a mutated run, a Python test stopped while running outweighs a cargo build that was stopped. job_of says once on stderr when it has no job object. docs/testing.md: one line rewrapped.
2026-12-02 05:19:44 +01:00

705 lines
39 KiB
Python

"""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 py_compile
import subprocess
import sys
import tempfile
import time
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from unittest import mock
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 <f>() -> u32 { N }` returns N,
# and a test `fn <name>() { assert_eq!(super::<f>(), 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)
'''
# A cargo whose rustc crashes like an access violation on Windows: always, or on its first call only (a marker file
# beside it), then the stub above.
CRASH_STUB = r'''
import os, runpy, sys
here = os.path.dirname(os.path.abspath(__file__))
mark = os.path.join(here, "crashed")
if __MODE__ == "always" or not os.path.exists(mark):
open(mark, "w").close()
print(" Compiling foo v0.1.0")
print("error: could not compile `foo` (lib test)")
print("")
print("Caused by:")
print(" process didn't exit successfully: `rustc --crate-name foo --edition=2021 src/lib.rs --test` "
"(exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)")
sys.exit(101)
runpy.run_path(os.path.join(here, "cargo_stub.py"), run_name="__main__")
'''
def hang_stub(repo, where):
"""STUB_CARGO that sleeps when value() is 2 and spare() is 5 (Mutation.BASE's second hunk undone alone): before
its `Running` line, as a build that hangs, or after it, as a test that hangs."""
hang = "sys.stdout.flush()\nif fns.get('value') == '2' and fns.get('spare') == '5':\n __import__('time').sleep(120)\n"
text = STUB_CARGO.replace('print(" Running', (hang if where == "build" else "") + 'print(" Running')
text = text.replace("failed = False\n", "failed = False\n" + (hang if where == "test" else ""))
path = os.path.join(repo.tmp.name, f"cargo_hang_{where}.py")
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(text)
return path
class Repo:
def crash_stub(self, mode):
path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py")
with open(path, "w", encoding="utf-8") as f:
f.write(CRASH_STUB.replace("__MODE__", repr(mode)))
return path
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)
# The same test, and once more in a process it starts, as the tests of a command-line tool do.
CHILD_TEST = TEST + (
"\n def test_two_in_a_child(self):\n"
" import subprocess\n"
" tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n"
" code = 'import sys; sys.path.insert(0, sys.argv[1]); import bar; print(bar.two())'\n"
" out = subprocess.run([sys.executable, '-I', '-c', code, tools], capture_output=True, text=True)\n"
" self.assertEqual(out.stdout.strip(), '2')\n")
def test_stale_bytecode_in_the_work_tree_is_never_run(self):
repo = Repo(self)
repo.commit("base", {".gitignore": "__pycache__/\n", "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.CHILD_TEST})
self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green")
# An ignored .pyc of the fixed bar.py left in the work tree (`git clean` keeps ignored files). An unchecked-hash
# .pyc is taken without looking at the source, like a timestamp one whose time and size still match.
tools = os.path.join(repo.dir, ".git", "red-green", "tree", "tools")
src = os.path.join(repo.tmp.name, "bar_fixed.py")
with open(src, "w", encoding="utf-8", newline="\n") as f:
f.write("def two():\n return 2\n")
py_compile.compile(src, cfile=os.path.join(tools, "__pycache__", f"bar.{sys.implementation.cache_tag}.pyc"),
doraise=True, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH)
code, r, _ = repo.run("--no-cargo", "--mutate")
# Read, it would make red pass in both processes and the undone fix not caught.
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual(r["rows"]["red_to_green"], ["tests/test_bar.py::test_bar.T.test_two",
"tests/test_bar.py::test_bar.T.test_two_in_a_child"])
self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")])
def test_bytecode_it_cannot_remove_stops_the_run_with_the_tree_put_back(self):
repo = Repo(self)
repo.commit("base", {".gitignore": "__pycache__/\n", "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})
self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green")
tree = os.path.join(repo.dir, ".git", "red-green", "tree")
cache = os.path.join(tree, "tools", "__pycache__")
os.makedirs(cache, exist_ok=True)
block_removal(self, cache)
code, r, err = repo.run("--no-cargo")
self.assertEqual((code, r), (2, None), err)
self.assertIn("cannot remove", err)
self.assertIn(os.path.join("tools", "__pycache__"), err)
# The red side had begun: the tree is back on the base all the same.
status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout
self.assertEqual(status, "")
def link_dir(test, link, target):
"""A directory junction on Windows (no privilege needed), a symbolic link elsewhere; removed at the end of `test`
before its temporary folder, so that the folder's cleanup does not go through it."""
if os.name == "nt":
subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True)
test.addCleanup(os.rmdir, link)
else:
os.symlink(target, link, target_is_directory=True)
test.addCleanup(os.unlink, link)
def deny_listing(test, folder):
"""Takes away the right to list `folder` (a deny entry for Everyone on Windows, mode 0 elsewhere) until the end of
`test`."""
if os.name == "nt":
subprocess.run(["icacls", folder, "/deny", "*S-1-1-0:(RD)"], check=True, capture_output=True)
test.addCleanup(subprocess.run, ["icacls", folder, "/remove:d", "*S-1-1-0"], check=True, capture_output=True)
else:
if os.geteuid() == 0:
test.skipTest("root lists any folder")
os.chmod(folder, 0)
test.addCleanup(os.chmod, folder, 0o700)
def block_removal(test, folder):
"""Keeps `folder` from being removed until the end of `test`: a file in it held open on Windows, the folder
read-only elsewhere."""
path = os.path.join(folder, "held.pyc")
if os.name == "nt":
held = open(path, "wb")
test.addCleanup(held.close)
else:
if os.geteuid() == 0:
test.skipTest("root removes any file")
open(path, "wb").close()
os.chmod(folder, 0o500)
test.addCleanup(os.chmod, folder, 0o700)
class DropBytecode(unittest.TestCase):
def setUp(self):
tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True)
self.addCleanup(tmp.cleanup)
self.tree, self.outside = os.path.join(tmp.name, "tree"), os.path.join(tmp.name, "outside")
for folder in (os.path.join(self.tree, "tools", "__pycache__"), os.path.join(self.outside, "__pycache__")):
os.makedirs(folder)
with open(os.path.join(folder, "x.pyc"), "wb") as f:
f.write(b"x")
def check(self):
rg.drop_bytecode(Path(self.tree))
self.assertFalse(os.path.exists(os.path.join(self.tree, "tools", "__pycache__")))
self.assertTrue(os.path.isfile(os.path.join(self.outside, "__pycache__", "x.pyc")))
def test_a_link_out_of_the_tree_is_not_followed(self):
link_dir(self, os.path.join(self.tree, "tools", "link"), self.outside)
self.check()
def test_a_link_named_pycache_is_left_alone(self):
link_dir(self, os.path.join(self.tree, "__pycache__"), os.path.join(self.outside, "__pycache__"))
self.check()
def test_a_folder_it_cannot_list_is_skipped(self):
locked = os.path.join(self.tree, "locked")
os.makedirs(os.path.join(locked, "__pycache__"))
deny_listing(self, locked)
self.check()
@unittest.skipUnless(os.name == "nt", "job objects are Windows'")
class Job(unittest.TestCase):
def test_a_job_object_that_cannot_be_joined_is_said_once(self):
err = io.StringIO()
with mock.patch.object(rg._KERNEL32, "AssignProcessToJobObject", return_value=0), \
mock.patch.object(rg, "_JOB_WARNED", False, create=True), redirect_stderr(err):
runs = [rg.run_output([sys.executable, "-c", "print(1)"], Path(ROOT), timeout=60) for _ in range(2)]
self.assertEqual([(code, out.strip()) for code, out in runs], [(0, "1"), (0, "1")])
self.assertEqual(err.getvalue().count("no Windows job object"), 1, err.getvalue())
class Mutation(unittest.TestCase):
# Two code changes far enough apart to be two hunks: the tested one and one no test looks at.
BASE = ("pub fn value() -> u32 {\n 1\n}\n\n" + "".join(f"// padding line {i}\n" for i in range(10))
+ "\npub fn spare() -> u32 {\n 5\n}\n" + LIB[LIB.index("\n#[cfg(test)]"):])
def test_each_code_hunk_undone_alone_is_caught_or_not(self):
repo = Repo(self)
repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
"d3d12/crates/foo/src/lib.rs": self.BASE})
repo.git("switch", "-q", "-c", "pr")
repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace(
" 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);",
"fn value_is_two() {\n assert_eq!(super::value(), 2);")})
code, r, _ = repo.run("--mutate")
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "not caught")])
text = rg.report(r)
self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 not caught", text)
self.assertIn("d3d12/crates/foo/src/lib.rs:17: not caught", text)
# The worktree is back on the base afterwards: the mutations left nothing behind.
tree = os.path.join(repo.dir, ".git", "red-green", "tree")
status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout
self.assertEqual(status, "")
def test_a_cargo_run_that_hangs_is_stopped_and_said_where(self):
repo = Repo(self)
repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
"d3d12/crates/foo/src/lib.rs": self.BASE})
repo.git("switch", "-q", "-c", "pr")
repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace(
" 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);",
"fn value_is_two() {\n assert_eq!(super::value(), 2);")})
# A test binary that hangs is caught; a build that hangs (no `Running` line yet) is no answer.
for where, result in (("test", "caught by timeout"), ("build", "timed out building")):
_code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where))
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where)
def test_a_test_stopped_running_outweighs_a_build_stopped(self):
# Undone alone, the second hunk makes cargo hang in its build and a Python test hang while running: the hunk
# is caught by timeout, since a test did hang.
watch = ("import os, time, unittest\n\n\nclass T(unittest.TestCase):\n def test_lib(self):\n"
" root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n"
" with open(os.path.join(root, 'd3d12', 'crates', 'foo', 'src', 'lib.rs'), encoding='utf-8') as f:\n"
" text = f.read()\n"
" if ' 2\\n' in text and ' 5\\n' in text:\n"
" time.sleep(120)\n")
repo = Repo(self)
repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
"d3d12/crates/foo/src/lib.rs": self.BASE})
repo.git("switch", "-q", "-c", "pr")
repo.commit("fix", {"tests/test_watch.py": watch,
"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace(
" 5\n", " 6\n").replace(
"fn value_is_one() {\n assert_eq!(super::value(), 1);",
"fn value_is_two() {\n assert_eq!(super::value(), 2);")})
_code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, "build"))
self.assertEqual(r["verdict"], "red then green", r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "caught by timeout")])
def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self):
# The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the
# other test. Neither is mutated; only the fix is.
spare_test = "\n #[test]\n fn spare_is_five() {\n assert_eq!(super::spare(), 5);\n }\n"
base = ("pub fn value() -> u32 {\n 1\n}\n\npub fn spare() -> u32 {\n 5\n}\n"
+ LIB[LIB.index("\n#[cfg(test)]"):LIB.rindex("}")]
+ "".join(f" // padding line {i}\n" for i in range(10)) + spare_test + "}\n")
repo = Repo(self)
repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n',
"d3d12/crates/foo/src/lib.rs": base})
repo.git("switch", "-q", "-c", "pr")
repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": base.replace(" 1\n", " 2\n").replace(spare_test, "")
.replace("fn value_is_one() {\n assert_eq!(super::value(), 1);",
"fn value_is_two() {\n assert_eq!(super::value(), 2);")})
code, r, _ = repo.run("--mutate")
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")])
def test_a_python_fix_undone_is_caught(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": Python.TEST})
code, r, _ = repo.run("--no-cargo", "--mutate")
self.assertEqual(r["verdict"], "red then green", r)
self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")])
# tools/bar.py with two hunks far apart, two() at line 2 (the fix) and settled() at line 15; a test of two().
BAR = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10))
+ "\ndef settled():\n return False\n")
def bar_repo(self, body, base_files=None):
test = ("import os, subprocess, sys, unittest\n"
"tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n"
"sys.path.insert(0, tools)\n"
"import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + body
+ " self.assertEqual(bar.two(), 2)\n")
repo = Repo(self)
repo.commit("base", {"tools/bar.py": self.BAR, **(base_files or {})})
repo.git("switch", "-q", "-c", "pr")
repo.commit("fix", {"tools/bar.py": self.BAR.replace("return 1", "return 2").replace("False", "True"),
"tests/test_bar.py": test})
return repo
def test_a_mutated_run_that_hangs_is_caught_by_timeout(self):
# Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does
# not hang there.
repo = self.bar_repo(" if bar.two() == 2 and not bar.settled():\n"
" subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n")
start = time.monotonic()
_code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5")
self.assertEqual(r["verdict"], "red then green", r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "caught by timeout")])
self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 caught by timeout", rg.report(r))
# The run did not wait for the sleeping process.
self.assertLess(time.monotonic() - start, 60)
def test_a_process_left_behind_does_not_hold_a_mutated_run(self):
# Undone alone, the fix makes the test leave a process behind that outlives it with its output; the test still
# fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. The process left
# behind is stopped then: 5 s later, it would write a file beside the work tree. (Kept in T, so that no
# ResourceWarning cuts the test's line in the verbose output.)
repo = self.bar_repo(
" if bar.two() != 2 and bar.settled():\n"
" mark = os.path.join(os.path.dirname(os.path.dirname(tools)), 'left-behind')\n"
" T.left = subprocess.Popen([sys.executable, '-c', 'import sys, time; time.sleep(5); "
"open(sys.argv[1], \"w\").close()', mark])\n")
start = time.monotonic()
_code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "20")
self.assertEqual(r["verdict"], "red then green", r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")])
self.assertLess(time.monotonic() - start, 20)
time.sleep(6) # it started before the run ended
self.assertFalse(os.path.exists(os.path.join(repo.dir, ".git", "red-green", "left-behind")))
def test_a_test_that_dirties_the_tree_does_not_change_the_next_hunk(self):
# When it finds two() wrong, the test writes into a tracked file that it also checks. Each mutation starts from
# the green tree, so the second hunk (settled(), which no test looks at) is not caught for that.
repo = self.bar_repo(" flag = os.path.join(tools, 'flag.txt')\n"
" if bar.two() != 2:\n"
" with open(flag, 'w', encoding='utf-8', newline='\\n') as f:\n"
" f.write('dirty\\n')\n"
" with open(flag, encoding='utf-8') as f:\n"
" self.assertEqual(f.read(), 'clean\\n')\n", {"tools/flag.txt": "clean\n"})
code, r, _ = repo.run("--no-cargo", "--mutate")
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")])
tree = os.path.join(repo.dir, ".git", "red-green", "tree")
status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout
self.assertEqual(status, "")
def test_hunks_past_mutate_max_are_listed_as_not_tried(self):
base = "".join(f"def f{n}():\n return 1\n" + "# padding\n" * 4 for n in range(1, 5))
test = Python.TEST.replace("bar.two(), 2", "bar.f1(), 2")
repo = Repo(self)
repo.commit("base", {"tools/bar.py": base})
repo.git("switch", "-q", "-c", "pr")
repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2"), "tests/test_bar.py": test})
code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-max", "2")
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (8, "not caught")])
self.assertEqual(r["mutations_skipped"], [{"file": "tools/bar.py", "line": 14},
{"file": "tools/bar.py", "line": 20}])
self.assertIn("not tried, past --mutate-max: tools/bar.py:14, tools/bar.py:20", rg.report(r))
def test_a_test_only_pull_request_has_nothing_to_undo(self):
repo = Repo(self)
repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"})
repo.git("switch", "-q", "-c", "pr")
repo.commit("test", {"tests/test_bar.py": Python.TEST})
code, r, _ = repo.run("--no-cargo", "--mutate")
# The verdict and exit code are those of any test that passes on both.
self.assertEqual((code, r["verdict"]), (1, "no red"), r)
self.assertEqual(r["mutations"], [])
self.assertEqual(r["mutations_not_run"], "nothing to undo: the diff changes no Rust or Python code outside its "
"tests")
self.assertIn("mutations: nothing to undo: the diff changes no Rust or Python code outside its tests",
rg.report(r))
def test_code_only_in_added_files_has_nothing_to_undo_in_the_files_it_modifies(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": Python.TEST})
code, r, _ = repo.run("--no-cargo", "--mutate")
self.assertEqual((code, r["verdict"]), (1, "red does not build"), r)
self.assertEqual((r["mutations"], r["added_not_mutated"]), ([], ["tools/bar.py"]))
text = rg.report(r)
self.assertIn("mutations: nothing to undo in the files it modifies: its code changes are in files it adds", text)
self.assertIn("not mutated, added by the pull request: tools/bar.py", text)
def test_code_with_no_test_gone_red_is_not_mutated_and_said_so(self):
repo = Repo(self)
repo.commit("base", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 3\n"})
repo.git("switch", "-q", "-c", "pr")
repo.commit("change", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 4\n",
"tests/test_bar.py": Python.TEST})
code, r, _ = repo.run("--no-cargo", "--mutate")
self.assertEqual((code, r["verdict"]), (1, "no red"), r)
self.assertEqual(r["mutations"], [])
self.assertIn("mutations: not run: no test went red then green", rg.report(r))
def test_files_the_pull_request_adds_are_listed_as_not_mutated(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/helper.py": "def value():\n return 2\n",
"tools/bar.py": "from helper import value\n\n\ndef two():\n return value()\n",
"tests/test_bar.py": Python.TEST})
code, r, _ = repo.run("--no-cargo", "--mutate")
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]],
[("tools/bar.py", "caught"), ("tools/bar.py", "caught")])
# helper.py holds the change and is never undone: the report says so rather than read as full coverage.
self.assertEqual(r["added_not_mutated"], ["tools/helper.py"])
self.assertIn("not mutated, added by the pull request: tools/helper.py", rg.report(r))
def test_mutate_options_are_checked(self):
for args, why in ((["--mutate", "--mutate-max", "0"], "--mutate-max"),
(["--mutate", "--mutate-timeout", "0"], "--mutate-timeout"),
(["--mutate", "--mutate-timeout", "nan"], "--mutate-timeout"),
(["--mutate", "--mutate-timeout", "inf"], "--mutate-timeout"),
(["--mutate-max", "3"], "--mutate"), (["--mutate-timeout", "60"], "--mutate")):
err = io.StringIO()
with redirect_stderr(err), self.assertRaises(SystemExit) as stop:
rg.main(["pr", "--no-fetch", *args])
self.assertEqual(stop.exception.code, 2, args)
self.assertIn(why, err.getvalue().splitlines()[-1], args)
def test_no_mutation_without_the_option(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": Python.TEST})
_code, r, _ = repo.run("--no-cargo")
self.assertIsNone(r["mutations"])
self.assertNotIn("mutations", rg.report(r))
class CompilerCrash(unittest.TestCase):
def fixed_repo(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);")})
return repo
def test_a_compiler_that_crashes_once_is_run_again(self):
repo = self.fixed_repo()
code, r, err = repo.run("--cargo", repo.crash_stub("once"))
self.assertEqual((code, r["verdict"]), (0, "red then green"), r)
self.assertEqual(r["red"]["rerun_after"], "0xc0000005, STATUS_ACCESS_VIOLATION")
self.assertIsNone(r["red"]["compiler_crashed"])
self.assertIn("the compiler crashed (0xc0000005, STATUS_ACCESS_VIOLATION), running again", err)
def test_a_compiler_that_crashes_twice_is_not_a_build_error(self):
repo = self.fixed_repo()
code, r, _ = repo.run("--cargo", repo.crash_stub("always"))
self.assertEqual((code, r["verdict"]), (1, "compiler crashed"), r)
self.assertEqual(r["red"]["compiler_crashed"], "0xc0000005, STATUS_ACCESS_VIOLATION")
self.assertEqual(r["red"]["no_build"], [])
self.assertIn("red: the compiler crashed twice", rg.report(r))
def test_what_counts_as_a_crashed_compiler(self):
crashed = [
" process didn't exit successfully: `C:\\x\\rustc.exe --crate-name a` (exit code: 0xc00000fd, STATUS_STACK_OVERFLOW)",
" process didn't exit successfully: `C:\\t\\build\\a-1\\build-script-build` (exit code: 0xc0000409)",
"error: internal compiler error: compiler/rustc_middle/src/ty/mod.rs:1: oops",
"note: the compiler unexpectedly panicked. this is a bug.",
"memory allocation of 1048576 bytes failed",
]
for line in crashed:
self.assertIsNotNone(rg.COMPILER_CRASH.search(line), line)
not_crashed = [
# A test binary that crashes is a test result, and an ordinary failure is a build error.
" process didn't exit successfully: `C:\\t\\debug\\deps\\foo-0123456789abcdef.exe` (exit code: 0xc0000005, STATUS_ACCESS_VIOLATION)",
" process didn't exit successfully: `C:\\x\\rustc.exe --crate-name a` (exit code: 1)",
"error[E0425]: cannot find value `x` in this scope",
]
for line in not_crashed:
self.assertIsNone(rg.COMPILER_CRASH.search(line), line)
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()