From 20297d9ab018386dec9eec6cc501d87abd831426 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 20:16:14 +0100 Subject: [PATCH 1/6] Run each mutant's importing tests first in ub check; hide the mutant-count warning --- README.md | 7 ++ src/ub_cli/check.py | 145 ++++++++++++++++++++++++++++++++++++++++- tests/test_check.py | 154 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 304 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index bcf8a5c..bf8a8f1 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,13 @@ 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 and no `-k`, each Python mutant first runs only the test modules that +import its module, directly or through other project modules, stopping at the +first failure. A failure kills the mutant. A pass reruns the full test command, +so the verdict matches a full-suite run. The focused tests must pass on the +original code first, or every mutant of that file runs the full command. + 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..3cfc8a1 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,11 +283,147 @@ 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 that import its module, then the full command. + + A focused failure is a kill. A focused pass reruns the full command, so a + mutant only some other test kills is still killed and no survivor is + reported that the full command would not report. + """ + + focus = None + + def run(self, command, cwd, timeout): + # Baselines run without a timeout; only mutant runs have one. + if self.focus is not None and timeout is not None: + result = super().run(self.focus, 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] + 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[str]: + """The test*.py module stems that import `module`, directly or through other modules.""" + + # shortcut: import statements only; import_module and subprocess imports are missed, + # which costs a full-command rerun, never a verdict. + reached = {module} + grew = True + while grew: + grew = False + 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 reached + ): + reached.add(name) + grew = True + return sorted( + path.stem + for path, (name, _) in graph.items() + if name in reached and name != module and fnmatch.fnmatch(path.name, "test*.py") + ) + + +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 of its own is narrowed: + appended words must reach unittest, and another -k would widen the user's selection. + """ + + if isinstance(command, list): + words = command + else: + lexer = shlex.shlex(command, posix=True, punctuation_chars=True) + lexer.whitespace_split = True + try: + words = list(lexer) + except ValueError: + return None + if not tests or "-k" in words or ("unittest", "discover") not in zip(words, words[1:]): + return None + if any(not word.strip("();<>|&") 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 the focused command for a source file, once it passed on the original code.""" + + graph = None + passed = {} + + def focus(path: Path): + nonlocal graph + if language_of(path) != "python": + return None + if graph is None: + graph = python_imports(root) + command, directory = test_plan(root, path, "python", override) + focused = focused_command(command, affected_tests(graph, _module_name(path))) + if focused is None: + return None + key = (str(focused), str(directory)) + if key not in passed: + passed[key] = runner.run(focused, directory, None).code == 0 + return focused if passed[key] else None + + 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: + runner.focus = focus(path) result = mutate_file( path, root, @@ -294,7 +434,8 @@ def _mutation_gate(root: Path, files, bundle, runner, baselines, options): 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 +461,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..13645bb 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -504,5 +504,159 @@ 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") + 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_indirect", "test_lazy"], + check.affected_tests(graph, "pkg.mod"), + ) + + def test_affected_tests_reach_importers_listed_before_their_imports(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_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 + " 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() From 923915f8c0d1390457c240a5fe3a4bb4ae837de2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 20:25:32 +0100 Subject: [PATCH 2/6] Run focused tests nearest first, one command per import distance --- src/ub_cli/check.py | 78 ++++++++++++++++++++++++--------------------- tests/test_check.py | 16 ++++++++-- 2 files changed, 55 insertions(+), 39 deletions(-) diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index 3cfc8a1..2f6f186 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -284,19 +284,20 @@ def _static_gates(root: Path, files, duplicates_files, bundle, options, coverage class FocusedRunner(CommandRunner): - """Run a mutant against the tests that import its module, then the full command. + """Run a mutant against the tests nearest its module, then the full command. - A focused failure is a kill. A focused pass reruns the full command, so a - mutant only some other test kills is still killed and no survivor is - reported that the full command would not report. + 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 = None + focus = () def run(self, command, cwd, timeout): # Baselines run without a timeout; only mutant runs have one. - if self.focus is not None and timeout is not None: - result = super().run(self.focus, cwd, timeout) + 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) @@ -345,28 +346,30 @@ def python_imports(root: Path) -> dict[Path, tuple[str, set[str]]]: return graph -def affected_tests(graph, module: str) -> list[str]: - """The test*.py module stems that import `module`, directly or through other modules.""" +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. reached = {module} - grew = True - while grew: - grew = False - 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 reached - ): - reached.add(name) - grew = True - return sorted( - path.stem - for path, (name, _) in graph.items() - if name in reached and name != module and fnmatch.fnmatch(path.name, "test*.py") - ) + 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 focused_command(command, tests: list[str]): @@ -380,7 +383,6 @@ def focused_command(command, tests: list[str]): words = command else: lexer = shlex.shlex(command, posix=True, punctuation_chars=True) - lexer.whitespace_split = True try: words = list(lexer) except ValueError: @@ -394,25 +396,29 @@ def focused_command(command, tests: list[str]): def _focuser(root: Path, runner, override: str | None): - """Return the focused command for a source file, once it passed on the original code.""" + """Return a source file's focused commands that pass on the original code.""" graph = None passed = {} - def focus(path: Path): + def focus(path: Path) -> list: nonlocal graph if language_of(path) != "python": - return None + return [] if graph is None: graph = python_imports(root) command, directory = test_plan(root, path, "python", override) - focused = focused_command(command, affected_tests(graph, _module_name(path))) - if focused is None: - return None - key = (str(focused), str(directory)) - if key not in passed: - passed[key] = runner.run(focused, directory, None).code == 0 - return focused if passed[key] else None + commands = [] + for tests in affected_tests(graph, _module_name(path)): + focused = focused_command(command, tests) + if focused is None: + return [] + key = (str(focused), str(directory)) + if key not in passed: + passed[key] = runner.run(focused, directory, None).code == 0 + if passed[key]: + commands.append(focused) + return commands return focus diff --git a/tests/test_check.py b/tests/test_check.py index 13645bb..222fe0e 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -557,16 +557,25 @@ def test_affected_tests_follow_imports_transitively(self): self.write("tests/helper.py", "import pkg.mod\n") graph = check.python_imports(self.root) self.assertEqual( - ["test_direct", "test_from", "test_indirect", "test_lazy"], + [["test_direct", "test_from", "test_lazy"], ["test_indirect"]], check.affected_tests(graph, "pkg.mod"), ) - def test_affected_tests_reach_importers_listed_before_their_imports(self): + 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")) + self.assertEqual([["test_late"]], check.affected_tests(graph, "pkg.mod")) + + 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" @@ -581,6 +590,7 @@ def test_focused_command_narrows_only_a_lone_unittest_discover(self): for unfocused, tests in ( (command, []), (command + " -k slow", ["test_a"]), + (command + " '-k' slow", ["test_a"]), (command + " 2>&1", ["test_a"]), ("cd tests && python -m unittest discover", ["test_a"]), ("python -m pytest", ["test_a"]), From 083aaf8120cf233d7dda69f3204db4a903c9f975 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 20:33:00 +0100 Subject: [PATCH 3/6] Refuse attached -k flags and comments; skip dot dirs when reading imports --- src/ub_cli/check.py | 28 ++++++++++++++++++++-------- tests/test_check.py | 5 +++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index 2f6f186..ce7d1ec 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -337,7 +337,11 @@ def python_imports(root: Path) -> dict[Path, tuple[str, set[str]]]: graph = {} for directory, folders, names in os.walk(root): - folders[:] = [folder for folder in folders if folder not in SKIP_LINK] + 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 @@ -350,7 +354,7 @@ 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. + # which costs a full-command rerun, never a verdict. Follow them if survivors' reruns dominate. reached = {module} frontier = {module} tiers = [] @@ -359,7 +363,11 @@ def affected_tests(graph, module: str) -> list[list[str]]: 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) + and any( + item == target or item.startswith(target + ".") + for item in imported + for target in frontier + ) } reached |= frontier tiers.append( @@ -375,22 +383,26 @@ def affected_tests(graph, module: str) -> list[list[str]]: 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 of its own is narrowed: - appended words must reach unittest, and another -k would widen the user's selection. + 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. """ if isinstance(command, list): words = command else: lexer = shlex.shlex(command, posix=True, punctuation_chars=True) + lexer.commenters = "" try: words = list(lexer) except ValueError: return None - if not tests or "-k" in words or ("unittest", "discover") not in zip(words, words[1:]): - return None - if any(not word.strip("();<>|&") for word in words): + if not tests or ("unittest", "discover") not in zip(words, words[1:]): return None + for word in words: + short_k = word.startswith("-") and not word.startswith("--") and "k" in word + if short_k or word.startswith("#") or not word.strip("();<>|&"): + 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)}" diff --git a/tests/test_check.py b/tests/test_check.py index 222fe0e..7741f17 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -533,6 +533,8 @@ def test_imports_resolve_relative_and_nested_imports(self): ) 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"]) @@ -591,6 +593,9 @@ def test_focused_command_narrows_only_a_lone_unittest_discover(self): (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"]), From 2b5550a5d1ffa6149e55336b45c9f9cf234f2d55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 20:35:10 +0100 Subject: [PATCH 4/6] Split focused_command below CRAP 10; fix README on skipped focus groups --- README.md | 4 ++-- src/ub_cli/check.py | 38 ++++++++++++++++++++++++-------------- 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index bf8a8f1..7fd9290 100644 --- a/README.md +++ b/README.md @@ -113,8 +113,8 @@ When the test command is a Python `python -m unittest discover` with no shell operators and no `-k`, each Python mutant first runs only the test modules that import its module, directly or through other project modules, stopping at the first failure. A failure kills the mutant. A pass reruns the full test command, -so the verdict matches a full-suite run. The focused tests must pass on the -original code first, or every mutant of that file runs the full command. +so the verdict matches a full-suite run. Each group of focused tests must pass +on the original code first, or it 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 diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index ce7d1ec..c49aba7 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -380,6 +380,26 @@ def affected_tests(graph, module: str) -> list[list[str]]: 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. @@ -388,21 +408,11 @@ def focused_command(command, tests: list[str]): the user's selection. """ - if isinstance(command, list): - words = command - else: - lexer = shlex.shlex(command, posix=True, punctuation_chars=True) - lexer.commenters = "" - try: - words = list(lexer) - except ValueError: - return None - if not tests or ("unittest", "discover") not in zip(words, words[1:]): + 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 - for word in words: - short_k = word.startswith("-") and not word.startswith("--") and "k" in word - if short_k or word.startswith("#") or not word.strip("();<>|&"): - 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)}" From a8b11f3bea526873416df685eda642780c3ba806 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 20:38:54 +0100 Subject: [PATCH 5/6] Run focused test modules one at a time, nearest then fastest; skip focus for uncovered files --- README.md | 11 ++++++----- src/ub_cli/check.py | 34 +++++++++++++++++++++------------- tests/test_check.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 7fd9290..1ba1734 100644 --- a/README.md +++ b/README.md @@ -110,11 +110,12 @@ 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 and no `-k`, each Python mutant first runs only the test modules that -import its module, directly or through other project modules, stopping at the -first failure. A failure kills the mutant. A pass reruns the full test command, -so the verdict matches a full-suite run. Each group of focused tests must pass -on the original code first, or it is skipped. +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 diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index c49aba7..f45d426 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -418,10 +418,13 @@ def focused_command(command, tests: list[str]): def _focuser(root: Path, runner, override: str | None): - """Return a source file's focused commands that pass on the original code.""" + """Return a source file's focused commands, one per test module, nearest and fastest first. + + A module whose focused command fails on the original code is left out. + """ graph = None - passed = {} + baselines = {} def focus(path: Path) -> list: nonlocal graph @@ -431,15 +434,18 @@ def focus(path: Path) -> list: graph = python_imports(root) command, directory = test_plan(root, path, "python", override) commands = [] - for tests in affected_tests(graph, _module_name(path)): - focused = focused_command(command, tests) - if focused is None: - return [] - key = (str(focused), str(directory)) - if key not in passed: - passed[key] = runner.run(focused, directory, None).code == 0 - if passed[key]: - commands.append(focused) + 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((baselines[key].seconds, focused)) + commands += [focused for _seconds, focused in sorted(timed, key=lambda item: item[0])] return commands return focus @@ -451,12 +457,14 @@ def _mutation_gate(root: Path, files, bundle, runner, baselines, options): incomplete = [] focus = _focuser(root, runner, options.test_command) for path in files: - runner.focus = focus(path) + 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, diff --git a/tests/test_check.py b/tests/test_check.py index 7741f17..71c5218 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -570,6 +570,34 @@ def test_affected_tests_drop_distances_without_tests(self): } self.assertEqual([["test_late"]], check.affected_tests(graph, "pkg.mod")) + def test_focus_orders_modules_nearest_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"): + 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} + 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_late", "test_early", "test_far") + ], + commands, + ) + self.assertEqual(commands, focus(self.root / "src/pkg/mod.py")) + self.assertEqual(4, 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"] From 69c535149930ab790757c599a6ab7df836ab0fb4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 20:45:43 +0100 Subject: [PATCH 6/6] Run the test module named for the file first within an import distance --- src/ub_cli/check.py | 8 +++++--- tests/test_check.py | 12 +++++++----- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index f45d426..f64104c 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -418,8 +418,10 @@ def focused_command(command, tests: list[str]): def _focuser(root: Path, runner, override: str | None): - """Return a source file's focused commands, one per test module, nearest and fastest first. + """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. """ @@ -444,8 +446,8 @@ def focus(path: Path) -> list: if key not in baselines: baselines[key] = runner.run(focused, directory, None) if baselines[key].code == 0: - timed.append((baselines[key].seconds, focused)) - commands += [focused for _seconds, focused in sorted(timed, key=lambda item: item[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 diff --git a/tests/test_check.py b/tests/test_check.py index 71c5218..32a5a44 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -570,14 +570,16 @@ def test_affected_tests_drop_distances_without_tests(self): } self.assertEqual([["test_late"]], check.affected_tests(graph, "pkg.mod")) - def test_focus_orders_modules_nearest_then_fastest_and_drops_failing_ones(self): + 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"): + 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} + 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): @@ -590,12 +592,12 @@ def run(command, directory, timeout): self.assertEqual( [ f"python -m unittest discover -f -k '*{test}.*'" - for test in ("test_late", "test_early", "test_far") + for test in ("test_mod", "test_late", "test_early", "test_far") ], commands, ) self.assertEqual(commands, focus(self.root / "src/pkg/mod.py")) - self.assertEqual(4, len(ran)) + 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):