"""mutate-changes run on a branch, against fake mutation tools that log how they were called.""" import contextlib import io import os import pathlib import re import shutil import subprocess import sys import tempfile import unittest import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import isolated_env from mutate_changes import main TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes" SETUP = "[mutmut]\ndo_not_mutate = *_old.py\n" PASSED = ["mutmut in pkg: 2 mutants on changed lines, 1 not killed.", "pkg/calc.py:6: survived: return n / 3"] # Stands in for mutmut, run through --prefix as `python3 mutmut ...` in the scratch copy. It logs each call with # the folder it runs in and the setup.cfg it finds there, then writes a mutants/ copy and prints results, both shaped like mutmut 3's. FAKE_MUTMUT = r"""import os, pathlib, sys log, mode, args = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3:] config = pathlib.Path("setup.cfg").read_text() with log.open("a") as written: written.write(f"{os.getcwd()}\n{' '.join(args)}\n{config}---\n") if args[:2] == ["mutmut", "results"]: if mode == "results-fail" or args[2:] != ["--all", "true"]: sys.exit("mutmut results broke") double, triple_1, triple_2 = ("no tests",) * 3 if mode == "no-test" else ("survived", "survived", "killed") print(f" other.x_f__mutmut_1: survived\n calc.x_double__mutmut_1: {double}\n calc.x_triple__mutmut_1: {triple_1}\n calc.x_triple__mutmut_2: {triple_2}") elif mode == "fails-once" and not ("--deselect=test_calc.py::test_slow[n=1]" in config and "--ignore=test_io.py" in config): print("==== short test summary info ====\nFAILED test_calc.py::test_slow[n=1] - boom\nERROR test_io.py - FileNotFoundError\nfailed to collect stats. runner returned 1") sys.exit(1) else: if mode != "no-copy": pathlib.Path("mutants").mkdir(exist_ok=True) functions = ["x_double__mutmut_orig(n): # doubles\n\treturn n * 2", "x_double__mutmut_1(n): # doubles\n\treturn n / 2", "x_triple__mutmut_orig(n):\n\treturn n * 3", "x_triple__mutmut_1(n):\n\treturn n / 3", "x_triple__mutmut_2(n):\n\treturn n * 4"] pathlib.Path("mutants/calc.py").write_bytes(b"# \xff is not UTF-8\n" + "".join(f"def {function}\n" for function in functions).encode()) if mode == "no-test": print("Stopping early, because we could not find any test case for any mutant.") sys.exit(1) """ # cargo-mutants, Infection and Stryker, which log how they were called and exit with the code the test gives. cargo-mutants also # logs the diff it is given and writes its outcome files, all but unviable.txt, as a run without an unviable mutant does. FAKE_TOOLS = r"""import pathlib, sys log, code, args = pathlib.Path(sys.argv[1]), int(sys.argv[2]), sys.argv[3:] with log.open("a") as written: written.write(" ".join(args) + "\n") if args[0] == "cargo": written.write(pathlib.Path(args[args.index("--in-diff") + 1]).read_text()) outcomes = pathlib.Path(args[args.index("--output") + 1], "mutants.out") outcomes.mkdir() (outcomes / "caught.txt").write_text("src/lib.rs:2:7: replace + with - in add\n") (outcomes / "missed.txt").write_text("src/lib.rs:2:5: replace add -> i32 with 0\n") (outcomes / "timeout.txt").write_text("src/lib.rs:2:7: replace + with * in add\n") print(f"{args[0]} reports") sys.exit(code) """ @contextlib.contextmanager def stdin_holding(text: str): """This process's stdin, the one a child inherits, as a pipe holding text.""" read, write = os.pipe() os.write(write, text.encode()) os.close(write) saved = os.dup(0) os.dup2(read, 0) os.close(read) try: yield finally: os.dup2(saved, 0) os.close(saved) class MutateChangesRuns(unittest.TestCase): def setUp(self): temp = tempfile.TemporaryDirectory() self.addCleanup(temp.cleanup) self.temp = pathlib.Path(temp.name) self.checkout = self.temp / "proj" (self.checkout / "pkg").mkdir(parents=True) (self.checkout / "pkg" / "setup.cfg").write_text(SETUP) (self.checkout / "pkg" / "calc.py").write_text("def double(n):\n\treturn n * 2\n") (self.checkout / "pkg" / "test_calc.py").write_text("") self.git("init", "-q", "-b", "main") self.commit() self.git("checkout", "-q", "-b", "work") # git lists the README first, and mutate-changes mutates no Markdown. (self.checkout / "README.md").write_text("Doubles and triples.\n") (self.checkout / "pkg" / "calc.py").write_text("def double(n): # doubles\n\treturn n * 2\n\n\ndef triple(n):\n\treturn n * 3\n") (self.checkout / "pkg" / "test_calc.py").write_text("# changed, but a test file is not mutated\n") self.commit() # Settings a user may have that change what git diff prints, and a file git lists as untracked and one it ignores. for name, value in (("color.diff", "always"), ("diff.relative", "true"), ("diff.external", "true"), ("diff.blank.textconv", "true")): self.git("config", name, value) (self.checkout / ".git" / "info").mkdir(exist_ok=True) (self.checkout / ".git" / "info" / "attributes").write_text("* diff=blank\n") (self.checkout / ".git" / "info" / "exclude").write_text("*.log\n") (self.checkout / "pkg" / "fixture.txt").write_text("") (self.checkout / "pkg" / "run.log").write_text("") (self.temp / "fake_mutmut.py").write_text(FAKE_MUTMUT) (self.temp / "fake_tools.py").write_text(FAKE_TOOLS) self.log = self.temp / "calls.log" def git(self, *args): return subprocess.run(["git", *args], check=True, capture_output=True, cwd=self.checkout, encoding="utf-8", env={**isolated_env(), "GIT_CONFIG_GLOBAL": "/dev/null"}).stdout def commit(self): self.git("add", ".") self.git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "-m", "x") def run_tool(self, *args, cwd=None, env=None): """Run mutate-changes in this process, from cwd, else the checkout: mutmut counts only the code a test reaches in its own process.""" before = os.getcwd() os.chdir(cwd or self.checkout) try: with unittest.mock.patch.dict(os.environ, {**isolated_env(), **(env or {})}, clear=True), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: code = main.main(list(args)) finally: os.chdir(before) return subprocess.CompletedProcess(args, code, out.getvalue(), err.getvalue()) def faked(self, mode): return ["--prefix", f"python3 {self.temp / 'fake_mutmut.py'} {self.log} {mode}"] def change_rust_php_and_typescript(self): """Commit a Rust, a PHP and a TypeScript file, then change line 2 of each in the working tree, PHP's with a byte that is not UTF-8.""" (self.checkout / "src").mkdir() (self.checkout / "src" / "lib.rs").write_text("pub fn add(a: i32, b: i32) -> i32 {\n\ta + b\n}\n") (self.checkout / "src" / "Calc.php").write_text(" i32 {\n\tb + a\n}\n") (self.checkout / "src" / "Calc.php").write_bytes(b"&2; printf '\\377'; false") self.assertEqual((ran.returncode, ran.stderr), (1, "\n".join(["mutmut run in pkg exited 1:", *map(str, range(8, 46)), "broken", "�"]) + "\n")) def test_mutmut_results_that_fails_fails_the_run(self): ran = self.run_tool(*self.faked("results-fail")) self.assertEqual((ran.returncode, ran.stderr), (1, "mutmut results in pkg exited 1:\nmutmut results broke\n")) def test_a_tool_gets_an_empty_input_in_place_of_the_terminal(self): # npx, for one, asks before it installs a package, and would wait for an answer. with stdin_holding("y\n"): ran = self.run_tool("--prefix", "cat; false") self.assertEqual(ran.stderr, "mutmut run in pkg exited 1:\n") def test_without_a_prefix_each_tool_runs_from_path(self): tools = self.temp / "tools" tools.mkdir() (tools / "git").symlink_to(shutil.which("git")) ran = self.run_tool(env={"PATH": str(tools)}) self.assertEqual(ran.returncode, 1) self.assertRegex(ran.stderr, "^mutmut run .* could not start: ") (tools / "mutmut").write_text(f'#!/bin/sh\nexec {sys.executable} {self.temp / "fake_mutmut.py"} {self.log} passes mutmut "$@"\n') (tools / "mutmut").chmod(0o755) ran = self.run_tool(env={"PATH": str(tools)}) self.assertEqual((ran.returncode, ran.stdout.splitlines()[:2]), (0, PASSED), ran.stderr) def test_rust_php_and_typescript_go_to_cargo_mutants_infection_and_stryker(self): self.change_rust_php_and_typescript() ran = self.run_tool("--base", "HEAD", "--jobs=3", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} 2") report = ["cargo-mutants: 3 mutants on changed lines, 2 not caught.", "src/lib.rs:2:5: missed: replace add -> i32 with 0", "src/lib.rs:2:7: timeout: replace + with * in add"] self.assertEqual((ran.returncode, ran.stdout.splitlines()[:-1]), (0, [*report, "Infection exited 2; its report:", "vendor/bin/infection reports", "Stryker exited 2; its report:", "npx reports"]), ran.stderr) calls = self.log.read_text().splitlines() self.assertRegex(calls[0], r"^cargo mutants --in-diff (\.mutate-changes-\w+)/branch\.diff --output \1 --jobs 3$") self.assertEqual([line for line in calls[1:-2] if line[:1] in "+-"], ["--- a/src/lib.rs", "+++ b/src/lib.rs", "-\ta + b", "+\tb + a"]) infection = f"vendor/bin/infection --git-diff-lines --git-diff-base={self.git('rev-parse', 'HEAD').strip()} --threads=3 --show-mutations=max --no-progress" self.assertEqual(calls[-2:], [infection, "npx stryker run --mutate src/calc.ts:2-2 --concurrency 3 --reporters clear-text"]) self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "README.md", "pkg", "src"]) def test_cargo_mutants_fails_the_run_unless_it_finished(self): self.change_rust_php_and_typescript() for code, failed in ((0, False), (1, True), (3, False), (4, True)): with self.subTest(code): ran = self.run_tool("--base", "HEAD", "--prefix", f"python3 {self.temp / 'fake_tools.py'} {self.log} {code}") self.assertEqual((ran.returncode, ran.stderr), (1, f"cargo mutants exited {code}:\ncargo reports\n") if failed else (0, "")) def test_a_branch_that_changes_no_mutated_language_says_so(self): ran = self.run_tool(*self.faked("passes"), "--base", "HEAD") self.assertEqual((ran.returncode, ran.stdout), (0, "No line the branch changes is in a language mutate-changes mutates.\n")) self.assertFalse(self.log.exists()) def test_help_prints_the_usage(self): for flag in ("-h", "--help"): with self.subTest(flag): ran = self.run_tool(flag) self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.")) def test_unknown_arguments_fail(self): for args in (["--jobs", "0"], ["--jobs", "x"], ["--jobs"], ["--colour"], ["--base", "a", "--base", "b"]): with self.subTest(args): ran = self.run_tool(*args) self.assertEqual(ran.returncode, 1) self.assertIn("usage: mutate-changes", ran.stderr) def test_the_launcher_runs_the_tool(self): # Run from the launcher's folder: there, under mutmut, the child finds the setup.cfg that mutmut's mutated code reads. ran = subprocess.run([str(TOOL), "--help"], capture_output=True, cwd=TOOL.parent, encoding="utf-8", env=isolated_env()) self.assertEqual((ran.returncode, ran.stdout.splitlines()[0]), (0, "Mutation-test the lines a branch adds or changes, and print each mutant its tests don't kill.")) if __name__ == "__main__": unittest.main()