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/test_red_green.py | |
| parent | 7c245a359b8bdb6d9985c6d3ffd2bee0609de911 (diff) | |
| parent | 895c472faa1c3d44a1358640f09c1f10e6a6a876 (diff) | |
Merge origin/main into carry/1346
Diffstat (limited to 'tests/test_red_green.py')
| -rw-r--r-- | tests/test_red_green.py | 382 |
1 files changed, 382 insertions, 0 deletions
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): |