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.
This commit is contained in:
TheGeogeo
2026-12-02 05:19:38 +01:00
parent 673ac44a1b
commit bf65aa4505
3 changed files with 137 additions and 22 deletions

View File

@ -164,9 +164,10 @@ python -I scripts/red_green.py <pull request number>
outside the tests and `#[cfg(test)]` code) and runs the tests again. A hunk is `caught` when a test that went red
then green fails, `not caught` when they all still pass, `does not build` when those tests no longer run,
`compiler crashed` when the compiler crashed twice, or `does not apply` when `main` moved those lines since. Each
mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past
--mutate-max` (`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not
change the verdict.
mutation starts from the green tree, reset and cleaned, so what a test writes into the tree changes no other. It
tries at most `--mutate-max` hunks (10) and lists the others as `not tried, past --mutate-max`
(`mutations_skipped` in `--json`). A `not caught` hunk is code no new test looks at; it does not change the
verdict.
- Files the pull request adds are not mutated: undoing one would delete it, which only shows that something uses it.
The report lists them (`not mutated, added by the pull request`), so a fix whose code sits in a new file is not
read as covered. When no hunk is undone, the report says why: `nothing to undo` when the pull request changes no

View File

@ -31,6 +31,7 @@ from __future__ import annotations
import argparse
import json
import math
import os
import re
import shutil
@ -81,25 +82,33 @@ if os.name == "nt":
_KERNEL32.CloseHandle.argtypes = (wintypes.HANDLE,)
_JOB_WARNED = False # job_of() says once that it has no job object
def job_of(p: subprocess.Popen):
"""On Windows, a job object holding `p`, or None. The processes `p` starts join it, and closing it stops every
process in it (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE): a process that outlives `p` is stopped with the job, where
`taskkill /T` no longer finds it once `p` has ended. A process `p` starts before it joins (its first instants)
stays out."""
stays out. Without one, it says so on stderr once."""
global _JOB_WARNED
job = _KERNEL32.CreateJobObjectW(None, None)
if not job:
return None
limits = _JobLimits(limit_flags=0x2000) # JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
handle = _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA
handle = job and _KERNEL32.OpenProcess(0x0101, False, p.pid) # PROCESS_TERMINATE | PROCESS_SET_QUOTA
# 9: JobObjectExtendedLimitInformation
joined = (handle and _KERNEL32.SetInformationJobObject(job, 9, ctypes.byref(limits), ctypes.sizeof(limits))
and _KERNEL32.AssignProcessToJobObject(job, handle))
error = ctypes.get_last_error()
if handle:
_KERNEL32.CloseHandle(handle)
if not joined:
if joined:
return job
if job:
_KERNEL32.CloseHandle(job)
return None
return job
if not _JOB_WARNED:
_JOB_WARNED = True
print(f"red_green: no Windows job object for the mutated runs (error {error}): a process one leaves behind "
"is not stopped", file=sys.stderr)
return None
def stop_all(p: subprocess.Popen, job) -> None:
@ -424,18 +433,26 @@ def drop_bytecode(tree: Path) -> None:
time and size it records still match (an undone change of the same size within the same second) or when it is an
unchecked-hash one, and `git clean` keeps them (they are ignored). An option of the run's own Python, such as
`-X pycache_prefix`, would not reach the processes its tests start. Links (symbolic links, and junctions, which
`is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's."""
`is_symlink()` does not see) are neither followed nor removed: what they point at is not the tree's. A folder it
cannot list is skipped: Python cannot import from it either. A `__pycache__` it cannot remove stops the run."""
folders, todo = [], [tree]
while todo:
with os.scandir(todo.pop()) as entries:
for e in entries:
if not e.is_dir(follow_symlinks=False) or e.is_symlink():
continue
if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT:
continue # a junction (Windows)
(folders if e.name == "__pycache__" else todo).append(e.path)
try:
with os.scandir(todo.pop()) as entries:
for e in entries:
if not e.is_dir(follow_symlinks=False) or e.is_symlink():
continue
if getattr(e.stat(follow_symlinks=False), "st_file_attributes", 0) \
& stat.FILE_ATTRIBUTE_REPARSE_POINT:
continue # a junction (Windows)
(folders if e.name == "__pycache__" else todo).append(e.path)
except OSError:
continue
for folder in folders:
shutil.rmtree(folder)
try:
shutil.rmtree(folder)
except OSError as e:
raise Failure(f"cannot remove {folder}, whose bytecode could run instead of the code: {e}") from None
def python_tests(tree: Path, files: list[str], timeout: float | None) -> dict:
@ -473,8 +490,10 @@ def side(tree: Path, crates: list[str], py_files: list[str], cargo: str, target:
result["tests"].update(part["tests"])
if part["no_build"]:
result["no_build"].append(part["no_build"])
for key in ("compiler_crashed", "rerun_after", "timed_out"):
for key in ("compiler_crashed", "rerun_after"):
result[key] = result[key] or part.get(key)
if part.get("timed_out") and result["timed_out"] != "running": # a test stopped running outweighs a build
result["timed_out"] = part["timed_out"]
return result
@ -588,8 +607,8 @@ def main(argv: list[str] | None = None) -> int:
p.error("--mutate-max and --mutate-timeout go with --mutate")
if a.mutate_max is not None and a.mutate_max < 1:
p.error("--mutate-max must be 1 or more")
if a.mutate_timeout is not None and not a.mutate_timeout > 0: # NaN too
p.error("--mutate-timeout must be more than 0 seconds")
if a.mutate_timeout is not None and not (math.isfinite(a.mutate_timeout) and a.mutate_timeout > 0):
p.error("--mutate-timeout must be a number of seconds above 0")
a.mutate_max = 10 if a.mutate_max is None else a.mutate_max
a.mutate_timeout = 600.0 if a.mutate_timeout is None else a.mutate_timeout
try:
@ -615,6 +634,14 @@ def main(argv: list[str] | None = None) -> int:
os.close(fd)
try:
result = check(repo, work, a, base, base_commit, head, merge_base)
except Failure:
# Stopped midway (a side, a mutation): the tree goes back on the base, as at the end of a run.
if (work / "tree" / ".git").exists():
try:
checkout(repo, work / "tree", base_commit)
except Failure:
pass
raise
finally:
lock.unlink(missing_ok=True)
except Failure as e:

View File

@ -10,6 +10,7 @@ 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"))
@ -280,6 +281,24 @@ class Python(unittest.TestCase):
"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`
@ -292,6 +311,34 @@ def link_dir(test, link, target):
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)
@ -315,6 +362,23 @@ class DropBytecode(unittest.TestCase):
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.
@ -353,6 +417,28 @@ class Mutation(unittest.TestCase):
_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.
@ -514,6 +600,7 @@ class Mutation(unittest.TestCase):
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: