Merge origin/main into carry/1346

This commit is contained in:
MoonEyes
2026-12-02 11:51:40 +01:00
11 changed files with 1924 additions and 87 deletions

View File

@ -322,6 +322,46 @@ class ShortsTest(unittest.TestCase):
shorts._write_catalog(path, [])
self.assertTrue(len(chmod_calls) > 0)
def test_catalog_collision_with_input_bank_rejected(self):
bank = os.path.join(self.tmp.name, "shorts.csv")
with open(bank, "wb") as f:
f.write(b"original input bank data")
out = self.tmp.name
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
rc = shorts.main([bank, out, "--jobs", "1"])
self.assertEqual(rc, 2)
self.assertIn("catalog would overwrite the input bank", err.getvalue())
self.assertEqual(len(err.getvalue().splitlines()), 1)
with open(bank, "rb") as f:
self.assertEqual(f.read(), b"original input bank data")
def test_catalog_collision_with_bank_export_directory_rejected(self):
bank = os.path.join(self.tmp.name, "shorts.csv.awc")
with open(bank, "wb") as f:
f.write(b"bank data")
out = self.tmp.name
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
rc = shorts.main([bank, out, "--jobs", "1"])
self.assertEqual(rc, 2)
self.assertIn("catalog would collide with bank export directory", err.getvalue())
self.assertEqual(len(err.getvalue().splitlines()), 1)
with open(bank, "rb") as f:
self.assertEqual(f.read(), b"bank data")
def test_catalog_collision_refusal_creates_no_output_folder(self):
src = os.path.join(self.tmp.name, "src")
os.makedirs(src)
out = os.path.join(self.tmp.name, "out")
bank = os.path.join(src, "shorts.csv.awc")
with open(bank, "wb") as f:
f.write(b"bank data")
# The bank exports to out/shorts.csv, the catalog's own path: refused before out/ exists.
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err:
rc = shorts.main([bank, out, "--jobs", "1"])
self.assertEqual(rc, 2)
self.assertIn("catalog would collide with bank export directory", err.getvalue())
self.assertFalse(os.path.exists(out))
if __name__ == "__main__":
unittest.main(verbosity=2)

View File

@ -1,6 +1,9 @@
"""tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's
formats (no game data). The contract test checks that those formats are still in the runtime's source."""
import contextlib
import csv
import datetime as dt
import io
import json
import os
import re
@ -50,8 +53,14 @@ class Fake:
self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1")
t += gap
def memory(self, t, private, used, budget=8000, left=3000, shared=500):
"""The runtime's video memory line and memory line, as a diagnostics build writes them every 5 s."""
def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0, reaper=0):
"""The runtime's video memory line, census line and memory line, as a diagnostics build writes them every 5 s."""
self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let "
f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired "
f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not "
f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread); 0 let go by the thread done "
f"with them instead, since the start, the reaper thread's line holding LEONIDA_REAPER_LIMIT=0 or "
f"more (0: no bound)")
self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory "
f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, "
f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could "
@ -66,6 +75,11 @@ class Fake:
self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title")
self.event(t + 0.5, "game_exited", exit_code=exit_code)
def state(self):
"""What the supervisor reads during the run (`game_gate.py state`)."""
self.summarize()
return game_gate.state(game_gate.Run(self.dir))
def summarize(self):
self.log.sort(key=lambda l: l[:27])
files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n",
@ -235,12 +249,177 @@ class Measures(unittest.TestCase):
self.assertEqual(m["vram_over_budget_s"], 185.0)
self.assertEqual(m["shared_in_use_max_mb"], 563)
def memory_run(self, limits, rows):
"""A run in the world with memory lines every 5 s from 70 s: rows of (private, video in use, PC left)."""
f = Fake()
f.meta["memory_stop"] = limits
f.event(1, "game", pid=1)
f.frames(10, 70, 60.0, 13)
f.frames(70, 70 + 5 * len(rows), 30.0, 4000)
for i, (private, used, left) in enumerate(rows):
f.memory(70 + 5 * i, private, used, budget=8000, left=left)
return f
def test_the_memory_stop_asks_for_a_stop_past_each_limit(self):
limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60}
calm = [(24000, 7000, 3000)] * 10
cases = {
"private bytes 31000 MB, over 30000 MB": calm + [(31000, 7000, 3000)],
"the PC had under 200 MB left to commit for 25 s": calm + [(24000, 7000, 150)] * 6,
# Exactly 20 s under the floor (five lines 5 s apart) is enough: the floor's boundary, as 60 s is the
# video memory's.
"the PC had under 200 MB left to commit for 20 s": calm + [(24000, 7000, 150)] * 5,
"video memory over its budget for 60 s": calm + [(24000, 9000, 3000)] * 13,
}
for why, rows in cases.items():
self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why)
# Under each limit, at the private limit itself, or not for long enough: no stop.
for rows in (calm, calm + [(30000, 7000, 3000)], calm + [(24000, 7000, 150)] * 4,
calm + [(24000, 9000, 3000)] * 12):
self.assertIsNone(self.memory_run(limits, rows).state()["memory_stop"])
# 0 turns a limit off, and a run.json without limits (an older gate) never stops for memory.
off = {"private_max_mb": 0, "commit_left_min_mb": 0, "over_budget_s": 0}
self.assertIsNone(self.memory_run(off, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"])
self.assertIsNone(self.memory_run(None, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"])
# A negative limit is off too, not a stop at the first line (`-StopOverBudgetSeconds -1` stopped every run).
for name in limits:
self.assertIsNone(self.memory_run(dict(limits, **{name: -1}), calm).state()["memory_stop"], name)
def test_a_run_stopped_for_memory_fails_with_its_reason(self):
limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60}
f = self.memory_run(limits, [(24000, 7000, 3000)] * 10 + [(31000, 7000, 3000)])
f.event(121, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB")
f.log.append(f"{stamp(121.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title")
f.event(121.5, "game_exited", exit_code=0)
s = f.summarize()
self.assertEqual(s["verdict"]["result"], "FAIL")
self.assertEqual(s["verdict"]["reasons"], ["memory_stop"])
self.assertEqual(s["stop"]["reason"], "memory")
self.assertEqual(s["stop"]["memory_why"], "private bytes 31000 MB, over 30000 MB")
self.assertEqual(s["memory"]["stop_limits"], limits)
# Stopped before the world (seen in a real run with a low cap): the memory stop is the one reason.
f = Fake()
f.meta["memory_stop"] = limits
f.event(1, "game", pid=1)
f.frames(10, 80, 60.0, 13)
f.memory(75, 31000, 4000)
f.event(80, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB")
f.event(83, "game_exited", exit_code=0)
self.assertEqual(f.summarize()["verdict"]["reasons"], ["memory_stop"])
def test_the_memory_series_and_a_pile_ups_slope(self):
f = passing()
for t in range(10, 390, 5):
# From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows.
grown = max(0, t - 70) // 5
f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown)
s = f.summarize()
m = s["memory"]
self.assertEqual(m["private_mb_per_min_in_world"], 120.0)
self.assertEqual((m["reaper_queue_max"], m["reaper_queue_max_at_s"]), (100 * 63, 385.0))
self.assertEqual(m["waiting_objects_max"], 3)
self.assertEqual(m["series"], "memory.csv")
# `summary` writes the series beside summary.json, one row per memory line, numbers only.
with contextlib.redirect_stdout(io.StringIO()):
game_gate.main(["game_gate.py", "summary", f.dir])
with open(os.path.join(f.dir, "memory.csv"), encoding="utf-8") as fh:
rows = list(csv.DictReader(fh))
self.assertEqual(len(rows), 76)
self.assertEqual(tuple(rows[0]), game_gate.SERIES_COLUMNS)
self.assertEqual(rows[-1]["private_mb"], "20630")
self.assertEqual(rows[-1]["reaper_queue"], "6300")
self.assertEqual(rows[-1]["vram_in_use_mb"], "7000")
# The same bytes on every machine: LF line ends, never CRLF.
with open(os.path.join(f.dir, "memory.csv"), "rb") as fh:
self.assertNotIn(b"\r", fh.read())
def summary_files(self, f):
"""`game_gate.py summary` on the folder: (exit code, summary.json, memory.csv rows or None, stderr)."""
f.summarize()
err = io.StringIO()
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err):
code = game_gate.main(["game_gate.py", "summary", f.dir])
with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh:
s = json.load(fh)
path = os.path.join(f.dir, "memory.csv")
rows = None
if os.path.isfile(path):
with open(path, encoding="utf-8") as fh:
rows = list(csv.DictReader(fh))
return code, s, rows, err.getvalue()
def test_the_series_takes_the_lines_within_2_s_of_each_memory_line(self):
f = passing()
f.memory(100, 20000, 7000, waiting=3, reaper=40) # the three lines at once, as the runtime writes them
f.memory(200, 21000, 7500, waiting=5, reaper=50)
census, video, memory = f.log[-3:]
# The video memory line 2 s before (taken), the census line 2.5 s after (too far: empty cells).
f.log[-3:] = [census.replace(stamp(200), stamp(202.5)), video.replace(stamp(200), stamp(198)), memory]
f.memory(300, 22000, 8000)
f.log[-3:] = f.log[-1:] # a memory line alone
_, _, rows, _ = self.summary_files(f)
got = [(r["t_s"], r["vram_in_use_mb"], r["shared_in_use_mb"], r["waiting_objects"], r["reaper_queue"])
for r in rows]
self.assertEqual(got, [("100.0", "7000", "500", "3", "40"), ("200.0", "7500", "500", "", ""),
("300.0", "", "", "", "")])
def test_the_slope_counts_the_world_up_to_the_stop(self):
f = Fake()
f.event(1, "game", pid=1)
f.frames(10, 70, 60.0, 13)
f.frames(70, 420, 50.0, 4000)
for t in range(70, 420, 5):
# 120 MB a minute in the world, then a jump while the title ends after the stop request (390 s).
f.memory(t, 20000 + 2 * (t - 70) if t <= 390 else 40000, 7000)
f.event(390, "stop_requested", reason="target")
f.event(420, "game_exited", exit_code=0)
self.assertEqual(f.summarize()["memory"]["private_mb_per_min_in_world"], 120.0)
# Fewer than 3 memory lines in the world: no slope.
f = passing()
for t in (40, 50, 60, 100, 200):
f.memory(t, 20000 + t, 7000)
self.assertIsNone(f.summarize()["memory"]["private_mb_per_min_in_world"])
def test_a_series_it_cannot_write_still_leaves_the_summary(self):
# memory.csv held by another program: the summary is written all the same, with no series named.
f = passing()
for t in range(70, 390, 5):
f.memory(t, 20000, 7000)
os.makedirs(os.path.join(f.dir, "memory.csv")) # opening it to write fails, as a locked file does
code, s, _, err = self.summary_files(f)
self.assertEqual(code, 0)
self.assertEqual(s["verdict"]["result"], "PASS")
self.assertIsNone(s["memory"]["series"])
self.assertEqual(s["memory"]["lines"], 64)
self.assertIn("memory.csv not written or removed", err)
def test_a_build_without_memory_lines_gives_no_memory_peaks(self):
m = passing().summarize()["memory"]
f = passing()
m = f.summarize()["memory"]
self.assertIsNone(m["source"])
self.assertEqual(m["lines"], 0)
self.assertIsNone(m["private_max_mb"])
self.assertIsNone(m["vram_in_use_max_mb"])
self.assertIsNone(m["series"])
self.assertIsNone(m["reaper_queue_max"])
self.assertIsNone(m["private_mb_per_min_in_world"])
# And `summary` writes no series file: not even a header alone.
with contextlib.redirect_stdout(io.StringIO()):
game_gate.main(["game_gate.py", "summary", f.dir])
self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv")))
def test_a_folder_summarized_again_without_memory_lines_keeps_no_old_series(self):
# A memory.csv from an earlier summary, and a log that has no memory lines now: the old rows must not sit
# beside `series: null`.
f = passing()
f.summarize()
with open(os.path.join(f.dir, "memory.csv"), "w", encoding="utf-8", newline="\n") as fh:
fh.write(",".join(game_gate.SERIES_COLUMNS) + "\n70.0,1000,500,15000,4000,8000,7000,500,0,0\n")
with contextlib.redirect_stdout(io.StringIO()):
game_gate.main(["game_gate.py", "summary", f.dir])
with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh:
self.assertIsNone(json.load(fh)["memory"]["series"])
self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv")))
def test_without_present_lines_the_frame_lines_give_the_rate(self):
f = Fake()
@ -317,6 +496,67 @@ class Script(unittest.TestCase):
with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
self.assertEqual(f.readline().strip(), "#Requires -Version 7.0")
def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self):
with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
text = f.read()
for name in ("StopPrivateMB", "StopCommitLeftMB", "StopOverBudgetSeconds"):
self.assertIn(f"[int]${name} = ", text)
# `start` rebuilds the command line of the detached `run`: a limit left out would be lost there.
self.assertIn(f"'-{name}'; ${name}", text)
self.assertIn("memory_stop = [ordered]@{", text)
# The private default follows the PC's memory too, not only its commit limit (a large page file).
self.assertIn("TotalPhysicalMemory", text)
self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text)
# What one poll of the supervisor reads (`game_gate.py state`, a STOP file, the minutes since the start) and the
# reason it stops the run for, with -WorldSeconds 300 and -MaxMinutes 45.
POLLS = [
# The world time reached in the same poll as a memory limit: a measurement, not a memory stop.
({"relaunched": False, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
"target"),
({"relaunched": False, "world_s": 295.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
"memory"),
({"relaunched": True, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20,
"relaunched"),
({"relaunched": False, "world_s": 100.0, "memory_stop": "video memory over its budget for 60 s"}, True, 20,
"memory"),
({"relaunched": False, "world_s": 100.0, "memory_stop": None}, True, 20, "stop_file"),
# A memory limit at the time limit: the memory stop names the real reason.
({"relaunched": False, "world_s": 100.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 45,
"memory"),
({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"),
({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"),
]
def test_a_poll_stops_for_the_target_before_the_memory_stop(self):
# The supervisor's own function is taken out of the script and put to PowerShell 7 with each poll above.
with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f:
text = f.read()
self.assertIn("$stopReason = Get-StopReason -Poll $state ", text)
self.assertIn("-TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes", text)
self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function
# The memory stop's sentence goes into the stop_requested event (`stop.memory_why`).
self.assertIn("if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }", text)
pwsh = shutil.which("pwsh")
if not pwsh:
self.skipTest("no PowerShell 7 here")
script = ("$ErrorActionPreference = 'Stop'; "
"$language = 'System.Management.Automation.Language'; "
"$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); "
"$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and "
"$args[0].Name -eq 'Get-StopReason' }, $true); "
"if (-not $fn) { throw 'the gate has no Get-StopReason' }; "
". ([scriptblock]::Create($fn.Extent.Text)); "
"foreach ($p in ($env:GATE_POLLS | ConvertFrom-Json)) "
"{ $r = Get-StopReason -Poll $p[0] -StopFile $p[1] -Minutes $p[2] -TargetSeconds 300 "
"-LimitMinutes 45; if ($r) { $r } else { 'none' } }")
env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"),
GATE_POLLS=json.dumps([p[:3] for p in self.POLLS]))
done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True,
text=True, timeout=120, env=env)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertEqual(done.stdout.split(), [p[3] for p in self.POLLS])
def test_no_variable_takes_a_parameters_name_in_another_case(self):
# PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name,
# and the stop could not wait for it.

View File

@ -1383,5 +1383,351 @@ class HostClassesTest(unittest.TestCase):
self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset())
class TestExportForwarders(unittest.TestCase):
def inspect_buf(self, buf: bytes) -> dict:
return pe_inspect._inspect_exports(pe_inspect.PeImage(buf))
def test_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarder(self):
"""The directory is [begin, end): an RVA equal to the end is past it, as in runtime/src/pe_loader.cpp."""
end = 0x1800 # the export directory of with_exports() is [0x1700, 0x1800)
data = with_exports([end], {0: "AtTheEnd"}, base=1)
exp = self.inspect_buf(data)
self.assertEqual(exp["forwarders"], {})
self.assertEqual(exp["exports"], ["AtTheEnd"])
last = with_exports([end - 1], {0: "LastByte"}, base=1)
self.assertIn("LastByte", self.inspect_buf(last)["forwarders"])
def test_case1_normal_exports_and_unused_slots(self):
"""Case 1: Normal code exports + unused zero-RVA slot skipped (forwarders empty, invalid_export_count 0)."""
data = with_exports([0x1000, 0, 0x1010], {0: "Alpha", 2: "Beta"}, base=1)
exp = self.inspect_buf(data)
self.assertEqual(exp["exports"], ["Alpha", "Beta"])
self.assertEqual(exp["forwarders"], {})
self.assertEqual(exp["invalid_export_count"], 0)
self.assertEqual(exp["invalid_exports"], [])
def test_case2_named_forwarded_export(self):
"""Case 2: Named forwarded export (RVA inside export directory [0x1700, 0x1800))."""
data = with_exports([0x1000, FORWARDER], {0: "NormalFunc", 1: "Sleep"}, base=10)
exp = self.inspect_buf(data)
self.assertEqual(exp["exports"], ["NormalFunc", "Sleep"])
self.assertEqual(exp["forwarders"], {"Sleep": "other.Target"})
self.assertEqual(exp["invalid_export_count"], 0)
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(data)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("(1 forwarded)", md)
self.assertIn("## Forwarded Exports", md)
self.assertIn("| `Sleep` | `other.Target` |", md)
finally:
os.unlink(tmp_path)
def test_case3_ordinal_only_forwarder(self):
"""Case 3: Ordinal-only forwarded export (index not in named)."""
data = with_exports([0x1000, FORWARDER], {0: "Func"}, base=10)
exp = self.inspect_buf(data)
self.assertEqual(exp["exports"], ["Func", "#11"])
self.assertEqual(exp["forwarders"], {"#11": "other.Target"})
self.assertEqual(exp["invalid_export_count"], 0)
def test_case4_aliased_named_forwarders(self):
"""Case 4: Two export names mapping to the same forwarded EAT index."""
data = with_exports([FORWARDER], {0: "AliasA"}, base=1)
buf = bytearray(data)
place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 2,
EXPORT_FUNCS, 0x1C00, 0x1C80))
place(buf, 0x1C00, struct.pack("<II", 0x1D00, 0x1D10))
place(buf, 0x1C80, struct.pack("<HH", 0, 0))
place(buf, 0x1D00, b"AliasA\0")
place(buf, 0x1D10, b"AliasB\0")
exp = self.inspect_buf(bytes(buf))
self.assertEqual(exp["exports"], ["AliasA", "AliasB"])
self.assertEqual(exp["forwarders"], {"AliasA": "other.Target", "AliasB": "other.Target"})
self.assertEqual(exp["invalid_export_count"], 0)
def test_case5_out_of_bounds_export_rva(self):
"""Case 5: Out-of-bounds export RVA (>= size_of_image)."""
data = with_exports([0x3000], {0: "BadFunc"}, base=10)
exp = self.inspect_buf(data)
self.assertEqual(exp["exports"], ["BadFunc"])
self.assertEqual(exp["invalid_export_count"], 1)
self.assertEqual(len(exp["invalid_exports"]), 1)
self.assertEqual(exp["invalid_exports"][0]["symbol"], "BadFunc")
self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_bounds")
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(data)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("INVALID: 1 invalid: BadFunc (out_of_bounds)", md)
finally:
os.unlink(tmp_path)
def test_case6_unreadable_forwarder_and_error_cap(self):
"""Case 6: Unreadable forwarder string and invalid error cap at <= 5."""
buf = bytearray(build_image())
dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8
struct.pack_into("<II", buf, dir_entry, 0x1700, 0x2000)
place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 1,
EXPORT_FUNCS, 0x1C00, 0x1C80))
place(buf, EXPORT_FUNCS, struct.pack("<I", 0x3500))
place(buf, 0x1C00, struct.pack("<I", 0x1D00))
place(buf, 0x1C80, struct.pack("<H", 0))
place(buf, 0x1D00, b"BrokenFwd\0")
exp = self.inspect_buf(bytes(buf))
self.assertEqual(exp["forwarders"], {"BrokenFwd": "?"})
self.assertEqual(exp["invalid_export_count"], 1)
self.assertEqual(exp["invalid_exports"][0]["reason"], "unreadable_forwarder")
bad_slots = [0x4000 + i * 0x100 for i in range(8)]
bad_names = {i: f"Bad{i}" for i in range(8)}
data_bad = with_exports(bad_slots, bad_names, base=1)
exp_bad = self.inspect_buf(data_bad)
self.assertEqual(exp_bad["invalid_export_count"], 8)
self.assertEqual(len(exp_bad["invalid_exports"]), 5)
def test_case7_combined_forwarder_and_invalid_summary(self):
"""Case 7: DLL with both valid forwarder and invalid export displays both in markdown."""
data = with_exports([0x1000, FORWARDER, 0x3000], {1: "Fwd|Func", 2: "BadFunc"}, base=10)
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(data)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("(1 forwarded; INVALID: 1 invalid: BadFunc (out_of_bounds))", md)
self.assertIn("| `Fwd\\|Func` | `other.Target` |", md)
finally:
os.unlink(tmp_path)
def test_case8_out_of_range_ordinal_and_small_dir_size(self):
"""Case 8: Ordinal index >= functions recorded as invalid, dir_size < 40 returns empty."""
data = with_exports([0x1000], {0: "NormalFunc"}, base=1)
buf = bytearray(data)
# Point the ordinal table to index 5 while NumberOfFunctions is 1
place(buf, 0x1C80, struct.pack("<H", 5))
exp = self.inspect_buf(bytes(buf))
self.assertNotIn("NormalFunc", exp["exports"])
self.assertEqual(exp["exports"], ["#1"])
self.assertEqual(exp["forwarders"], {})
self.assertEqual(exp["invalid_export_count"], 1)
self.assertEqual(len(exp["invalid_exports"]), 1)
self.assertEqual(exp["invalid_exports"][0]["symbol"], "NormalFunc")
self.assertEqual(exp["invalid_exports"][0]["ordinal"], 6)
self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_range_ordinal")
# When slot is 0, exports is empty, but out-of-range ordinal is still recorded
data_zero = with_exports([0], {0: "NormalFunc"}, base=1)
buf_zero = bytearray(data_zero)
place(buf_zero, 0x1C80, struct.pack("<H", 5))
exp_zero = self.inspect_buf(bytes(buf_zero))
self.assertEqual(exp_zero["exports"], [])
self.assertEqual(exp_zero["invalid_export_count"], 1)
# dir_size < 40 returns empty dict
dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8
struct.pack_into("<II", buf, dir_entry, 0x1700, 39)
exp_small = self.inspect_buf(bytes(buf))
self.assertEqual(exp_small["exports"], [])
self.assertEqual(exp_small["forwarders"], {})
self.assertEqual(exp_small["invalid_export_count"], 0)
def test_case9_out_of_range_ordinal_markdown_report(self):
"""Case 9: Markdown report includes out_of_range_ordinal invalid export."""
data = with_exports([0x1000], {0: "NormalFunc"}, base=1)
buf = bytearray(data)
place(buf, 0x1C80, struct.pack("<H", 5))
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(buf)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("INVALID: 1 invalid: NormalFunc (out_of_range_ordinal)", md)
finally:
os.unlink(tmp_path)
def test_case10_malformed_forwarder_targets(self):
"""Case 10: Malformed forwarder target strings recorded as malformed_forwarder."""
bad_targets = [
b"nodot\0",
b".leadingdot\0",
b"trailingdot.\0",
b"other.#\0",
b"other.#notanumber\0",
b"other.#0\0",
b"other.#70000\0",
b"bad\x01target.Func\0",
]
for target_bytes in bad_targets:
with self.subTest(target=target_bytes):
data = bytearray(with_exports([FORWARDER], {0: "TestFunc"}, base=1))
place(data, FORWARDER, target_bytes)
exp = self.inspect_buf(bytes(data))
self.assertEqual(exp["invalid_export_count"], 1)
self.assertEqual(exp["invalid_exports"][0]["symbol"], "TestFunc")
self.assertEqual(exp["invalid_exports"][0]["reason"], "malformed_forwarder")
def test_case11_intra_module_forwarder_self_loop(self):
"""Case 11: Forwarder targeting itself in the same module is recorded as forwarder_loop."""
# sample.dll exporting Sleep -> sample.Sleep or sample.dll.Sleep
for target in (b"sample.Sleep\0", b"sample.dll.Sleep\0"):
with self.subTest(target=target):
data = bytearray(with_exports([FORWARDER], {0: "Sleep"}, base=1))
place(data, FORWARDER, target)
exp = self.inspect_buf(bytes(data))
self.assertEqual(exp["invalid_export_count"], 1)
self.assertEqual(exp["invalid_exports"][0]["symbol"], "Sleep")
self.assertEqual(exp["invalid_exports"][0]["reason"], "forwarder_loop")
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(data)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("INVALID: 1 invalid: Sleep (forwarder_loop)", md)
finally:
os.unlink(tmp_path)
def test_case12_intra_module_forwarder_cyclic_loop(self):
"""Case 12: Mutual/cyclic intra-module forwarders (Alpha -> Beta, Beta -> Alpha)."""
fwd_a = 0x1790
fwd_b = 0x17B0
data = bytearray(with_exports([fwd_a, fwd_b], {0: "Alpha", 1: "Beta"}, base=1))
place(data, fwd_a, b"sample.Beta\0")
place(data, fwd_b, b"sample.Alpha\0")
exp = self.inspect_buf(bytes(data))
self.assertEqual(exp["invalid_export_count"], 2)
symbols = {inv["symbol"] for inv in exp["invalid_exports"]}
self.assertEqual(symbols, {"Alpha", "Beta"})
for inv in exp["invalid_exports"]:
self.assertEqual(inv["reason"], "forwarder_loop")
def test_case13_intra_module_forwarder_depth_limit(self):
"""Case 13: Forwarder chain >= 8 within the same module is detected as a loop."""
# Chain F0 -> F1 -> ... -> F8
slots = []
names = {}
base_addr = 0x1790
for k in range(9):
addr = base_addr + k * 11
slots.append(addr)
names[k] = f"F{k}"
data = bytearray(with_exports(slots, names, base=1))
for k in range(8):
addr = base_addr + k * 11
place(data, addr, f"sample.F{k+1}\0".encode())
# The 9th points to an external module (valid in isolation)
place(data, base_addr + 8 * 11, b"kernel32.Sleep\0")
exp = self.inspect_buf(bytes(data))
# F0's chain length reaches 8, so F0 triggers forwarder_loop
f0_inv = [inv for inv in exp["invalid_exports"] if inv["symbol"] == "F0"]
self.assertEqual(len(f0_inv), 1)
self.assertEqual(f0_inv[0]["reason"], "forwarder_loop")
def test_case14_pe_header_edge_cases(self):
"""Case 14: e_lfanew overlapping DOS header, SizeOfImage 0, SizeOfHeaders > SizeOfImage."""
base_data = build_image()
# e_lfanew < 0x40
data_short_nt = bytearray(base_data)
struct.pack_into("<I", data_short_nt, 0x3C, 0x20)
with self.assertRaisesRegex(pe_inspect.PeFormatError, "overlaps the 64-byte MS-DOS header"):
pe_inspect.PeImage(bytes(data_short_nt))
# SizeOfImage == 0
data_zero_img = bytearray(base_data)
struct.pack_into("<I", data_zero_img, 0x58 + 56, 0)
with self.assertRaisesRegex(pe_inspect.PeFormatError, "invalid SizeOfImage 0"):
pe_inspect.PeImage(bytes(data_zero_img))
# SizeOfHeaders > SizeOfImage
data_hdr_overflow = bytearray(base_data)
struct.pack_into("<I", data_hdr_overflow, 0x58 + 60, 0x4000)
with self.assertRaisesRegex(pe_inspect.PeFormatError, "exceeds SizeOfImage"):
pe_inspect.PeImage(bytes(data_hdr_overflow))
class TestExceptionDirectoryArchitectureValidation(unittest.TestCase):
"""Clean-room unit tests ensuring non-x64 machine architectures (e.g. i386, ARM64)
gracefully reject 12-byte RUNTIME_FUNCTION parsing with informative diagnostics."""
def test_x86_machine_exception_directory_rejected_as_non_x64(self):
# 32-bit x86 image (IMAGE_FILE_MACHINE_I386 = 0x14C)
data = build_image(is64=False, with_directories=True)
img = pe_inspect.PeImage(data)
pdata = pe_inspect._inspect_pdata(img)
self.assertTrue(pdata["present"])
self.assertEqual(pdata["format"], "non-x64")
self.assertEqual(pdata["parsed_count"], 0)
self.assertIn("x86", pdata["rejection_reason"])
self.assertIn("stack-based SEH", pdata["rejection_reason"])
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(data)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("(non-x64)", md)
self.assertNotIn("(OK)", md)
finally:
os.unlink(tmp_path)
def test_arm64_machine_exception_directory_rejected_as_arm64(self):
# ARM64 image (IMAGE_FILE_MACHINE_ARM64 = 0xAA64)
buf = bytearray(build_image(is64=True, with_directories=True))
# Change machine to ARM64 (0xAA64) at FileHeader + 0 (0x44)
struct.pack_into("<H", buf, 0x44, 0xAA64)
# Give 32 bytes of pdata (4 entries of 8-byte ARM64 records)
dir_entry = 0x58 + 112 + pe_inspect.DIR_EXCEPTION * 8
struct.pack_into("<II", buf, dir_entry, 0x1800, 32)
img = pe_inspect.PeImage(bytes(buf))
pdata = pe_inspect._inspect_pdata(img)
self.assertTrue(pdata["present"])
self.assertEqual(pdata["format"], "arm64")
self.assertEqual(pdata["entry_count"], 4) # 32 // 8
self.assertEqual(pdata["parsed_count"], 0)
self.assertIn("ARM64", pdata["rejection_reason"])
self.assertIn("8-byte", pdata["rejection_reason"])
with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f:
f.write(buf)
f.flush()
tmp_path = f.name
try:
report = pe_inspect.inspect(tmp_path, None)
md = pe_inspect.to_markdown(report)
self.assertIn("(arm64)", md)
self.assertNotIn("(OK)", md)
finally:
os.unlink(tmp_path)
def test_unknown_architecture_exception_directory_rejected(self):
# ARM Thumb-2 (0x1C4)
buf = bytearray(build_image(is64=False, with_directories=True))
struct.pack_into("<H", buf, 0x44, 0x01C4)
img = pe_inspect.PeImage(bytes(buf))
pdata = pe_inspect._inspect_pdata(img)
self.assertTrue(pdata["present"])
self.assertIn("unsupported", pdata["format"])
self.assertEqual(pdata["parsed_count"], 0)
self.assertIn("unsupported machine", pdata["rejection_reason"])
if __name__ == "__main__":
unittest.main()

View File

@ -2,11 +2,15 @@
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"))
@ -66,6 +70,18 @@ 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")
@ -235,6 +251,372 @@ class Python(unittest.TestCase):
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):