diff options
| author | MoonEyes <14891700+MoonEyes@users.noreply.github.com> | 2026-12-02 11:51:40 +0100 |
|---|---|---|
| committer | MoonEyes <14891700+MoonEyes@users.noreply.github.com> | 2026-12-02 11:51:40 +0100 |
| commit | fff970e616bf965729cd08a4e86bc6264494de73 (patch) | |
| tree | 03cdc30677fbe1ddaaf33d160150c9afbcfe73c5 /tests | |
| parent | 7c245a359b8bdb6d9985c6d3ffd2bee0609de911 (diff) | |
| parent | 895c472faa1c3d44a1358640f09c1f10e6a6a876 (diff) | |
Merge origin/main into carry/1346
Diffstat (limited to 'tests')
| -rw-r--r-- | tests/test_awc_shorts.py | 40 | ||||
| -rw-r--r-- | tests/test_game_gate.py | 246 | ||||
| -rw-r--r-- | tests/test_pe_inspect.py | 346 | ||||
| -rw-r--r-- | tests/test_red_green.py | 382 |
4 files changed, 1011 insertions, 3 deletions
diff --git a/tests/test_awc_shorts.py b/tests/test_awc_shorts.py index 9540dc218..7d34ce1d6 100644 --- a/tests/test_awc_shorts.py +++ b/tests/test_awc_shorts.py | |||
| @@ -322,6 +322,46 @@ class ShortsTest(unittest.TestCase): | |||
| 322 | shorts._write_catalog(path, []) | 322 | shorts._write_catalog(path, []) |
| 323 | self.assertTrue(len(chmod_calls) > 0) | 323 | self.assertTrue(len(chmod_calls) > 0) |
| 324 | 324 | ||
| 325 | def test_catalog_collision_with_input_bank_rejected(self): | ||
| 326 | bank = os.path.join(self.tmp.name, "shorts.csv") | ||
| 327 | with open(bank, "wb") as f: | ||
| 328 | f.write(b"original input bank data") | ||
| 329 | out = self.tmp.name | ||
| 330 | with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 331 | rc = shorts.main([bank, out, "--jobs", "1"]) | ||
| 332 | self.assertEqual(rc, 2) | ||
| 333 | self.assertIn("catalog would overwrite the input bank", err.getvalue()) | ||
| 334 | self.assertEqual(len(err.getvalue().splitlines()), 1) | ||
| 335 | with open(bank, "rb") as f: | ||
| 336 | self.assertEqual(f.read(), b"original input bank data") | ||
| 337 | |||
| 338 | def test_catalog_collision_with_bank_export_directory_rejected(self): | ||
| 339 | bank = os.path.join(self.tmp.name, "shorts.csv.awc") | ||
| 340 | with open(bank, "wb") as f: | ||
| 341 | f.write(b"bank data") | ||
| 342 | out = self.tmp.name | ||
| 343 | with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 344 | rc = shorts.main([bank, out, "--jobs", "1"]) | ||
| 345 | self.assertEqual(rc, 2) | ||
| 346 | self.assertIn("catalog would collide with bank export directory", err.getvalue()) | ||
| 347 | self.assertEqual(len(err.getvalue().splitlines()), 1) | ||
| 348 | with open(bank, "rb") as f: | ||
| 349 | self.assertEqual(f.read(), b"bank data") | ||
| 350 | |||
| 351 | def test_catalog_collision_refusal_creates_no_output_folder(self): | ||
| 352 | src = os.path.join(self.tmp.name, "src") | ||
| 353 | os.makedirs(src) | ||
| 354 | out = os.path.join(self.tmp.name, "out") | ||
| 355 | bank = os.path.join(src, "shorts.csv.awc") | ||
| 356 | with open(bank, "wb") as f: | ||
| 357 | f.write(b"bank data") | ||
| 358 | # The bank exports to out/shorts.csv, the catalog's own path: refused before out/ exists. | ||
| 359 | with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as err: | ||
| 360 | rc = shorts.main([bank, out, "--jobs", "1"]) | ||
| 361 | self.assertEqual(rc, 2) | ||
| 362 | self.assertIn("catalog would collide with bank export directory", err.getvalue()) | ||
| 363 | self.assertFalse(os.path.exists(out)) | ||
| 364 | |||
| 325 | 365 | ||
| 326 | if __name__ == "__main__": | 366 | if __name__ == "__main__": |
| 327 | unittest.main(verbosity=2) | 367 | unittest.main(verbosity=2) |
diff --git a/tests/test_game_gate.py b/tests/test_game_gate.py index 9873a95bf..b842660f9 100644 --- a/tests/test_game_gate.py +++ b/tests/test_game_gate.py | |||
| @@ -1,6 +1,9 @@ | |||
| 1 | """tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's | 1 | """tools/game_gate.py on synthetic run folders: every log line below is made up by the test, in the runtime's |
| 2 | formats (no game data). The contract test checks that those formats are still in the runtime's source.""" | 2 | formats (no game data). The contract test checks that those formats are still in the runtime's source.""" |
| 3 | import contextlib | ||
| 4 | import csv | ||
| 3 | import datetime as dt | 5 | import datetime as dt |
| 6 | import io | ||
| 4 | import json | 7 | import json |
| 5 | import os | 8 | import os |
| 6 | import re | 9 | import re |
| @@ -50,8 +53,14 @@ class Fake: | |||
| 50 | self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") | 53 | self.log.append(f"{stamp(t)} DEBUG leonida_gpu::frame: present token=1") |
| 51 | t += gap | 54 | t += gap |
| 52 | 55 | ||
| 53 | def memory(self, t, private, used, budget=8000, left=3000, shared=500): | 56 | def memory(self, t, private, used, budget=8000, left=3000, shared=500, waiting=0, reaper=0): |
| 54 | """The runtime's video memory line and memory line, as a diagnostics build writes them every 5 s.""" | 57 | """The runtime's video memory line, census line and memory line, as a diagnostics build writes them every 5 s.""" |
| 58 | self.log.append(f"{stamp(t)} INFO leonida_gpu::census: memory, what waits to be let go: {waiting} objects let " | ||
| 59 | f"go that wait for the submissions that may use them (LEONIDA_BURY_LAG), {reaper} retired " | ||
| 60 | f"objects, landed host lists and lists' fronts handed to the thread that lets them go and not " | ||
| 61 | f"let go yet (LEONIDA_REAPER=0: let go by the submitting thread); 0 let go by the thread done " | ||
| 62 | f"with them instead, since the start, the reaper thread's line holding LEONIDA_REAPER_LIMIT=0 or " | ||
| 63 | f"more (0: no bound)") | ||
| 55 | self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " | 64 | self.log.append(f"{stamp(t)} INFO leonida_gpu::host: video memory as the system counts it, with the memory " |
| 56 | f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " | 65 | f"line: the card's own: budget {budget} MB, in use {used} MB, 100 MB could still be reserved, " |
| 57 | f"0 MB reserved; the PC's shared with the card: budget 16000 MB, in use {shared} MB, 0 MB could " | 66 | 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: | |||
| 66 | self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") | 75 | self.log.append(f"{stamp(t + 0.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") |
| 67 | self.event(t + 0.5, "game_exited", exit_code=exit_code) | 76 | self.event(t + 0.5, "game_exited", exit_code=exit_code) |
| 68 | 77 | ||
| 78 | def state(self): | ||
| 79 | """What the supervisor reads during the run (`game_gate.py state`).""" | ||
| 80 | self.summarize() | ||
| 81 | return game_gate.state(game_gate.Run(self.dir)) | ||
| 82 | |||
| 69 | def summarize(self): | 83 | def summarize(self): |
| 70 | self.log.sort(key=lambda l: l[:27]) | 84 | self.log.sort(key=lambda l: l[:27]) |
| 71 | files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n", | 85 | files = {"run.json": json.dumps(self.meta), "leonida.log": "\n".join(self.log) + "\n", |
| @@ -235,12 +249,177 @@ class Measures(unittest.TestCase): | |||
| 235 | self.assertEqual(m["vram_over_budget_s"], 185.0) | 249 | self.assertEqual(m["vram_over_budget_s"], 185.0) |
| 236 | self.assertEqual(m["shared_in_use_max_mb"], 563) | 250 | self.assertEqual(m["shared_in_use_max_mb"], 563) |
| 237 | 251 | ||
| 252 | def memory_run(self, limits, rows): | ||
| 253 | """A run in the world with memory lines every 5 s from 70 s: rows of (private, video in use, PC left).""" | ||
| 254 | f = Fake() | ||
| 255 | f.meta["memory_stop"] = limits | ||
| 256 | f.event(1, "game", pid=1) | ||
| 257 | f.frames(10, 70, 60.0, 13) | ||
| 258 | f.frames(70, 70 + 5 * len(rows), 30.0, 4000) | ||
| 259 | for i, (private, used, left) in enumerate(rows): | ||
| 260 | f.memory(70 + 5 * i, private, used, budget=8000, left=left) | ||
| 261 | return f | ||
| 262 | |||
| 263 | def test_the_memory_stop_asks_for_a_stop_past_each_limit(self): | ||
| 264 | limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60} | ||
| 265 | calm = [(24000, 7000, 3000)] * 10 | ||
| 266 | cases = { | ||
| 267 | "private bytes 31000 MB, over 30000 MB": calm + [(31000, 7000, 3000)], | ||
| 268 | "the PC had under 200 MB left to commit for 25 s": calm + [(24000, 7000, 150)] * 6, | ||
| 269 | # Exactly 20 s under the floor (five lines 5 s apart) is enough: the floor's boundary, as 60 s is the | ||
| 270 | # video memory's. | ||
| 271 | "the PC had under 200 MB left to commit for 20 s": calm + [(24000, 7000, 150)] * 5, | ||
| 272 | "video memory over its budget for 60 s": calm + [(24000, 9000, 3000)] * 13, | ||
| 273 | } | ||
| 274 | for why, rows in cases.items(): | ||
| 275 | self.assertEqual(self.memory_run(limits, rows).state()["memory_stop"], why) | ||
| 276 | # Under each limit, at the private limit itself, or not for long enough: no stop. | ||
| 277 | for rows in (calm, calm + [(30000, 7000, 3000)], calm + [(24000, 7000, 150)] * 4, | ||
| 278 | calm + [(24000, 9000, 3000)] * 12): | ||
| 279 | self.assertIsNone(self.memory_run(limits, rows).state()["memory_stop"]) | ||
| 280 | # 0 turns a limit off, and a run.json without limits (an older gate) never stops for memory. | ||
| 281 | off = {"private_max_mb": 0, "commit_left_min_mb": 0, "over_budget_s": 0} | ||
| 282 | self.assertIsNone(self.memory_run(off, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"]) | ||
| 283 | self.assertIsNone(self.memory_run(None, cases["private bytes 31000 MB, over 30000 MB"]).state()["memory_stop"]) | ||
| 284 | # A negative limit is off too, not a stop at the first line (`-StopOverBudgetSeconds -1` stopped every run). | ||
| 285 | for name in limits: | ||
| 286 | self.assertIsNone(self.memory_run(dict(limits, **{name: -1}), calm).state()["memory_stop"], name) | ||
| 287 | |||
| 288 | def test_a_run_stopped_for_memory_fails_with_its_reason(self): | ||
| 289 | limits = {"private_max_mb": 30000, "commit_left_min_mb": 200, "over_budget_s": 60} | ||
| 290 | f = self.memory_run(limits, [(24000, 7000, 3000)] * 10 + [(31000, 7000, 3000)]) | ||
| 291 | f.event(121, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB") | ||
| 292 | f.log.append(f"{stamp(121.3)} INFO leonida_hle::modules::lifecycle: title suspended; ending the title") | ||
| 293 | f.event(121.5, "game_exited", exit_code=0) | ||
| 294 | s = f.summarize() | ||
| 295 | self.assertEqual(s["verdict"]["result"], "FAIL") | ||
| 296 | self.assertEqual(s["verdict"]["reasons"], ["memory_stop"]) | ||
| 297 | self.assertEqual(s["stop"]["reason"], "memory") | ||
| 298 | self.assertEqual(s["stop"]["memory_why"], "private bytes 31000 MB, over 30000 MB") | ||
| 299 | self.assertEqual(s["memory"]["stop_limits"], limits) | ||
| 300 | # Stopped before the world (seen in a real run with a low cap): the memory stop is the one reason. | ||
| 301 | f = Fake() | ||
| 302 | f.meta["memory_stop"] = limits | ||
| 303 | f.event(1, "game", pid=1) | ||
| 304 | f.frames(10, 80, 60.0, 13) | ||
| 305 | f.memory(75, 31000, 4000) | ||
| 306 | f.event(80, "stop_requested", reason="memory", why="private bytes 31000 MB, over 30000 MB") | ||
| 307 | f.event(83, "game_exited", exit_code=0) | ||
| 308 | self.assertEqual(f.summarize()["verdict"]["reasons"], ["memory_stop"]) | ||
| 309 | |||
| 310 | def test_the_memory_series_and_a_pile_ups_slope(self): | ||
| 311 | f = passing() | ||
| 312 | for t in range(10, 390, 5): | ||
| 313 | # From the world on (70 s) the private bytes grow 10 MB every 5 s and the reaper's queue grows. | ||
| 314 | grown = max(0, t - 70) // 5 | ||
| 315 | f.memory(t, 20000 + 10 * grown, 7000, waiting=3, reaper=100 * grown) | ||
| 316 | s = f.summarize() | ||
| 317 | m = s["memory"] | ||
| 318 | self.assertEqual(m["private_mb_per_min_in_world"], 120.0) | ||
| 319 | self.assertEqual((m["reaper_queue_max"], m["reaper_queue_max_at_s"]), (100 * 63, 385.0)) | ||
| 320 | self.assertEqual(m["waiting_objects_max"], 3) | ||
| 321 | self.assertEqual(m["series"], "memory.csv") | ||
| 322 | # `summary` writes the series beside summary.json, one row per memory line, numbers only. | ||
| 323 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 324 | game_gate.main(["game_gate.py", "summary", f.dir]) | ||
| 325 | with open(os.path.join(f.dir, "memory.csv"), encoding="utf-8") as fh: | ||
| 326 | rows = list(csv.DictReader(fh)) | ||
| 327 | self.assertEqual(len(rows), 76) | ||
| 328 | self.assertEqual(tuple(rows[0]), game_gate.SERIES_COLUMNS) | ||
| 329 | self.assertEqual(rows[-1]["private_mb"], "20630") | ||
| 330 | self.assertEqual(rows[-1]["reaper_queue"], "6300") | ||
| 331 | self.assertEqual(rows[-1]["vram_in_use_mb"], "7000") | ||
| 332 | # The same bytes on every machine: LF line ends, never CRLF. | ||
| 333 | with open(os.path.join(f.dir, "memory.csv"), "rb") as fh: | ||
| 334 | self.assertNotIn(b"\r", fh.read()) | ||
| 335 | |||
| 336 | def summary_files(self, f): | ||
| 337 | """`game_gate.py summary` on the folder: (exit code, summary.json, memory.csv rows or None, stderr).""" | ||
| 338 | f.summarize() | ||
| 339 | err = io.StringIO() | ||
| 340 | with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(err): | ||
| 341 | code = game_gate.main(["game_gate.py", "summary", f.dir]) | ||
| 342 | with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh: | ||
| 343 | s = json.load(fh) | ||
| 344 | path = os.path.join(f.dir, "memory.csv") | ||
| 345 | rows = None | ||
| 346 | if os.path.isfile(path): | ||
| 347 | with open(path, encoding="utf-8") as fh: | ||
| 348 | rows = list(csv.DictReader(fh)) | ||
| 349 | return code, s, rows, err.getvalue() | ||
| 350 | |||
| 351 | def test_the_series_takes_the_lines_within_2_s_of_each_memory_line(self): | ||
| 352 | f = passing() | ||
| 353 | f.memory(100, 20000, 7000, waiting=3, reaper=40) # the three lines at once, as the runtime writes them | ||
| 354 | f.memory(200, 21000, 7500, waiting=5, reaper=50) | ||
| 355 | census, video, memory = f.log[-3:] | ||
| 356 | # The video memory line 2 s before (taken), the census line 2.5 s after (too far: empty cells). | ||
| 357 | f.log[-3:] = [census.replace(stamp(200), stamp(202.5)), video.replace(stamp(200), stamp(198)), memory] | ||
| 358 | f.memory(300, 22000, 8000) | ||
| 359 | f.log[-3:] = f.log[-1:] # a memory line alone | ||
| 360 | _, _, rows, _ = self.summary_files(f) | ||
| 361 | got = [(r["t_s"], r["vram_in_use_mb"], r["shared_in_use_mb"], r["waiting_objects"], r["reaper_queue"]) | ||
| 362 | for r in rows] | ||
| 363 | self.assertEqual(got, [("100.0", "7000", "500", "3", "40"), ("200.0", "7500", "500", "", ""), | ||
| 364 | ("300.0", "", "", "", "")]) | ||
| 365 | |||
| 366 | def test_the_slope_counts_the_world_up_to_the_stop(self): | ||
| 367 | f = Fake() | ||
| 368 | f.event(1, "game", pid=1) | ||
| 369 | f.frames(10, 70, 60.0, 13) | ||
| 370 | f.frames(70, 420, 50.0, 4000) | ||
| 371 | for t in range(70, 420, 5): | ||
| 372 | # 120 MB a minute in the world, then a jump while the title ends after the stop request (390 s). | ||
| 373 | f.memory(t, 20000 + 2 * (t - 70) if t <= 390 else 40000, 7000) | ||
| 374 | f.event(390, "stop_requested", reason="target") | ||
| 375 | f.event(420, "game_exited", exit_code=0) | ||
| 376 | self.assertEqual(f.summarize()["memory"]["private_mb_per_min_in_world"], 120.0) | ||
| 377 | # Fewer than 3 memory lines in the world: no slope. | ||
| 378 | f = passing() | ||
| 379 | for t in (40, 50, 60, 100, 200): | ||
| 380 | f.memory(t, 20000 + t, 7000) | ||
| 381 | self.assertIsNone(f.summarize()["memory"]["private_mb_per_min_in_world"]) | ||
| 382 | |||
| 383 | def test_a_series_it_cannot_write_still_leaves_the_summary(self): | ||
| 384 | # memory.csv held by another program: the summary is written all the same, with no series named. | ||
| 385 | f = passing() | ||
| 386 | for t in range(70, 390, 5): | ||
| 387 | f.memory(t, 20000, 7000) | ||
| 388 | os.makedirs(os.path.join(f.dir, "memory.csv")) # opening it to write fails, as a locked file does | ||
| 389 | code, s, _, err = self.summary_files(f) | ||
| 390 | self.assertEqual(code, 0) | ||
| 391 | self.assertEqual(s["verdict"]["result"], "PASS") | ||
| 392 | self.assertIsNone(s["memory"]["series"]) | ||
| 393 | self.assertEqual(s["memory"]["lines"], 64) | ||
| 394 | self.assertIn("memory.csv not written or removed", err) | ||
| 395 | |||
| 238 | def test_a_build_without_memory_lines_gives_no_memory_peaks(self): | 396 | def test_a_build_without_memory_lines_gives_no_memory_peaks(self): |
| 239 | m = passing().summarize()["memory"] | 397 | f = passing() |
| 398 | m = f.summarize()["memory"] | ||
| 240 | self.assertIsNone(m["source"]) | 399 | self.assertIsNone(m["source"]) |
| 241 | self.assertEqual(m["lines"], 0) | 400 | self.assertEqual(m["lines"], 0) |
| 242 | self.assertIsNone(m["private_max_mb"]) | 401 | self.assertIsNone(m["private_max_mb"]) |
| 243 | self.assertIsNone(m["vram_in_use_max_mb"]) | 402 | self.assertIsNone(m["vram_in_use_max_mb"]) |
| 403 | self.assertIsNone(m["series"]) | ||
| 404 | self.assertIsNone(m["reaper_queue_max"]) | ||
| 405 | self.assertIsNone(m["private_mb_per_min_in_world"]) | ||
| 406 | # And `summary` writes no series file: not even a header alone. | ||
| 407 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 408 | game_gate.main(["game_gate.py", "summary", f.dir]) | ||
| 409 | self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv"))) | ||
| 410 | |||
| 411 | def test_a_folder_summarized_again_without_memory_lines_keeps_no_old_series(self): | ||
| 412 | # A memory.csv from an earlier summary, and a log that has no memory lines now: the old rows must not sit | ||
| 413 | # beside `series: null`. | ||
| 414 | f = passing() | ||
| 415 | f.summarize() | ||
| 416 | with open(os.path.join(f.dir, "memory.csv"), "w", encoding="utf-8", newline="\n") as fh: | ||
| 417 | fh.write(",".join(game_gate.SERIES_COLUMNS) + "\n70.0,1000,500,15000,4000,8000,7000,500,0,0\n") | ||
| 418 | with contextlib.redirect_stdout(io.StringIO()): | ||
| 419 | game_gate.main(["game_gate.py", "summary", f.dir]) | ||
| 420 | with open(os.path.join(f.dir, "summary.json"), encoding="utf-8") as fh: | ||
| 421 | self.assertIsNone(json.load(fh)["memory"]["series"]) | ||
| 422 | self.assertFalse(os.path.exists(os.path.join(f.dir, "memory.csv"))) | ||
| 244 | 423 | ||
| 245 | def test_without_present_lines_the_frame_lines_give_the_rate(self): | 424 | def test_without_present_lines_the_frame_lines_give_the_rate(self): |
| 246 | f = Fake() | 425 | f = Fake() |
| @@ -317,6 +496,67 @@ class Script(unittest.TestCase): | |||
| 317 | with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: | 496 | with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: |
| 318 | self.assertEqual(f.readline().strip(), "#Requires -Version 7.0") | 497 | self.assertEqual(f.readline().strip(), "#Requires -Version 7.0") |
| 319 | 498 | ||
| 499 | def test_the_memory_stop_limits_reach_the_run_and_its_detached_start(self): | ||
| 500 | with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: | ||
| 501 | text = f.read() | ||
| 502 | for name in ("StopPrivateMB", "StopCommitLeftMB", "StopOverBudgetSeconds"): | ||
| 503 | self.assertIn(f"[int]${name} = ", text) | ||
| 504 | # `start` rebuilds the command line of the detached `run`: a limit left out would be lost there. | ||
| 505 | self.assertIn(f"'-{name}'; ${name}", text) | ||
| 506 | self.assertIn("memory_stop = [ordered]@{", text) | ||
| 507 | # The private default follows the PC's memory too, not only its commit limit (a large page file). | ||
| 508 | self.assertIn("TotalPhysicalMemory", text) | ||
| 509 | self.assertIn("[math]::Min($commitLimitMB * 0.9, $physicalMB * 1.25)", text) | ||
| 510 | |||
| 511 | # What one poll of the supervisor reads (`game_gate.py state`, a STOP file, the minutes since the start) and the | ||
| 512 | # reason it stops the run for, with -WorldSeconds 300 and -MaxMinutes 45. | ||
| 513 | POLLS = [ | ||
| 514 | # The world time reached in the same poll as a memory limit: a measurement, not a memory stop. | ||
| 515 | ({"relaunched": False, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, | ||
| 516 | "target"), | ||
| 517 | ({"relaunched": False, "world_s": 295.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, | ||
| 518 | "memory"), | ||
| 519 | ({"relaunched": True, "world_s": 300.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 20, | ||
| 520 | "relaunched"), | ||
| 521 | ({"relaunched": False, "world_s": 100.0, "memory_stop": "video memory over its budget for 60 s"}, True, 20, | ||
| 522 | "memory"), | ||
| 523 | ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, True, 20, "stop_file"), | ||
| 524 | # A memory limit at the time limit: the memory stop names the real reason. | ||
| 525 | ({"relaunched": False, "world_s": 100.0, "memory_stop": "private bytes 31000 MB, over 30000 MB"}, False, 45, | ||
| 526 | "memory"), | ||
| 527 | ({"relaunched": False, "world_s": 0.0, "memory_stop": None}, False, 45, "timeout"), | ||
| 528 | ({"relaunched": False, "world_s": 100.0, "memory_stop": None}, False, 20, "none"), | ||
| 529 | ] | ||
| 530 | |||
| 531 | def test_a_poll_stops_for_the_target_before_the_memory_stop(self): | ||
| 532 | # The supervisor's own function is taken out of the script and put to PowerShell 7 with each poll above. | ||
| 533 | with open(os.path.join(ROOT, "scripts", "game-gate.ps1"), encoding="utf-8") as f: | ||
| 534 | text = f.read() | ||
| 535 | self.assertIn("$stopReason = Get-StopReason -Poll $state ", text) | ||
| 536 | self.assertIn("-TargetSeconds $WorldSeconds -LimitMinutes $MaxMinutes", text) | ||
| 537 | self.assertEqual(text.count("$stopReason = "), 2) # set to $null before the loop, then only from the function | ||
| 538 | # The memory stop's sentence goes into the stop_requested event (`stop.memory_why`). | ||
| 539 | self.assertIn("if ($stopReason -eq 'memory') { $memoryWhy = $state.memory_stop }", text) | ||
| 540 | pwsh = shutil.which("pwsh") | ||
| 541 | if not pwsh: | ||
| 542 | self.skipTest("no PowerShell 7 here") | ||
| 543 | script = ("$ErrorActionPreference = 'Stop'; " | ||
| 544 | "$language = 'System.Management.Automation.Language'; " | ||
| 545 | "$ast = ($language + '.Parser' -as [type])::ParseFile($env:GATE_SCRIPT, [ref]$null, [ref]$null); " | ||
| 546 | "$fn = $ast.Find({ $args[0].GetType().Name -eq 'FunctionDefinitionAst' -and " | ||
| 547 | "$args[0].Name -eq 'Get-StopReason' }, $true); " | ||
| 548 | "if (-not $fn) { throw 'the gate has no Get-StopReason' }; " | ||
| 549 | ". ([scriptblock]::Create($fn.Extent.Text)); " | ||
| 550 | "foreach ($p in ($env:GATE_POLLS | ConvertFrom-Json)) " | ||
| 551 | "{ $r = Get-StopReason -Poll $p[0] -StopFile $p[1] -Minutes $p[2] -TargetSeconds 300 " | ||
| 552 | "-LimitMinutes 45; if ($r) { $r } else { 'none' } }") | ||
| 553 | env = dict(os.environ, GATE_SCRIPT=os.path.join(ROOT, "scripts", "game-gate.ps1"), | ||
| 554 | GATE_POLLS=json.dumps([p[:3] for p in self.POLLS])) | ||
| 555 | done = subprocess.run([pwsh, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, | ||
| 556 | text=True, timeout=120, env=env) | ||
| 557 | self.assertEqual(done.returncode, 0, done.stderr) | ||
| 558 | self.assertEqual(done.stdout.split(), [p[3] for p in self.POLLS]) | ||
| 559 | |||
| 320 | def test_no_variable_takes_a_parameters_name_in_another_case(self): | 560 | def test_no_variable_takes_a_parameters_name_in_another_case(self): |
| 321 | # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, | 561 | # PowerShell names ignore case: a `$game` process held in the `[string]$Game` parameter became its name, |
| 322 | # and the stop could not wait for it. | 562 | # and the stop could not wait for it. |
diff --git a/tests/test_pe_inspect.py b/tests/test_pe_inspect.py index 4c0cb1228..f9312dc1d 100644 --- a/tests/test_pe_inspect.py +++ b/tests/test_pe_inspect.py | |||
| @@ -1383,5 +1383,351 @@ class HostClassesTest(unittest.TestCase): | |||
| 1383 | self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset()) | 1383 | self.assertEqual(pe_inspect.runtime_shim_dlls(os.path.join(self.dir, "missing")), frozenset()) |
| 1384 | 1384 | ||
| 1385 | 1385 | ||
| 1386 | class TestExportForwarders(unittest.TestCase): | ||
| 1387 | def inspect_buf(self, buf: bytes) -> dict: | ||
| 1388 | return pe_inspect._inspect_exports(pe_inspect.PeImage(buf)) | ||
| 1389 | |||
| 1390 | def test_export_rva_at_the_end_of_the_export_directory_is_not_a_forwarder(self): | ||
| 1391 | """The directory is [begin, end): an RVA equal to the end is past it, as in runtime/src/pe_loader.cpp.""" | ||
| 1392 | end = 0x1800 # the export directory of with_exports() is [0x1700, 0x1800) | ||
| 1393 | data = with_exports([end], {0: "AtTheEnd"}, base=1) | ||
| 1394 | exp = self.inspect_buf(data) | ||
| 1395 | self.assertEqual(exp["forwarders"], {}) | ||
| 1396 | self.assertEqual(exp["exports"], ["AtTheEnd"]) | ||
| 1397 | last = with_exports([end - 1], {0: "LastByte"}, base=1) | ||
| 1398 | self.assertIn("LastByte", self.inspect_buf(last)["forwarders"]) | ||
| 1399 | |||
| 1400 | def test_case1_normal_exports_and_unused_slots(self): | ||
| 1401 | """Case 1: Normal code exports + unused zero-RVA slot skipped (forwarders empty, invalid_export_count 0).""" | ||
| 1402 | data = with_exports([0x1000, 0, 0x1010], {0: "Alpha", 2: "Beta"}, base=1) | ||
| 1403 | exp = self.inspect_buf(data) | ||
| 1404 | self.assertEqual(exp["exports"], ["Alpha", "Beta"]) | ||
| 1405 | self.assertEqual(exp["forwarders"], {}) | ||
| 1406 | self.assertEqual(exp["invalid_export_count"], 0) | ||
| 1407 | self.assertEqual(exp["invalid_exports"], []) | ||
| 1408 | |||
| 1409 | def test_case2_named_forwarded_export(self): | ||
| 1410 | """Case 2: Named forwarded export (RVA inside export directory [0x1700, 0x1800)).""" | ||
| 1411 | data = with_exports([0x1000, FORWARDER], {0: "NormalFunc", 1: "Sleep"}, base=10) | ||
| 1412 | exp = self.inspect_buf(data) | ||
| 1413 | self.assertEqual(exp["exports"], ["NormalFunc", "Sleep"]) | ||
| 1414 | self.assertEqual(exp["forwarders"], {"Sleep": "other.Target"}) | ||
| 1415 | self.assertEqual(exp["invalid_export_count"], 0) | ||
| 1416 | |||
| 1417 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1418 | f.write(data) | ||
| 1419 | f.flush() | ||
| 1420 | tmp_path = f.name | ||
| 1421 | try: | ||
| 1422 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1423 | md = pe_inspect.to_markdown(report) | ||
| 1424 | self.assertIn("(1 forwarded)", md) | ||
| 1425 | self.assertIn("## Forwarded Exports", md) | ||
| 1426 | self.assertIn("| `Sleep` | `other.Target` |", md) | ||
| 1427 | finally: | ||
| 1428 | os.unlink(tmp_path) | ||
| 1429 | |||
| 1430 | def test_case3_ordinal_only_forwarder(self): | ||
| 1431 | """Case 3: Ordinal-only forwarded export (index not in named).""" | ||
| 1432 | data = with_exports([0x1000, FORWARDER], {0: "Func"}, base=10) | ||
| 1433 | exp = self.inspect_buf(data) | ||
| 1434 | self.assertEqual(exp["exports"], ["Func", "#11"]) | ||
| 1435 | self.assertEqual(exp["forwarders"], {"#11": "other.Target"}) | ||
| 1436 | self.assertEqual(exp["invalid_export_count"], 0) | ||
| 1437 | |||
| 1438 | def test_case4_aliased_named_forwarders(self): | ||
| 1439 | """Case 4: Two export names mapping to the same forwarded EAT index.""" | ||
| 1440 | data = with_exports([FORWARDER], {0: "AliasA"}, base=1) | ||
| 1441 | buf = bytearray(data) | ||
| 1442 | place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 2, | ||
| 1443 | EXPORT_FUNCS, 0x1C00, 0x1C80)) | ||
| 1444 | place(buf, 0x1C00, struct.pack("<II", 0x1D00, 0x1D10)) | ||
| 1445 | place(buf, 0x1C80, struct.pack("<HH", 0, 0)) | ||
| 1446 | place(buf, 0x1D00, b"AliasA\0") | ||
| 1447 | place(buf, 0x1D10, b"AliasB\0") | ||
| 1448 | exp = self.inspect_buf(bytes(buf)) | ||
| 1449 | self.assertEqual(exp["exports"], ["AliasA", "AliasB"]) | ||
| 1450 | self.assertEqual(exp["forwarders"], {"AliasA": "other.Target", "AliasB": "other.Target"}) | ||
| 1451 | self.assertEqual(exp["invalid_export_count"], 0) | ||
| 1452 | |||
| 1453 | def test_case5_out_of_bounds_export_rva(self): | ||
| 1454 | """Case 5: Out-of-bounds export RVA (>= size_of_image).""" | ||
| 1455 | data = with_exports([0x3000], {0: "BadFunc"}, base=10) | ||
| 1456 | exp = self.inspect_buf(data) | ||
| 1457 | self.assertEqual(exp["exports"], ["BadFunc"]) | ||
| 1458 | self.assertEqual(exp["invalid_export_count"], 1) | ||
| 1459 | self.assertEqual(len(exp["invalid_exports"]), 1) | ||
| 1460 | self.assertEqual(exp["invalid_exports"][0]["symbol"], "BadFunc") | ||
| 1461 | self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_bounds") | ||
| 1462 | |||
| 1463 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1464 | f.write(data) | ||
| 1465 | f.flush() | ||
| 1466 | tmp_path = f.name | ||
| 1467 | try: | ||
| 1468 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1469 | md = pe_inspect.to_markdown(report) | ||
| 1470 | self.assertIn("INVALID: 1 invalid: BadFunc (out_of_bounds)", md) | ||
| 1471 | finally: | ||
| 1472 | os.unlink(tmp_path) | ||
| 1473 | |||
| 1474 | def test_case6_unreadable_forwarder_and_error_cap(self): | ||
| 1475 | """Case 6: Unreadable forwarder string and invalid error cap at <= 5.""" | ||
| 1476 | buf = bytearray(build_image()) | ||
| 1477 | dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8 | ||
| 1478 | struct.pack_into("<II", buf, dir_entry, 0x1700, 0x2000) | ||
| 1479 | place(buf, 0x1700, struct.pack("<IIHHIIIIIII", 0, 0, 0, 0, 0x1780, 1, 1, 1, | ||
| 1480 | EXPORT_FUNCS, 0x1C00, 0x1C80)) | ||
| 1481 | place(buf, EXPORT_FUNCS, struct.pack("<I", 0x3500)) | ||
| 1482 | place(buf, 0x1C00, struct.pack("<I", 0x1D00)) | ||
| 1483 | place(buf, 0x1C80, struct.pack("<H", 0)) | ||
| 1484 | place(buf, 0x1D00, b"BrokenFwd\0") | ||
| 1485 | exp = self.inspect_buf(bytes(buf)) | ||
| 1486 | self.assertEqual(exp["forwarders"], {"BrokenFwd": "?"}) | ||
| 1487 | self.assertEqual(exp["invalid_export_count"], 1) | ||
| 1488 | self.assertEqual(exp["invalid_exports"][0]["reason"], "unreadable_forwarder") | ||
| 1489 | |||
| 1490 | bad_slots = [0x4000 + i * 0x100 for i in range(8)] | ||
| 1491 | bad_names = {i: f"Bad{i}" for i in range(8)} | ||
| 1492 | data_bad = with_exports(bad_slots, bad_names, base=1) | ||
| 1493 | exp_bad = self.inspect_buf(data_bad) | ||
| 1494 | self.assertEqual(exp_bad["invalid_export_count"], 8) | ||
| 1495 | self.assertEqual(len(exp_bad["invalid_exports"]), 5) | ||
| 1496 | |||
| 1497 | def test_case7_combined_forwarder_and_invalid_summary(self): | ||
| 1498 | """Case 7: DLL with both valid forwarder and invalid export displays both in markdown.""" | ||
| 1499 | data = with_exports([0x1000, FORWARDER, 0x3000], {1: "Fwd|Func", 2: "BadFunc"}, base=10) | ||
| 1500 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1501 | f.write(data) | ||
| 1502 | f.flush() | ||
| 1503 | tmp_path = f.name | ||
| 1504 | try: | ||
| 1505 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1506 | md = pe_inspect.to_markdown(report) | ||
| 1507 | self.assertIn("(1 forwarded; INVALID: 1 invalid: BadFunc (out_of_bounds))", md) | ||
| 1508 | self.assertIn("| `Fwd\\|Func` | `other.Target` |", md) | ||
| 1509 | finally: | ||
| 1510 | os.unlink(tmp_path) | ||
| 1511 | |||
| 1512 | def test_case8_out_of_range_ordinal_and_small_dir_size(self): | ||
| 1513 | """Case 8: Ordinal index >= functions recorded as invalid, dir_size < 40 returns empty.""" | ||
| 1514 | data = with_exports([0x1000], {0: "NormalFunc"}, base=1) | ||
| 1515 | buf = bytearray(data) | ||
| 1516 | # Point the ordinal table to index 5 while NumberOfFunctions is 1 | ||
| 1517 | place(buf, 0x1C80, struct.pack("<H", 5)) | ||
| 1518 | exp = self.inspect_buf(bytes(buf)) | ||
| 1519 | self.assertNotIn("NormalFunc", exp["exports"]) | ||
| 1520 | self.assertEqual(exp["exports"], ["#1"]) | ||
| 1521 | self.assertEqual(exp["forwarders"], {}) | ||
| 1522 | self.assertEqual(exp["invalid_export_count"], 1) | ||
| 1523 | self.assertEqual(len(exp["invalid_exports"]), 1) | ||
| 1524 | self.assertEqual(exp["invalid_exports"][0]["symbol"], "NormalFunc") | ||
| 1525 | self.assertEqual(exp["invalid_exports"][0]["ordinal"], 6) | ||
| 1526 | self.assertEqual(exp["invalid_exports"][0]["reason"], "out_of_range_ordinal") | ||
| 1527 | |||
| 1528 | # When slot is 0, exports is empty, but out-of-range ordinal is still recorded | ||
| 1529 | data_zero = with_exports([0], {0: "NormalFunc"}, base=1) | ||
| 1530 | buf_zero = bytearray(data_zero) | ||
| 1531 | place(buf_zero, 0x1C80, struct.pack("<H", 5)) | ||
| 1532 | exp_zero = self.inspect_buf(bytes(buf_zero)) | ||
| 1533 | self.assertEqual(exp_zero["exports"], []) | ||
| 1534 | self.assertEqual(exp_zero["invalid_export_count"], 1) | ||
| 1535 | |||
| 1536 | # dir_size < 40 returns empty dict | ||
| 1537 | dir_entry = 0x58 + 112 + pe_inspect.DIR_EXPORT * 8 | ||
| 1538 | struct.pack_into("<II", buf, dir_entry, 0x1700, 39) | ||
| 1539 | exp_small = self.inspect_buf(bytes(buf)) | ||
| 1540 | self.assertEqual(exp_small["exports"], []) | ||
| 1541 | self.assertEqual(exp_small["forwarders"], {}) | ||
| 1542 | self.assertEqual(exp_small["invalid_export_count"], 0) | ||
| 1543 | |||
| 1544 | def test_case9_out_of_range_ordinal_markdown_report(self): | ||
| 1545 | """Case 9: Markdown report includes out_of_range_ordinal invalid export.""" | ||
| 1546 | data = with_exports([0x1000], {0: "NormalFunc"}, base=1) | ||
| 1547 | buf = bytearray(data) | ||
| 1548 | place(buf, 0x1C80, struct.pack("<H", 5)) | ||
| 1549 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1550 | f.write(buf) | ||
| 1551 | f.flush() | ||
| 1552 | tmp_path = f.name | ||
| 1553 | try: | ||
| 1554 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1555 | md = pe_inspect.to_markdown(report) | ||
| 1556 | self.assertIn("INVALID: 1 invalid: NormalFunc (out_of_range_ordinal)", md) | ||
| 1557 | finally: | ||
| 1558 | os.unlink(tmp_path) | ||
| 1559 | |||
| 1560 | def test_case10_malformed_forwarder_targets(self): | ||
| 1561 | """Case 10: Malformed forwarder target strings recorded as malformed_forwarder.""" | ||
| 1562 | bad_targets = [ | ||
| 1563 | b"nodot\0", | ||
| 1564 | b".leadingdot\0", | ||
| 1565 | b"trailingdot.\0", | ||
| 1566 | b"other.#\0", | ||
| 1567 | b"other.#notanumber\0", | ||
| 1568 | b"other.#0\0", | ||
| 1569 | b"other.#70000\0", | ||
| 1570 | b"bad\x01target.Func\0", | ||
| 1571 | ] | ||
| 1572 | for target_bytes in bad_targets: | ||
| 1573 | with self.subTest(target=target_bytes): | ||
| 1574 | data = bytearray(with_exports([FORWARDER], {0: "TestFunc"}, base=1)) | ||
| 1575 | place(data, FORWARDER, target_bytes) | ||
| 1576 | exp = self.inspect_buf(bytes(data)) | ||
| 1577 | self.assertEqual(exp["invalid_export_count"], 1) | ||
| 1578 | self.assertEqual(exp["invalid_exports"][0]["symbol"], "TestFunc") | ||
| 1579 | self.assertEqual(exp["invalid_exports"][0]["reason"], "malformed_forwarder") | ||
| 1580 | |||
| 1581 | def test_case11_intra_module_forwarder_self_loop(self): | ||
| 1582 | """Case 11: Forwarder targeting itself in the same module is recorded as forwarder_loop.""" | ||
| 1583 | # sample.dll exporting Sleep -> sample.Sleep or sample.dll.Sleep | ||
| 1584 | for target in (b"sample.Sleep\0", b"sample.dll.Sleep\0"): | ||
| 1585 | with self.subTest(target=target): | ||
| 1586 | data = bytearray(with_exports([FORWARDER], {0: "Sleep"}, base=1)) | ||
| 1587 | place(data, FORWARDER, target) | ||
| 1588 | exp = self.inspect_buf(bytes(data)) | ||
| 1589 | self.assertEqual(exp["invalid_export_count"], 1) | ||
| 1590 | self.assertEqual(exp["invalid_exports"][0]["symbol"], "Sleep") | ||
| 1591 | self.assertEqual(exp["invalid_exports"][0]["reason"], "forwarder_loop") | ||
| 1592 | |||
| 1593 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1594 | f.write(data) | ||
| 1595 | f.flush() | ||
| 1596 | tmp_path = f.name | ||
| 1597 | try: | ||
| 1598 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1599 | md = pe_inspect.to_markdown(report) | ||
| 1600 | self.assertIn("INVALID: 1 invalid: Sleep (forwarder_loop)", md) | ||
| 1601 | finally: | ||
| 1602 | os.unlink(tmp_path) | ||
| 1603 | |||
| 1604 | def test_case12_intra_module_forwarder_cyclic_loop(self): | ||
| 1605 | """Case 12: Mutual/cyclic intra-module forwarders (Alpha -> Beta, Beta -> Alpha).""" | ||
| 1606 | fwd_a = 0x1790 | ||
| 1607 | fwd_b = 0x17B0 | ||
| 1608 | data = bytearray(with_exports([fwd_a, fwd_b], {0: "Alpha", 1: "Beta"}, base=1)) | ||
| 1609 | place(data, fwd_a, b"sample.Beta\0") | ||
| 1610 | place(data, fwd_b, b"sample.Alpha\0") | ||
| 1611 | exp = self.inspect_buf(bytes(data)) | ||
| 1612 | self.assertEqual(exp["invalid_export_count"], 2) | ||
| 1613 | symbols = {inv["symbol"] for inv in exp["invalid_exports"]} | ||
| 1614 | self.assertEqual(symbols, {"Alpha", "Beta"}) | ||
| 1615 | for inv in exp["invalid_exports"]: | ||
| 1616 | self.assertEqual(inv["reason"], "forwarder_loop") | ||
| 1617 | |||
| 1618 | def test_case13_intra_module_forwarder_depth_limit(self): | ||
| 1619 | """Case 13: Forwarder chain >= 8 within the same module is detected as a loop.""" | ||
| 1620 | # Chain F0 -> F1 -> ... -> F8 | ||
| 1621 | slots = [] | ||
| 1622 | names = {} | ||
| 1623 | base_addr = 0x1790 | ||
| 1624 | for k in range(9): | ||
| 1625 | addr = base_addr + k * 11 | ||
| 1626 | slots.append(addr) | ||
| 1627 | names[k] = f"F{k}" | ||
| 1628 | data = bytearray(with_exports(slots, names, base=1)) | ||
| 1629 | for k in range(8): | ||
| 1630 | addr = base_addr + k * 11 | ||
| 1631 | place(data, addr, f"sample.F{k+1}\0".encode()) | ||
| 1632 | # The 9th points to an external module (valid in isolation) | ||
| 1633 | place(data, base_addr + 8 * 11, b"kernel32.Sleep\0") | ||
| 1634 | |||
| 1635 | exp = self.inspect_buf(bytes(data)) | ||
| 1636 | # F0's chain length reaches 8, so F0 triggers forwarder_loop | ||
| 1637 | f0_inv = [inv for inv in exp["invalid_exports"] if inv["symbol"] == "F0"] | ||
| 1638 | self.assertEqual(len(f0_inv), 1) | ||
| 1639 | self.assertEqual(f0_inv[0]["reason"], "forwarder_loop") | ||
| 1640 | |||
| 1641 | def test_case14_pe_header_edge_cases(self): | ||
| 1642 | """Case 14: e_lfanew overlapping DOS header, SizeOfImage 0, SizeOfHeaders > SizeOfImage.""" | ||
| 1643 | base_data = build_image() | ||
| 1644 | |||
| 1645 | # e_lfanew < 0x40 | ||
| 1646 | data_short_nt = bytearray(base_data) | ||
| 1647 | struct.pack_into("<I", data_short_nt, 0x3C, 0x20) | ||
| 1648 | with self.assertRaisesRegex(pe_inspect.PeFormatError, "overlaps the 64-byte MS-DOS header"): | ||
| 1649 | pe_inspect.PeImage(bytes(data_short_nt)) | ||
| 1650 | |||
| 1651 | # SizeOfImage == 0 | ||
| 1652 | data_zero_img = bytearray(base_data) | ||
| 1653 | struct.pack_into("<I", data_zero_img, 0x58 + 56, 0) | ||
| 1654 | with self.assertRaisesRegex(pe_inspect.PeFormatError, "invalid SizeOfImage 0"): | ||
| 1655 | pe_inspect.PeImage(bytes(data_zero_img)) | ||
| 1656 | |||
| 1657 | # SizeOfHeaders > SizeOfImage | ||
| 1658 | data_hdr_overflow = bytearray(base_data) | ||
| 1659 | struct.pack_into("<I", data_hdr_overflow, 0x58 + 60, 0x4000) | ||
| 1660 | with self.assertRaisesRegex(pe_inspect.PeFormatError, "exceeds SizeOfImage"): | ||
| 1661 | pe_inspect.PeImage(bytes(data_hdr_overflow)) | ||
| 1662 | |||
| 1663 | |||
| 1664 | class TestExceptionDirectoryArchitectureValidation(unittest.TestCase): | ||
| 1665 | """Clean-room unit tests ensuring non-x64 machine architectures (e.g. i386, ARM64) | ||
| 1666 | gracefully reject 12-byte RUNTIME_FUNCTION parsing with informative diagnostics.""" | ||
| 1667 | |||
| 1668 | def test_x86_machine_exception_directory_rejected_as_non_x64(self): | ||
| 1669 | # 32-bit x86 image (IMAGE_FILE_MACHINE_I386 = 0x14C) | ||
| 1670 | data = build_image(is64=False, with_directories=True) | ||
| 1671 | img = pe_inspect.PeImage(data) | ||
| 1672 | pdata = pe_inspect._inspect_pdata(img) | ||
| 1673 | self.assertTrue(pdata["present"]) | ||
| 1674 | self.assertEqual(pdata["format"], "non-x64") | ||
| 1675 | self.assertEqual(pdata["parsed_count"], 0) | ||
| 1676 | self.assertIn("x86", pdata["rejection_reason"]) | ||
| 1677 | self.assertIn("stack-based SEH", pdata["rejection_reason"]) | ||
| 1678 | |||
| 1679 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1680 | f.write(data) | ||
| 1681 | f.flush() | ||
| 1682 | tmp_path = f.name | ||
| 1683 | try: | ||
| 1684 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1685 | md = pe_inspect.to_markdown(report) | ||
| 1686 | self.assertIn("(non-x64)", md) | ||
| 1687 | self.assertNotIn("(OK)", md) | ||
| 1688 | finally: | ||
| 1689 | os.unlink(tmp_path) | ||
| 1690 | |||
| 1691 | def test_arm64_machine_exception_directory_rejected_as_arm64(self): | ||
| 1692 | # ARM64 image (IMAGE_FILE_MACHINE_ARM64 = 0xAA64) | ||
| 1693 | buf = bytearray(build_image(is64=True, with_directories=True)) | ||
| 1694 | # Change machine to ARM64 (0xAA64) at FileHeader + 0 (0x44) | ||
| 1695 | struct.pack_into("<H", buf, 0x44, 0xAA64) | ||
| 1696 | # Give 32 bytes of pdata (4 entries of 8-byte ARM64 records) | ||
| 1697 | dir_entry = 0x58 + 112 + pe_inspect.DIR_EXCEPTION * 8 | ||
| 1698 | struct.pack_into("<II", buf, dir_entry, 0x1800, 32) | ||
| 1699 | img = pe_inspect.PeImage(bytes(buf)) | ||
| 1700 | pdata = pe_inspect._inspect_pdata(img) | ||
| 1701 | self.assertTrue(pdata["present"]) | ||
| 1702 | self.assertEqual(pdata["format"], "arm64") | ||
| 1703 | self.assertEqual(pdata["entry_count"], 4) # 32 // 8 | ||
| 1704 | self.assertEqual(pdata["parsed_count"], 0) | ||
| 1705 | self.assertIn("ARM64", pdata["rejection_reason"]) | ||
| 1706 | self.assertIn("8-byte", pdata["rejection_reason"]) | ||
| 1707 | |||
| 1708 | with tempfile.NamedTemporaryFile(suffix=".dll", delete=False) as f: | ||
| 1709 | f.write(buf) | ||
| 1710 | f.flush() | ||
| 1711 | tmp_path = f.name | ||
| 1712 | try: | ||
| 1713 | report = pe_inspect.inspect(tmp_path, None) | ||
| 1714 | md = pe_inspect.to_markdown(report) | ||
| 1715 | self.assertIn("(arm64)", md) | ||
| 1716 | self.assertNotIn("(OK)", md) | ||
| 1717 | finally: | ||
| 1718 | os.unlink(tmp_path) | ||
| 1719 | |||
| 1720 | def test_unknown_architecture_exception_directory_rejected(self): | ||
| 1721 | # ARM Thumb-2 (0x1C4) | ||
| 1722 | buf = bytearray(build_image(is64=False, with_directories=True)) | ||
| 1723 | struct.pack_into("<H", buf, 0x44, 0x01C4) | ||
| 1724 | img = pe_inspect.PeImage(bytes(buf)) | ||
| 1725 | pdata = pe_inspect._inspect_pdata(img) | ||
| 1726 | self.assertTrue(pdata["present"]) | ||
| 1727 | self.assertIn("unsupported", pdata["format"]) | ||
| 1728 | self.assertEqual(pdata["parsed_count"], 0) | ||
| 1729 | self.assertIn("unsupported machine", pdata["rejection_reason"]) | ||
| 1730 | |||
| 1731 | |||
| 1386 | if __name__ == "__main__": | 1732 | if __name__ == "__main__": |
| 1387 | unittest.main() | 1733 | unittest.main() |
diff --git a/tests/test_red_green.py b/tests/test_red_green.py index 5f4b89529..85ccae0ee 100644 --- a/tests/test_red_green.py +++ b/tests/test_red_green.py | |||
| @@ -2,11 +2,15 @@ | |||
| 2 | import io | 2 | import io |
| 3 | import json | 3 | import json |
| 4 | import os | 4 | import os |
| 5 | import py_compile | ||
| 5 | import subprocess | 6 | import subprocess |
| 6 | import sys | 7 | import sys |
| 7 | import tempfile | 8 | import tempfile |
| 9 | import time | ||
| 8 | import unittest | 10 | import unittest |
| 9 | from contextlib import redirect_stderr, redirect_stdout | 11 | from contextlib import redirect_stderr, redirect_stdout |
| 12 | from pathlib import Path | ||
| 13 | from unittest import mock | ||
| 10 | 14 | ||
| 11 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | 15 | ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) |
| 12 | sys.path.insert(0, os.path.join(ROOT, "scripts")) | 16 | 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__") | |||
| 66 | ''' | 70 | ''' |
| 67 | 71 | ||
| 68 | 72 | ||
| 73 | def hang_stub(repo, where): | ||
| 74 | """STUB_CARGO that sleeps when value() is 2 and spare() is 5 (Mutation.BASE's second hunk undone alone): before | ||
| 75 | its `Running` line, as a build that hangs, or after it, as a test that hangs.""" | ||
| 76 | hang = "sys.stdout.flush()\nif fns.get('value') == '2' and fns.get('spare') == '5':\n __import__('time').sleep(120)\n" | ||
| 77 | text = STUB_CARGO.replace('print(" Running', (hang if where == "build" else "") + 'print(" Running') | ||
| 78 | text = text.replace("failed = False\n", "failed = False\n" + (hang if where == "test" else "")) | ||
| 79 | path = os.path.join(repo.tmp.name, f"cargo_hang_{where}.py") | ||
| 80 | with open(path, "w", encoding="utf-8", newline="\n") as f: | ||
| 81 | f.write(text) | ||
| 82 | return path | ||
| 83 | |||
| 84 | |||
| 69 | class Repo: | 85 | class Repo: |
| 70 | def crash_stub(self, mode): | 86 | def crash_stub(self, mode): |
| 71 | path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py") | 87 | path = os.path.join(self.tmp.name, f"cargo_crash_{mode}.py") |
| @@ -235,6 +251,372 @@ class Python(unittest.TestCase): | |||
| 235 | self.assertIn("does not import", r["red"]["no_build"][0]) | 251 | self.assertIn("does not import", r["red"]["no_build"][0]) |
| 236 | self.assertEqual(code, 1) | 252 | self.assertEqual(code, 1) |
| 237 | 253 | ||
| 254 | # The same test, and once more in a process it starts, as the tests of a command-line tool do. | ||
| 255 | CHILD_TEST = TEST + ( | ||
| 256 | "\n def test_two_in_a_child(self):\n" | ||
| 257 | " import subprocess\n" | ||
| 258 | " tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n" | ||
| 259 | " code = 'import sys; sys.path.insert(0, sys.argv[1]); import bar; print(bar.two())'\n" | ||
| 260 | " out = subprocess.run([sys.executable, '-I', '-c', code, tools], capture_output=True, text=True)\n" | ||
| 261 | " self.assertEqual(out.stdout.strip(), '2')\n") | ||
| 262 | |||
| 263 | def test_stale_bytecode_in_the_work_tree_is_never_run(self): | ||
| 264 | repo = Repo(self) | ||
| 265 | repo.commit("base", {".gitignore": "__pycache__/\n", "tools/bar.py": "def two():\n return 1\n"}) | ||
| 266 | repo.git("switch", "-q", "-c", "pr") | ||
| 267 | repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.CHILD_TEST}) | ||
| 268 | self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green") | ||
| 269 | # An ignored .pyc of the fixed bar.py left in the work tree (`git clean` keeps ignored files). An unchecked-hash | ||
| 270 | # .pyc is taken without looking at the source, like a timestamp one whose time and size still match. | ||
| 271 | tools = os.path.join(repo.dir, ".git", "red-green", "tree", "tools") | ||
| 272 | src = os.path.join(repo.tmp.name, "bar_fixed.py") | ||
| 273 | with open(src, "w", encoding="utf-8", newline="\n") as f: | ||
| 274 | f.write("def two():\n return 2\n") | ||
| 275 | py_compile.compile(src, cfile=os.path.join(tools, "__pycache__", f"bar.{sys.implementation.cache_tag}.pyc"), | ||
| 276 | doraise=True, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH) | ||
| 277 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 278 | # Read, it would make red pass in both processes and the undone fix not caught. | ||
| 279 | self.assertEqual((code, r["verdict"]), (0, "red then green"), r) | ||
| 280 | self.assertEqual(r["rows"]["red_to_green"], ["tests/test_bar.py::test_bar.T.test_two", | ||
| 281 | "tests/test_bar.py::test_bar.T.test_two_in_a_child"]) | ||
| 282 | self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) | ||
| 283 | |||
| 284 | def test_bytecode_it_cannot_remove_stops_the_run_with_the_tree_put_back(self): | ||
| 285 | repo = Repo(self) | ||
| 286 | repo.commit("base", {".gitignore": "__pycache__/\n", "tools/bar.py": "def two():\n return 1\n"}) | ||
| 287 | repo.git("switch", "-q", "-c", "pr") | ||
| 288 | repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": self.TEST}) | ||
| 289 | self.assertEqual(repo.run("--no-cargo")[1]["verdict"], "red then green") | ||
| 290 | tree = os.path.join(repo.dir, ".git", "red-green", "tree") | ||
| 291 | cache = os.path.join(tree, "tools", "__pycache__") | ||
| 292 | os.makedirs(cache, exist_ok=True) | ||
| 293 | block_removal(self, cache) | ||
| 294 | code, r, err = repo.run("--no-cargo") | ||
| 295 | self.assertEqual((code, r), (2, None), err) | ||
| 296 | self.assertIn("cannot remove", err) | ||
| 297 | self.assertIn(os.path.join("tools", "__pycache__"), err) | ||
| 298 | # The red side had begun: the tree is back on the base all the same. | ||
| 299 | status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout | ||
| 300 | self.assertEqual(status, "") | ||
| 301 | |||
| 302 | |||
| 303 | def link_dir(test, link, target): | ||
| 304 | """A directory junction on Windows (no privilege needed), a symbolic link elsewhere; removed at the end of `test` | ||
| 305 | before its temporary folder, so that the folder's cleanup does not go through it.""" | ||
| 306 | if os.name == "nt": | ||
| 307 | subprocess.run(["cmd", "/c", "mklink", "/J", link, target], check=True, capture_output=True) | ||
| 308 | test.addCleanup(os.rmdir, link) | ||
| 309 | else: | ||
| 310 | os.symlink(target, link, target_is_directory=True) | ||
| 311 | test.addCleanup(os.unlink, link) | ||
| 312 | |||
| 313 | |||
| 314 | def deny_listing(test, folder): | ||
| 315 | """Takes away the right to list `folder` (a deny entry for Everyone on Windows, mode 0 elsewhere) until the end of | ||
| 316 | `test`.""" | ||
| 317 | if os.name == "nt": | ||
| 318 | subprocess.run(["icacls", folder, "/deny", "*S-1-1-0:(RD)"], check=True, capture_output=True) | ||
| 319 | test.addCleanup(subprocess.run, ["icacls", folder, "/remove:d", "*S-1-1-0"], check=True, capture_output=True) | ||
| 320 | else: | ||
| 321 | if os.geteuid() == 0: | ||
| 322 | test.skipTest("root lists any folder") | ||
| 323 | os.chmod(folder, 0) | ||
| 324 | test.addCleanup(os.chmod, folder, 0o700) | ||
| 325 | |||
| 326 | |||
| 327 | def block_removal(test, folder): | ||
| 328 | """Keeps `folder` from being removed until the end of `test`: a file in it held open on Windows, the folder | ||
| 329 | read-only elsewhere.""" | ||
| 330 | path = os.path.join(folder, "held.pyc") | ||
| 331 | if os.name == "nt": | ||
| 332 | held = open(path, "wb") | ||
| 333 | test.addCleanup(held.close) | ||
| 334 | else: | ||
| 335 | if os.geteuid() == 0: | ||
| 336 | test.skipTest("root removes any file") | ||
| 337 | open(path, "wb").close() | ||
| 338 | os.chmod(folder, 0o500) | ||
| 339 | test.addCleanup(os.chmod, folder, 0o700) | ||
| 340 | |||
| 341 | |||
| 342 | class DropBytecode(unittest.TestCase): | ||
| 343 | def setUp(self): | ||
| 344 | tmp = tempfile.TemporaryDirectory(prefix="red-green-test-", ignore_cleanup_errors=True) | ||
| 345 | self.addCleanup(tmp.cleanup) | ||
| 346 | self.tree, self.outside = os.path.join(tmp.name, "tree"), os.path.join(tmp.name, "outside") | ||
| 347 | for folder in (os.path.join(self.tree, "tools", "__pycache__"), os.path.join(self.outside, "__pycache__")): | ||
| 348 | os.makedirs(folder) | ||
| 349 | with open(os.path.join(folder, "x.pyc"), "wb") as f: | ||
| 350 | f.write(b"x") | ||
| 351 | |||
| 352 | def check(self): | ||
| 353 | rg.drop_bytecode(Path(self.tree)) | ||
| 354 | self.assertFalse(os.path.exists(os.path.join(self.tree, "tools", "__pycache__"))) | ||
| 355 | self.assertTrue(os.path.isfile(os.path.join(self.outside, "__pycache__", "x.pyc"))) | ||
| 356 | |||
| 357 | def test_a_link_out_of_the_tree_is_not_followed(self): | ||
| 358 | link_dir(self, os.path.join(self.tree, "tools", "link"), self.outside) | ||
| 359 | self.check() | ||
| 360 | |||
| 361 | def test_a_link_named_pycache_is_left_alone(self): | ||
| 362 | link_dir(self, os.path.join(self.tree, "__pycache__"), os.path.join(self.outside, "__pycache__")) | ||
| 363 | self.check() | ||
| 364 | |||
| 365 | def test_a_folder_it_cannot_list_is_skipped(self): | ||
| 366 | locked = os.path.join(self.tree, "locked") | ||
| 367 | os.makedirs(os.path.join(locked, "__pycache__")) | ||
| 368 | deny_listing(self, locked) | ||
| 369 | self.check() | ||
| 370 | |||
| 371 | |||
| 372 | @unittest.skipUnless(os.name == "nt", "job objects are Windows'") | ||
| 373 | class Job(unittest.TestCase): | ||
| 374 | def test_a_job_object_that_cannot_be_joined_is_said_once(self): | ||
| 375 | err = io.StringIO() | ||
| 376 | with mock.patch.object(rg._KERNEL32, "AssignProcessToJobObject", return_value=0), \ | ||
| 377 | mock.patch.object(rg, "_JOB_WARNED", False, create=True), redirect_stderr(err): | ||
| 378 | runs = [rg.run_output([sys.executable, "-c", "print(1)"], Path(ROOT), timeout=60) for _ in range(2)] | ||
| 379 | self.assertEqual([(code, out.strip()) for code, out in runs], [(0, "1"), (0, "1")]) | ||
| 380 | self.assertEqual(err.getvalue().count("no Windows job object"), 1, err.getvalue()) | ||
| 381 | |||
| 382 | |||
| 383 | class Mutation(unittest.TestCase): | ||
| 384 | # Two code changes far enough apart to be two hunks: the tested one and one no test looks at. | ||
| 385 | BASE = ("pub fn value() -> u32 {\n 1\n}\n\n" + "".join(f"// padding line {i}\n" for i in range(10)) | ||
| 386 | + "\npub fn spare() -> u32 {\n 5\n}\n" + LIB[LIB.index("\n#[cfg(test)]"):]) | ||
| 387 | |||
| 388 | def test_each_code_hunk_undone_alone_is_caught_or_not(self): | ||
| 389 | repo = Repo(self) | ||
| 390 | repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', | ||
| 391 | "d3d12/crates/foo/src/lib.rs": self.BASE}) | ||
| 392 | repo.git("switch", "-q", "-c", "pr") | ||
| 393 | repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( | ||
| 394 | " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", | ||
| 395 | "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) | ||
| 396 | code, r, _ = repo.run("--mutate") | ||
| 397 | self.assertEqual((code, r["verdict"]), (0, "red then green"), r) | ||
| 398 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "not caught")]) | ||
| 399 | text = rg.report(r) | ||
| 400 | self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 not caught", text) | ||
| 401 | self.assertIn("d3d12/crates/foo/src/lib.rs:17: not caught", text) | ||
| 402 | # The worktree is back on the base afterwards: the mutations left nothing behind. | ||
| 403 | tree = os.path.join(repo.dir, ".git", "red-green", "tree") | ||
| 404 | status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout | ||
| 405 | self.assertEqual(status, "") | ||
| 406 | |||
| 407 | def test_a_cargo_run_that_hangs_is_stopped_and_said_where(self): | ||
| 408 | repo = Repo(self) | ||
| 409 | repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', | ||
| 410 | "d3d12/crates/foo/src/lib.rs": self.BASE}) | ||
| 411 | repo.git("switch", "-q", "-c", "pr") | ||
| 412 | repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( | ||
| 413 | " 5\n", " 6\n").replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", | ||
| 414 | "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) | ||
| 415 | # A test binary that hangs is caught; a build that hangs (no `Running` line yet) is no answer. | ||
| 416 | for where, result in (("test", "caught by timeout"), ("build", "timed out building")): | ||
| 417 | _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, where)) | ||
| 418 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, result)], where) | ||
| 419 | |||
| 420 | def test_a_test_stopped_running_outweighs_a_build_stopped(self): | ||
| 421 | # Undone alone, the second hunk makes cargo hang in its build and a Python test hang while running: the hunk | ||
| 422 | # is caught by timeout, since a test did hang. | ||
| 423 | watch = ("import os, time, unittest\n\n\nclass T(unittest.TestCase):\n def test_lib(self):\n" | ||
| 424 | " root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n" | ||
| 425 | " with open(os.path.join(root, 'd3d12', 'crates', 'foo', 'src', 'lib.rs'), encoding='utf-8') as f:\n" | ||
| 426 | " text = f.read()\n" | ||
| 427 | " if ' 2\\n' in text and ' 5\\n' in text:\n" | ||
| 428 | " time.sleep(120)\n") | ||
| 429 | repo = Repo(self) | ||
| 430 | repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', | ||
| 431 | "d3d12/crates/foo/src/lib.rs": self.BASE}) | ||
| 432 | repo.git("switch", "-q", "-c", "pr") | ||
| 433 | repo.commit("fix", {"tests/test_watch.py": watch, | ||
| 434 | "d3d12/crates/foo/src/lib.rs": self.BASE.replace(" 1\n", " 2\n").replace( | ||
| 435 | " 5\n", " 6\n").replace( | ||
| 436 | "fn value_is_one() {\n assert_eq!(super::value(), 1);", | ||
| 437 | "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) | ||
| 438 | _code, r, _ = repo.run("--mutate", "--mutate-timeout", "5", "--cargo", hang_stub(repo, "build")) | ||
| 439 | self.assertEqual(r["verdict"], "red then green", r) | ||
| 440 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (17, "caught by timeout")]) | ||
| 441 | |||
| 442 | def test_a_hunk_that_only_deletes_a_test_is_not_mutated(self): | ||
| 443 | # The pull request also deletes an obsolete test: a hunk of test code only, like the one that renames the | ||
| 444 | # other test. Neither is mutated; only the fix is. | ||
| 445 | spare_test = "\n #[test]\n fn spare_is_five() {\n assert_eq!(super::spare(), 5);\n }\n" | ||
| 446 | base = ("pub fn value() -> u32 {\n 1\n}\n\npub fn spare() -> u32 {\n 5\n}\n" | ||
| 447 | + LIB[LIB.index("\n#[cfg(test)]"):LIB.rindex("}")] | ||
| 448 | + "".join(f" // padding line {i}\n" for i in range(10)) + spare_test + "}\n") | ||
| 449 | repo = Repo(self) | ||
| 450 | repo.commit("base", {"d3d12/crates/foo/Cargo.toml": '[package]\nname = "foo"\n', | ||
| 451 | "d3d12/crates/foo/src/lib.rs": base}) | ||
| 452 | repo.git("switch", "-q", "-c", "pr") | ||
| 453 | repo.commit("fix", {"d3d12/crates/foo/src/lib.rs": base.replace(" 1\n", " 2\n").replace(spare_test, "") | ||
| 454 | .replace("fn value_is_one() {\n assert_eq!(super::value(), 1);", | ||
| 455 | "fn value_is_two() {\n assert_eq!(super::value(), 2);")}) | ||
| 456 | code, r, _ = repo.run("--mutate") | ||
| 457 | self.assertEqual((code, r["verdict"]), (0, "red then green"), r) | ||
| 458 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught")]) | ||
| 459 | |||
| 460 | def test_a_python_fix_undone_is_caught(self): | ||
| 461 | repo = Repo(self) | ||
| 462 | repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) | ||
| 463 | repo.git("switch", "-q", "-c", "pr") | ||
| 464 | repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) | ||
| 465 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 466 | self.assertEqual(r["verdict"], "red then green", r) | ||
| 467 | self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], [("tools/bar.py", "caught")]) | ||
| 468 | |||
| 469 | # tools/bar.py with two hunks far apart, two() at line 2 (the fix) and settled() at line 15; a test of two(). | ||
| 470 | BAR = ("def two():\n return 1\n" + "".join(f"# padding line {i}\n" for i in range(10)) | ||
| 471 | + "\ndef settled():\n return False\n") | ||
| 472 | |||
| 473 | def bar_repo(self, body, base_files=None): | ||
| 474 | test = ("import os, subprocess, sys, unittest\n" | ||
| 475 | "tools = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'tools')\n" | ||
| 476 | "sys.path.insert(0, tools)\n" | ||
| 477 | "import bar\n\n\nclass T(unittest.TestCase):\n def test_two(self):\n" + body | ||
| 478 | + " self.assertEqual(bar.two(), 2)\n") | ||
| 479 | repo = Repo(self) | ||
| 480 | repo.commit("base", {"tools/bar.py": self.BAR, **(base_files or {})}) | ||
| 481 | repo.git("switch", "-q", "-c", "pr") | ||
| 482 | repo.commit("fix", {"tools/bar.py": self.BAR.replace("return 1", "return 2").replace("False", "True"), | ||
| 483 | "tests/test_bar.py": test}) | ||
| 484 | return repo | ||
| 485 | |||
| 486 | def test_a_mutated_run_that_hangs_is_caught_by_timeout(self): | ||
| 487 | # Undone alone, the second hunk makes the test start a process that sleeps. Red has neither hunk, so it does | ||
| 488 | # not hang there. | ||
| 489 | repo = self.bar_repo(" if bar.two() == 2 and not bar.settled():\n" | ||
| 490 | " subprocess.run([sys.executable, '-c', 'import time; time.sleep(120)'])\n") | ||
| 491 | start = time.monotonic() | ||
| 492 | _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "5") | ||
| 493 | self.assertEqual(r["verdict"], "red then green", r) | ||
| 494 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "caught by timeout")]) | ||
| 495 | self.assertIn("mutations (2 hunks undone one at a time): 1 caught, 1 caught by timeout", rg.report(r)) | ||
| 496 | # The run did not wait for the sleeping process. | ||
| 497 | self.assertLess(time.monotonic() - start, 60) | ||
| 498 | |||
| 499 | def test_a_process_left_behind_does_not_hold_a_mutated_run(self): | ||
| 500 | # Undone alone, the fix makes the test leave a process behind that outlives it with its output; the test still | ||
| 501 | # fails, so the hunk is caught, as soon as the test ends and not when the timeout runs out. The process left | ||
| 502 | # behind is stopped then: 5 s later, it would write a file beside the work tree. (Kept in T, so that no | ||
| 503 | # ResourceWarning cuts the test's line in the verbose output.) | ||
| 504 | repo = self.bar_repo( | ||
| 505 | " if bar.two() != 2 and bar.settled():\n" | ||
| 506 | " mark = os.path.join(os.path.dirname(os.path.dirname(tools)), 'left-behind')\n" | ||
| 507 | " T.left = subprocess.Popen([sys.executable, '-c', 'import sys, time; time.sleep(5); " | ||
| 508 | "open(sys.argv[1], \"w\").close()', mark])\n") | ||
| 509 | start = time.monotonic() | ||
| 510 | _code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-timeout", "20") | ||
| 511 | self.assertEqual(r["verdict"], "red then green", r) | ||
| 512 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) | ||
| 513 | self.assertLess(time.monotonic() - start, 20) | ||
| 514 | time.sleep(6) # it started before the run ended | ||
| 515 | self.assertFalse(os.path.exists(os.path.join(repo.dir, ".git", "red-green", "left-behind"))) | ||
| 516 | |||
| 517 | def test_a_test_that_dirties_the_tree_does_not_change_the_next_hunk(self): | ||
| 518 | # When it finds two() wrong, the test writes into a tracked file that it also checks. Each mutation starts from | ||
| 519 | # the green tree, so the second hunk (settled(), which no test looks at) is not caught for that. | ||
| 520 | repo = self.bar_repo(" flag = os.path.join(tools, 'flag.txt')\n" | ||
| 521 | " if bar.two() != 2:\n" | ||
| 522 | " with open(flag, 'w', encoding='utf-8', newline='\\n') as f:\n" | ||
| 523 | " f.write('dirty\\n')\n" | ||
| 524 | " with open(flag, encoding='utf-8') as f:\n" | ||
| 525 | " self.assertEqual(f.read(), 'clean\\n')\n", {"tools/flag.txt": "clean\n"}) | ||
| 526 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 527 | self.assertEqual((code, r["verdict"]), (0, "red then green"), r) | ||
| 528 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (15, "not caught")]) | ||
| 529 | tree = os.path.join(repo.dir, ".git", "red-green", "tree") | ||
| 530 | status = subprocess.run(["git", "status", "--porcelain"], cwd=tree, capture_output=True, text=True).stdout | ||
| 531 | self.assertEqual(status, "") | ||
| 532 | |||
| 533 | def test_hunks_past_mutate_max_are_listed_as_not_tried(self): | ||
| 534 | base = "".join(f"def f{n}():\n return 1\n" + "# padding\n" * 4 for n in range(1, 5)) | ||
| 535 | test = Python.TEST.replace("bar.two(), 2", "bar.f1(), 2") | ||
| 536 | repo = Repo(self) | ||
| 537 | repo.commit("base", {"tools/bar.py": base}) | ||
| 538 | repo.git("switch", "-q", "-c", "pr") | ||
| 539 | repo.commit("fix", {"tools/bar.py": base.replace("return 1", "return 2"), "tests/test_bar.py": test}) | ||
| 540 | code, r, _ = repo.run("--no-cargo", "--mutate", "--mutate-max", "2") | ||
| 541 | self.assertEqual((code, r["verdict"]), (0, "red then green"), r) | ||
| 542 | self.assertEqual([(m["line"], m["result"]) for m in r["mutations"]], [(2, "caught"), (8, "not caught")]) | ||
| 543 | self.assertEqual(r["mutations_skipped"], [{"file": "tools/bar.py", "line": 14}, | ||
| 544 | {"file": "tools/bar.py", "line": 20}]) | ||
| 545 | self.assertIn("not tried, past --mutate-max: tools/bar.py:14, tools/bar.py:20", rg.report(r)) | ||
| 546 | |||
| 547 | def test_a_test_only_pull_request_has_nothing_to_undo(self): | ||
| 548 | repo = Repo(self) | ||
| 549 | repo.commit("base", {"tools/bar.py": "def two():\n return 2\n"}) | ||
| 550 | repo.git("switch", "-q", "-c", "pr") | ||
| 551 | repo.commit("test", {"tests/test_bar.py": Python.TEST}) | ||
| 552 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 553 | # The verdict and exit code are those of any test that passes on both. | ||
| 554 | self.assertEqual((code, r["verdict"]), (1, "no red"), r) | ||
| 555 | self.assertEqual(r["mutations"], []) | ||
| 556 | self.assertEqual(r["mutations_not_run"], "nothing to undo: the diff changes no Rust or Python code outside its " | ||
| 557 | "tests") | ||
| 558 | self.assertIn("mutations: nothing to undo: the diff changes no Rust or Python code outside its tests", | ||
| 559 | rg.report(r)) | ||
| 560 | |||
| 561 | def test_code_only_in_added_files_has_nothing_to_undo_in_the_files_it_modifies(self): | ||
| 562 | repo = Repo(self) | ||
| 563 | repo.commit("base", {"README.md": "base\n"}) | ||
| 564 | repo.git("switch", "-q", "-c", "pr") | ||
| 565 | repo.commit("new tool", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) | ||
| 566 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 567 | self.assertEqual((code, r["verdict"]), (1, "red does not build"), r) | ||
| 568 | self.assertEqual((r["mutations"], r["added_not_mutated"]), ([], ["tools/bar.py"])) | ||
| 569 | text = rg.report(r) | ||
| 570 | self.assertIn("mutations: nothing to undo in the files it modifies: its code changes are in files it adds", text) | ||
| 571 | self.assertIn("not mutated, added by the pull request: tools/bar.py", text) | ||
| 572 | |||
| 573 | def test_code_with_no_test_gone_red_is_not_mutated_and_said_so(self): | ||
| 574 | repo = Repo(self) | ||
| 575 | repo.commit("base", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 3\n"}) | ||
| 576 | repo.git("switch", "-q", "-c", "pr") | ||
| 577 | repo.commit("change", {"tools/bar.py": "def two():\n return 2\n\n\ndef three():\n return 4\n", | ||
| 578 | "tests/test_bar.py": Python.TEST}) | ||
| 579 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 580 | self.assertEqual((code, r["verdict"]), (1, "no red"), r) | ||
| 581 | self.assertEqual(r["mutations"], []) | ||
| 582 | self.assertIn("mutations: not run: no test went red then green", rg.report(r)) | ||
| 583 | |||
| 584 | def test_files_the_pull_request_adds_are_listed_as_not_mutated(self): | ||
| 585 | repo = Repo(self) | ||
| 586 | repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) | ||
| 587 | repo.git("switch", "-q", "-c", "pr") | ||
| 588 | repo.commit("fix", {"tools/helper.py": "def value():\n return 2\n", | ||
| 589 | "tools/bar.py": "from helper import value\n\n\ndef two():\n return value()\n", | ||
| 590 | "tests/test_bar.py": Python.TEST}) | ||
| 591 | code, r, _ = repo.run("--no-cargo", "--mutate") | ||
| 592 | self.assertEqual((code, r["verdict"]), (0, "red then green"), r) | ||
| 593 | self.assertEqual([(m["file"], m["result"]) for m in r["mutations"]], | ||
| 594 | [("tools/bar.py", "caught"), ("tools/bar.py", "caught")]) | ||
| 595 | # helper.py holds the change and is never undone: the report says so rather than read as full coverage. | ||
| 596 | self.assertEqual(r["added_not_mutated"], ["tools/helper.py"]) | ||
| 597 | self.assertIn("not mutated, added by the pull request: tools/helper.py", rg.report(r)) | ||
| 598 | |||
| 599 | def test_mutate_options_are_checked(self): | ||
| 600 | for args, why in ((["--mutate", "--mutate-max", "0"], "--mutate-max"), | ||
| 601 | (["--mutate", "--mutate-timeout", "0"], "--mutate-timeout"), | ||
| 602 | (["--mutate", "--mutate-timeout", "nan"], "--mutate-timeout"), | ||
| 603 | (["--mutate", "--mutate-timeout", "inf"], "--mutate-timeout"), | ||
| 604 | (["--mutate-max", "3"], "--mutate"), (["--mutate-timeout", "60"], "--mutate")): | ||
| 605 | err = io.StringIO() | ||
| 606 | with redirect_stderr(err), self.assertRaises(SystemExit) as stop: | ||
| 607 | rg.main(["pr", "--no-fetch", *args]) | ||
| 608 | self.assertEqual(stop.exception.code, 2, args) | ||
| 609 | self.assertIn(why, err.getvalue().splitlines()[-1], args) | ||
| 610 | |||
| 611 | def test_no_mutation_without_the_option(self): | ||
| 612 | repo = Repo(self) | ||
| 613 | repo.commit("base", {"tools/bar.py": "def two():\n return 1\n"}) | ||
| 614 | repo.git("switch", "-q", "-c", "pr") | ||
| 615 | repo.commit("fix", {"tools/bar.py": "def two():\n return 2\n", "tests/test_bar.py": Python.TEST}) | ||
| 616 | _code, r, _ = repo.run("--no-cargo") | ||
| 617 | self.assertIsNone(r["mutations"]) | ||
| 618 | self.assertNotIn("mutations", rg.report(r)) | ||
| 619 | |||
| 238 | 620 | ||
| 239 | class CompilerCrash(unittest.TestCase): | 621 | class CompilerCrash(unittest.TestCase): |
| 240 | def fixed_repo(self): | 622 | def fixed_repo(self): |