diff --git a/README.md b/README.md index a2346fa..bbfe282 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,14 @@ generates coverage once, verifies the unmutated tests pass, and reruns every covered mutant so a previous kill cannot hide a weakened test. For faster differential mutation runs, use `ub mutate`. +When the test command is a Python `python -m unittest discover` with no shell +operators, comment, or `-k`, each Python mutant first runs the test modules that +import its module, directly or through other project modules, one at a time: +nearest import first, then fastest on the original code. The first failure +kills the mutant. When all pass, the full test command reruns, so the verdict +matches a full-suite run. A test module that fails on the original code is +skipped. + By default it prints one summary line per gate, the items that failed (one line per CRAP function, duplicate pair, and surviving or uncovered mutant, the first 20 of each), and a verdict. The coverage command's output appears only when coverage fails or is diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index f9cdc4e..f64104c 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -3,8 +3,11 @@ from __future__ import annotations import argparse +import ast import contextlib +import fnmatch import os +import shlex import sys import tempfile from pathlib import Path @@ -23,6 +26,7 @@ from ub_cli.vendor.mutator.coverage import covered_lines from ub_cli.vendor.mutator.report import format_results, format_site_log from ub_cli.vendor.mutator.runner import CommandRunner, test_plan +from ub_cli.vendor.mutator.workers import SKIP_LINK from tree_sitter_language_pack import Error as ParserError @@ -279,22 +283,197 @@ def _static_gates(root: Path, files, duplicates_files, bundle, options, coverage return crap + dry, incomplete + warnings +class FocusedRunner(CommandRunner): + """Run a mutant against the tests nearest its module, then the full command. + + Each focused command runs in turn; a failure is a kill. When every focused + command passes, the full command reruns, so a mutant only some other test + kills is still killed and no survivor is reported that the full command + would not report. + """ + + focus = () + + def run(self, command, cwd, timeout): + # Baselines run without a timeout; only mutant runs have one. + for focused in self.focus if timeout is not None else (): + result = super().run(focused, cwd, timeout) + if result.timed_out or result.code != 0: + return result + return super().run(command, cwd, timeout) + + +def _module_name(path: Path) -> str: + parts = [] if path.name == "__init__.py" else [path.stem] + folder = path.parent + while (folder / "__init__.py").is_file(): + parts.insert(0, folder.name) + folder = folder.parent + return ".".join(parts) + + +def _imports(path: Path, name: str) -> set[str]: + """Every module `path` names in an import statement, at any depth.""" + + try: + tree = ast.parse(path.read_bytes()) + except (OSError, SyntaxError, ValueError): + return set() + package = name.split(".") if path.name == "__init__.py" else name.split(".")[:-1] + found = set() + for node in ast.walk(tree): + if isinstance(node, ast.Import): + found.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + prefix = package[: len(package) - node.level + 1] if node.level else [] + base = ".".join(prefix + ([node.module] if node.module else [])) + found.add(base) + found.update(f"{base}.{alias.name}".lstrip(".") for alias in node.names) + return found + + +def python_imports(root: Path) -> dict[Path, tuple[str, set[str]]]: + """Each Python file under `root` with its module name and the modules it imports.""" + + graph = {} + for directory, folders, names in os.walk(root): + folders[:] = [ + folder + for folder in folders + if folder not in SKIP_LINK and folder != "node_modules" and not folder.startswith(".") + ] + for file_name in names: + if file_name.endswith(".py"): + path = Path(directory) / file_name + name = _module_name(path) + graph[path] = (name, _imports(path, name)) + return graph + + +def affected_tests(graph, module: str) -> list[list[str]]: + """The test*.py module stems that import `module`, grouped by import distance, nearest first.""" + + # shortcut: import statements only; import_module and subprocess imports are missed, + # which costs a full-command rerun, never a verdict. Follow them if survivors' reruns dominate. + reached = {module} + frontier = {module} + tiers = [] + while frontier: + frontier = { + name + for name, imported in graph.values() + if name not in reached + and any( + item == target or item.startswith(target + ".") + for item in imported + for target in frontier + ) + } + reached |= frontier + tiers.append( + sorted( + path.stem + for path, (name, _) in graph.items() + if name in frontier and fnmatch.fnmatch(path.name, "test*.py") + ) + ) + return [tier for tier in tiers if tier] + + +def _words(command) -> list[str] | None: + """A command's words as a POSIX shell splits them, with `#` kept as a word.""" + + if isinstance(command, list): + return command + lexer = shlex.shlex(command, posix=True, punctuation_chars=True) + lexer.commenters = "" + try: + return list(lexer) + except ValueError: + return None + + +def _blocks_focus(word: str) -> bool: + """A -k flag, a comment, or a shell operator.""" + + short_k = word.startswith("-") and not word.startswith("--") and "k" in word + return short_k or word.startswith("#") or not word.strip("();<>|&") + + +def focused_command(command, tests: list[str]): + """`command` narrowed to `tests` and stopped at the first failure, or None. + + Only a lone `unittest discover` command with no -k and no comment is + narrowed: appended words must reach unittest, and another -k would widen + the user's selection. + """ + + words = _words(command) + if not tests or words is None or ("unittest", "discover") not in zip(words, words[1:]): + return None + if any(_blocks_focus(word) for word in words): + return None + extra = ["-f"] + [word for test in tests for word in ("-k", f"*{test}.*")] + return command + extra if isinstance(command, list) else f"{command} {shlex.join(extra)}" + + +def _focuser(root: Path, runner, override: str | None): + """Return a source file's focused commands, one per test module. + + Nearest import first; within one distance, the module named for the file + (`test_`), then the fastest on the original code. + A module whose focused command fails on the original code is left out. + """ + + graph = None + baselines = {} + + def focus(path: Path) -> list: + nonlocal graph + if language_of(path) != "python": + return [] + if graph is None: + graph = python_imports(root) + command, directory = test_plan(root, path, "python", override) + commands = [] + for tier in affected_tests(graph, _module_name(path)): + timed = [] + for test in tier: + focused = focused_command(command, [test]) + if focused is None: + return [] + key = (str(focused), str(directory)) + if key not in baselines: + baselines[key] = runner.run(focused, directory, None) + if baselines[key].code == 0: + timed.append((test != f"test_{path.stem}", baselines[key].seconds, focused)) + commands += [focused for *_order, focused in sorted(timed, key=lambda item: item[:2])] + return commands + + return focus + + def _mutation_gate(root: Path, files, bundle, runner, baselines, options): forms = [] results = [] incomplete = [] + focus = _focuser(root, runner, options.test_command) for path in files: + covered = _mutation_coverage(root, path, bundle) + # A file without covered lines runs no mutant, so its focus would only cost baselines. + runner.focus = focus(path) if covered else [] result = mutate_file( path, root, runner=runner, - covered_lines=_mutation_coverage(root, path, bundle), + covered_lines=covered, ignore_coverage=False, mutate_all=True, lines=None, test_command=options.test_command, timeout_factor=10.0, - mutation_warning=50, + # The per-file mutant count is noise on a passing run. + mutation_warning=50 if options.verbose else sys.maxsize, baselines=baselines, max_workers=options.max_workers, ) @@ -320,7 +499,7 @@ def _mutation_gate(root: Path, files, bundle, runner, baselines, options): def _gates(root: Path, files, duplicates_files, options, coverage_log: str, ran) -> int: - runner = CommandRunner() + runner = FocusedRunner() baselines = _baselines(root, files, runner, options.test_command) bundle = load_bundle(root) failures, incomplete = _static_gates( diff --git a/tests/test_check.py b/tests/test_check.py index 66d8d40..32a5a44 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -504,5 +504,204 @@ def test_go_module_coverage_path_matches_the_project_source(self): self.assertEqual(source, (self.root / "add.go").read_text(encoding="utf-8")) +class FocusTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.root = Path(self.directory.name) + + def write(self, relative, text=""): + path = self.root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + def test_module_names_follow_packages(self): + self.write("src/pkg/__init__.py") + self.write("src/pkg/sub/__init__.py") + self.assertEqual("pkg.sub.m", check._module_name(self.write("src/pkg/sub/m.py"))) + self.assertEqual("pkg.sub", check._module_name(self.root / "src/pkg/sub/__init__.py")) + self.assertEqual("test_x", check._module_name(self.write("tests/test_x.py"))) + + def test_imports_resolve_relative_and_nested_imports(self): + self.write("src/pkg/__init__.py", "from . import mod\n") + self.write("src/pkg/sub/__init__.py", "from .. import other\n") + self.write( + "src/pkg/sub/m.py", + "import json\nfrom . import y\nfrom .. import mod\n" + "def f():\n from pkg.lazy import thing\n", + ) + self.write("src/pkg/user.py", "from .mod import add\n") + self.write("target/mutation-workers/pkg/copy.py", "import pkg.mod\n") + self.write(".worktrees/other/src/pkg/copy.py", "import pkg.mod\n") + self.write("node_modules/pkg/copy.py", "import pkg.mod\n") + graph = check.python_imports(self.root) + imports = {name: imported for name, imported in graph.values()} + self.assertEqual({"pkg", "pkg.mod"}, imports["pkg"]) + self.assertEqual({"pkg", "pkg.other"}, imports["pkg.sub"]) + self.assertEqual( + {"json", "pkg.sub", "pkg.sub.y", "pkg", "pkg.mod", "pkg.lazy", "pkg.lazy.thing"}, + imports["pkg.sub.m"], + ) + self.assertEqual({"pkg.mod", "pkg.mod.add"}, imports["pkg.user"]) + self.assertEqual({"pkg", "pkg.sub", "pkg.sub.m", "pkg.user"}, set(imports)) + + def test_affected_tests_follow_imports_transitively(self): + self.write("src/pkg/__init__.py") + self.write("src/pkg/mod.py", "def add(a, b):\n return a + b\n") + self.write("src/pkg/user.py", "from . import mod\n") + self.write("tests/test_direct.py", "import pkg.mod\n") + self.write("tests/test_from.py", "from pkg.mod import add\n") + self.write("tests/test_indirect.py", "import pkg.user\n") + self.write("tests/test_lazy.py", "def f():\n from pkg import mod\n") + self.write("tests/test_package.py", "import pkg\n") + self.write("tests/test_other.py", "import json\n") + self.write("tests/helper.py", "import pkg.mod\n") + graph = check.python_imports(self.root) + self.assertEqual( + [["test_direct", "test_from", "test_lazy"], ["test_indirect"]], + check.affected_tests(graph, "pkg.mod"), + ) + + def test_affected_tests_drop_distances_without_tests(self): + graph = { + Path("tests/test_late.py"): ("test_late", {"pkg.user"}), + Path("src/pkg/user.py"): ("pkg.user", {"pkg.mod"}), + } + self.assertEqual([["test_late"]], check.affected_tests(graph, "pkg.mod")) + + def test_focus_orders_modules_nearest_then_named_then_fastest_and_drops_failing_ones(self): + self.write("src/pkg/__init__.py") + self.write("src/pkg/mod.py", "def add(a, b):\n return a + b\n") + self.write("src/pkg/user.py", "from . import mod\n") + for name in ("test_early", "test_late", "test_broken", "test_mod"): + self.write(f"tests/{name}.py", "import pkg.mod\n") + self.write("tests/test_far.py", "import pkg.user\n") + seconds = { + "test_early": 3.0, "test_late": 0.5, "test_broken": 0.1, "test_far": 0.1, "test_mod": 4.0 + } + ran = [] + + def run(command, directory, timeout): + test = command.split("*")[-2].rstrip(".") + ran.append(test) + return SimpleNamespace(code=int(test == "test_broken"), seconds=seconds[test]) + + focus = check._focuser(self.root, SimpleNamespace(run=run), "python -m unittest discover") + commands = focus(self.root / "src/pkg/mod.py") + self.assertEqual( + [ + f"python -m unittest discover -f -k '*{test}.*'" + for test in ("test_mod", "test_late", "test_early", "test_far") + ], + commands, + ) + self.assertEqual(commands, focus(self.root / "src/pkg/mod.py")) + self.assertEqual(5, len(ran)) + self.assertEqual([], check._focuser(self.root, None, "make test")(self.root / "src/pkg/mod.py")) + + def test_focused_runner_stops_at_the_first_failing_focus(self): + runner = check.FocusedRunner() + runner.focus = ["exit 0", "exit 3", "exit 4"] + self.assertEqual(3, runner.run("exit 0", self.root, 5).code) + runner.focus = ["exit 0"] + self.assertEqual(5, runner.run("exit 5", self.root, 5).code) + runner.focus = ["exit 3"] + self.assertEqual(0, runner.run("exit 0", self.root, None).code) + + def test_focused_command_narrows_only_a_lone_unittest_discover(self): + command = "uv run python -m unittest discover -s tests -q" + self.assertEqual( + command + " -f -k '*test_a.*' -k '*test_b.*'", + check.focused_command(command, ["test_a", "test_b"]), + ) + self.assertEqual( + ["py", "-m", "unittest", "discover", "-f", "-k", "*test_a.*"], + check.focused_command(["py", "-m", "unittest", "discover"], ["test_a"]), + ) + for unfocused, tests in ( + (command, []), + (command + " -k slow", ["test_a"]), + (command + " '-k' slow", ["test_a"]), + (command + " -kslow", ["test_a"]), + (command + " -qk slow", ["test_a"]), + (command + " # quiet", ["test_a"]), + (command + " 2>&1", ["test_a"]), + ("cd tests && python -m unittest discover", ["test_a"]), + ("python -m pytest", ["test_a"]), + ("python -m unittest test_a", ["test_a"]), + ("python -m unittest discover -p 'test*.py", ["test_a"]), + (["py", "-m", "pytest"], ["test_a"]), + ): + with self.subTest(command=unfocused, tests=tests): + self.assertIsNone(check.focused_command(unfocused, tests)) + + def run_gate(self, direct_test): + self.write("src/pkg/__init__.py") + self.write("src/pkg/mod.py", "def add(a, b):\n return a + b\n") + self.write( + "tests/test_direct.py", + "import unittest\nimport pkg.mod\n\n" + f"class Direct(unittest.TestCase):\n def test_add(self):\n {direct_test}\n", + ) + self.write( + "tests/test_hidden.py", + "import importlib\nimport unittest\n\n" + "class Hidden(unittest.TestCase):\n def test_add(self):\n" + " add = importlib.import_module('pkg.mod').add\n" + " self.assertEqual(5, add(2, 3))\n", + ) + self.write( + "target/coverage/python/lcov.info", + "SF:src/pkg/mod.py\nDA:1,1\nDA:2,1\nend_of_record\n", + ) + test_command = f"PYTHONPATH=src {shlex.quote(sys.executable)} -m unittest discover -s tests" + calls = [] + run = check.CommandRunner.run + + def record(runner, command, cwd, timeout): + calls.append((command, timeout)) + return run(runner, command, cwd, timeout) + + output = io.StringIO() + with patch.object(check.CommandRunner, "run", autospec=True, side_effect=record): + with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): + status = check.run( + [ + "--root", str(self.root), "-s", "src", "--use-existing-coverage", + "--test-command", test_command, "--max-workers", "1", + ] + ) + focused = test_command + " -f -k '*test_direct.*'" + self.assertEqual(0, status, output.getvalue()) + self.assertIn("Mutation: 1 killed, 0 survived", output.getvalue()) + self.assertIn((focused, None), calls) + mutant_runs = [command for command, timeout in calls if timeout is not None] + return mutant_runs, focused, test_command + + def test_focused_kill_skips_the_full_command(self): + mutant_runs, focused, _full = self.run_gate("self.assertEqual(5, pkg.mod.add(2, 3))") + self.assertEqual([focused], mutant_runs) + + def test_mutant_only_an_unselected_test_kills_is_still_killed(self): + mutant_runs, focused, full = self.run_gate("self.assertIsNotNone(pkg.mod.add(2, 3))") + self.assertEqual([focused, full], mutant_runs) + + def test_mutation_count_warning_needs_verbose(self): + self.write("src/example.py", "def add(a, b):\n return a" + " + b" * 51 + "\n") + self.write( + "target/coverage/python/lcov.info", "SF:src/example.py\nDA:1,1\nDA:2,1\nend_of_record\n" + ) + for verbose in ([], ["--verbose"]): + output = io.StringIO() + with contextlib.redirect_stdout(output), contextlib.redirect_stderr(output): + check.run( + ["--root", str(self.root), "--use-existing-coverage", + "--test-command", "exit 0", *verbose] + ) + with self.subTest(verbose=verbose): + self.assertEqual(bool(verbose), "WARNING: 51 covered mutations" in output.getvalue()) + + if __name__ == "__main__": unittest.main()