From e4986843024eb3428c04a0cc22f44f13b0385aca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 18:00:40 +0100 Subject: [PATCH 1/2] Share one failure format across ub crap, mutate and check; find tests/ for default Python runs - CRAP lines read '18.0 CRAP, 8 CC, 46% covered: pkg/fn' in ub crap and ub check. - ub check and ub mutate print one line per unkilled mutant: 'path:line survived > -> >='. - The no-executed-lines message names the custom or Python coverage command that ran. - Default unittest discovery runs tests/ or test/ when the top level holds no tests. - 'Wrote' prints the metrics path relative to the root. - ub mutate --scan says 'coverage unknown' when no report covers a file. - Tests clear ub's own gate for engines.py. --- README.md | 16 +++-- src/ub_cli/check.py | 66 +++++++++++++-------- src/ub_cli/engines.py | 114 ++++++++++++++++++++++++++---------- tests/test_check.py | 40 +++++++++---- tests/test_engines.py | 132 +++++++++++++++++++++++++++++++++++++++++- 5 files changed, 297 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 35aa817..e0e3737 100644 --- a/README.md +++ b/README.md @@ -81,18 +81,25 @@ names `ub COMMAND` instead of the engine. Coverage and mutation runs use the target project's toolchain. Upstream coverage runners can install missing coverage tools. To read coverage already collected by your CI, use `ub check --use-existing-coverage` or `ub crap --use-existing-coverage`. +When the default Python run uses `unittest discover` and the project's top level +holds no tests, ub points it at a `tests/` or `test/` directory that has no +`__init__.py`, which plain discovery would skip. By default each command prints a summary line and the items that need work: `ub crap` lists functions with CRAP ≥ 10, or above `--threshold` (complexity ≥ 10 with `--no-coverage`), `ub dry` one line per duplicate pair, and `ub mutate` the surviving and uncovered mutants. `ub crap` and `ub dry` show -the first 10 items; `ub mutate --scan` prints one line per file with sites. +the first 10 items; `ub mutate --scan` prints one line per file with sites, +saying `coverage unknown` when no report covers the file. A CRAP line reads +`18.0 CRAP, 8 CC, 46% covered: pkg.module/function` and a mutant line +`src/pkg/module.py:109 survived > -> >=`; `ub check` prints the same lines. Coverage output stays hidden unless a coverage command fails. Pass `--verbose` for the engine's full report, every mutant, and the coverage output. ub exits 2 with one cause line where the engine would report nothing useful: when a whole-project `ub crap` reads coverage in which no analyzed function -ran a line, and when a path or filter argument matches no source file (except +ran a line (the message names the custom or Python coverage command that ran), +and when a path or filter argument matches no source file (except with `--changed`). A bare run on a project without source files still exits 0. ## Combined gate @@ -102,8 +109,9 @@ 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`. -By default it prints one summary line per gate, the items that failed, and a -verdict. The coverage command's output appears only when coverage fails or is +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 incomplete. Pass `--verbose` for the full CRAP table, duplicate list, and mutant log, and to stream the coverage command's output. diff --git a/src/ub_cli/check.py b/src/ub_cli/check.py index 9df8121..f9cdc4e 100644 --- a/src/ub_cli/check.py +++ b/src/ub_cli/check.py @@ -26,10 +26,14 @@ from tree_sitter_language_pack import Error as ParserError -NO_EXECUTED_LINES = ( - "Coverage reports show no executed lines in any analyzed function. " - "Did the coverage command run the tests?" -) +def no_executed_lines(commands: list[str]) -> str: + """Why coverage proves nothing, naming the coverage commands that ran.""" + + ran = " and ".join(f"`{command}`" for command in commands) or "the coverage command" + return ( + "Coverage reports show no executed lines in any analyzed function. " + f"Did {ran} run the tests?" + ) def unexecuted(entries) -> bool: @@ -38,12 +42,19 @@ def unexecuted(entries) -> bool: return bool(entries) and not any(entry.coverage for entry in entries) +def crap_line(entry) -> str: + return ( + f"{entry.crap:.1f} CRAP, {entry.complexity} CC, {entry.coverage:.0f}% covered: " + f"{entry.namespace}/{entry.name}" + ) + + +def mutant_line(site, status: str) -> str: + return f"{site.file}:{site.line} {status} {site.description}" + + def _crap_failures(entries) -> list[str]: - return [ - f"CRAP {entry.crap:.1f} >= 10 in {entry.namespace}/{entry.name}" - for entry in entries - if entry.crap is not None and entry.crap >= 10 - ] + return [crap_line(entry) for entry in entries if entry.crap is not None and entry.crap >= 10] def _dry_failures(candidates) -> list[str]: @@ -56,13 +67,14 @@ def _dry_failures(candidates) -> list[str]: ] -def _mutation_failures(forms) -> list[str]: - return [ - f"{form.file}:{form.line} has {form.survived} surviving " - f"and {form.uncovered} uncovered mutants" - for form in forms - if form.survived or form.uncovered +def _mutation_failures(results) -> list[str]: + # A covered site with no outcome counts as survived, as the engine's form totals count it. + statuses = [ + (site, result.statuses.get(site.mutation_id, "survived")) + for result in results + for site in result.sites ] + return [mutant_line(site, status) for site, status in statuses if status != "killed"] def _analyze(root: Path, files: list[Path], bundle) -> tuple[list, list, list[str]]: @@ -242,13 +254,13 @@ def _verdict(failures: list[str], incomplete: list[str]) -> int: return 0 -def _static_gates(root: Path, files, duplicates_files, bundle, options, coverage_log: str): +def _static_gates(root: Path, files, duplicates_files, bundle, options, coverage_log: str, ran): """Report CRAP and duplication. Return their failures and incomplete reasons.""" entries, measured, incomplete = _analyze(root, files, bundle) write_crap(entries, root) if unexecuted(measured): - incomplete.append(NO_EXECUTED_LINES) + incomplete.append(no_executed_lines(ran)) measured = [] if incomplete: print(coverage_log, end="", file=sys.stderr) @@ -269,6 +281,7 @@ def _static_gates(root: Path, files, duplicates_files, bundle, options, coverage def _mutation_gate(root: Path, files, bundle, runner, baselines, options): forms = [] + results = [] incomplete = [] for path in files: result = mutate_file( @@ -291,9 +304,10 @@ def _mutation_gate(root: Path, files, bundle, runner, baselines, options): if options.verbose: print(format_site_log(result.sites, result.statuses), end="") forms.extend(result.forms) + results.append(result) if options.verbose: print(format_results(forms), end="") - failures = _mutation_failures(forms) + failures = _mutation_failures(results) killed = sum(form.killed for form in forms) survived = sum(form.survived for form in forms) uncovered = sum(form.uncovered for form in forms) @@ -305,12 +319,12 @@ def _mutation_gate(root: Path, files, bundle, runner, baselines, options): return failures, incomplete -def _gates(root: Path, files, duplicates_files, options, coverage_log: str) -> int: +def _gates(root: Path, files, duplicates_files, options, coverage_log: str, ran) -> int: runner = CommandRunner() baselines = _baselines(root, files, runner, options.test_command) bundle = load_bundle(root) failures, incomplete = _static_gates( - root, files, duplicates_files, bundle, options, coverage_log + root, files, duplicates_files, bundle, options, coverage_log, ran ) if incomplete: return _verdict(failures, incomplete) @@ -318,7 +332,7 @@ def _gates(root: Path, files, duplicates_files, options, coverage_log: str) -> i return _verdict(failures + mutation_failures, incomplete) -def _check(options) -> int: +def _check(options, ran: list[str]) -> int: root = options.root.resolve() if not root.is_dir(): raise ValueError(f"Project root is not a directory: {root}") @@ -330,10 +344,10 @@ def _check(options) -> int: if not files and not duplicates_files: raise ValueError("No supported source files found.") if options.use_existing_coverage: - return _gates(root, files, duplicates_files, options, "") + return _gates(root, files, duplicates_files, options, "", ran) coverage_log, stale = _generate_coverage(root, files, options) with _set_aside(stale): - return _gates(root, files, duplicates_files, options, coverage_log) + return _gates(root, files, duplicates_files, options, coverage_log, ran) def run(argv: list[str] | None = None) -> int: @@ -389,8 +403,12 @@ def run(argv: list[str] | None = None) -> int: if options.max_workers is not None and options.max_workers < 1: print("--max-workers requires a positive integer", file=sys.stderr) return 2 + from ub_cli.engines import _swapped, python_tests + + ran = [] try: - return _check(options) + with _swapped(python_tests(ran)): + return _check(options, ran) except (OSError, ValueError, ParserError) as exc: print(str(exc), file=sys.stderr) return 2 diff --git a/src/ub_cli/engines.py b/src/ub_cli/engines.py index 44a26bc..de9c21c 100644 --- a/src/ub_cli/engines.py +++ b/src/ub_cli/engines.py @@ -1,20 +1,23 @@ """Run a vendored engine with ub's terse output and stricter exits. The engines stay untouched on disk. While one runs, ub swaps a few of its -module-level names: the report formatters, the coverage runner, and the -file selection. The engine still prints each report when it is ready, so a -long mutation run streams per file. A renamed name fails loudly in the tests. +module-level names: the report formatters, the coverage runner, the file +selection, and the default Python test discovery. The engine still prints +each report when it is ready, so a long mutation run streams per file. A +renamed name fails loudly in the tests. """ from __future__ import annotations import contextlib import dataclasses +import shlex import sys from importlib import import_module from pathlib import Path -from ub_cli.check import NO_EXECUTED_LINES, _quietly, unexecuted +from ub_cli import check +from ub_cli.check import _quietly, crap_line, mutant_line, no_executed_lines, unexecuted LIMIT = 10 VERBOSE_HELP = { @@ -52,7 +55,7 @@ def _unmatched(options, files: list[Path]) -> str | None: candidate = Path(argument) if Path(argument).is_absolute() else root / argument if candidate.exists(): target = candidate.resolve() - hit = any(path == target or path.is_relative_to(target) for path in files) + hit = any(path.is_relative_to(target) for path in files) else: hit = any(argument in path.as_posix() for path in files) if not hit: @@ -80,7 +83,7 @@ def analyzed(files, root, bundle): narrowed = options.positionals or options.changed if bundle is not None and not narrowed and unexecuted(entries): hint = "" if verbose else " Rerun with --verbose to see its output." - raise Stop(NO_EXECUTED_LINES + hint) + raise Stop(no_executed_lines(seen["ran"]) + hint) return entries return analyzed @@ -117,11 +120,7 @@ def crap_report(entries, threshold: float | None = None) -> str: notable = [entry for entry in entries if entry.crap is not None and entry.crap > threshold] cutoff = f"> {threshold:g}" summary = f"CRAP: {len(notable)} of {len(entries)} functions {cutoff}" - lines = [ - f" {entry.crap:.1f} CRAP, {entry.complexity} CC, {entry.coverage:.0f}% covered: " - f"{entry.namespace}/{entry.name}" - for entry in notable - ] + lines = [f" {crap_line(entry)}" for entry in notable] else: notable = [entry for entry in entries if entry.complexity >= 10] summary = ( @@ -143,12 +142,14 @@ def dry_report(candidates) -> str: return "\n".join([summary, *_shown(lines)]) + "\n" -def _site_log(format_site_log): - def unkilled(sites, statuses): - kept = {key: status for key, status in statuses.items() if status != "killed"} - return format_site_log(sites, kept) +def site_log(sites, statuses) -> str: + """One line per mutant the tests did not kill.""" - return unkilled + return "".join( + mutant_line(site, statuses[site.mutation_id]) + "\n" + for site in sites + if statuses.get(site.mutation_id, "killed") != "killed" + ) def mutation_summary(forms) -> str: @@ -165,17 +166,22 @@ def mutation_summary(forms) -> str: ) -def scan_summary(path, sites, changed, covered) -> str: - if not sites: - return "" - notes = [] - if covered is not None: - missed = sum(not covered.get(site.mutation_id, True) for site in sites) - notes.append(f"{missed} uncovered") - if changed: - notes.append(f"{len(changed)} changed functions") - detail = f" ({', '.join(notes)})" if notes else "" - return f"Scan: {len(sites)} mutation sites in {path}{detail}\n" +def _scan_summary(seen: dict): + def scanned(path, sites, changed, covered) -> str: + if not sites: + return "" + notes = [] + if covered is not None: + missed = sum(not covered[site.mutation_id] for site in sites) + notes.append(f"{missed} uncovered") + elif not seen["options"].no_coverage: + notes.append("coverage unknown") + if changed: + notes.append(f"{len(changed)} changed functions") + detail = f" ({', '.join(notes)})" if notes else "" + return f"Scan: {len(sites)} mutation sites in {path}{detail}\n" + + return scanned def _unwritten(mutate_file): @@ -185,15 +191,63 @@ def mutated(*args, **kwargs): return mutated +def _relative(write_metrics): + def written(entries, root): + return write_metrics(entries, root).relative_to(root) + + return written + + +def _tests_dir(command, directory: Path): + """Point a default `unittest discover` at tests/ or test/ when the top level has no tests.""" + + # shortcut: assumes `-s .` finds nothing without top-level test*.py or an + # importable tests package; ask unittest itself if a layout proves this wrong. + if not isinstance(command, list): + return command + base = command[:-2] if command[-2:] == ["-s", "."] else command + if base[-2:] != ["unittest", "discover"] or any(directory.glob("test*.py")): + return command + for name in ("tests", "test"): + if (directory / name).is_dir(): + # An importable package is one `-s .` already finds. + return command if (directory / name / "__init__.py").is_file() else base + ["-s", name] + return command + + +def python_tests(ran: list[str]) -> list: + """Find tests/ for the default Python runs, and record each coverage run in `ran`.""" + + runners = import_module("ub_cli.vendor.crapper.runners") + mutator = import_module("ub_cli.vendor.mutator.engine") + run_shell, test_plan = runners.run_shell, mutator.test_plan + + def shell(command, cwd): + command = _tests_dir(command, cwd) + if isinstance(command, str) or command[2:4] == ["coverage", "run"]: + ran.append(command if isinstance(command, str) else shlex.join(command)) + return run_shell(command, cwd) + + def plan(*args): + command, directory = test_plan(*args) + return _tests_dir(command, directory), directory + + return [(runners, "run_shell", shell), (mutator, "test_plan", plan), (check, "test_plan", plan)] + + def _replacements(command: str, engine, verbose: bool) -> list: - seen = {} + seen = {"ran": []} replacements = [(engine, "select_files", _strict_selection(engine.select_files, seen))] + if command != "dry": + replacements += python_tests(seen["ran"]) if command == "crap": replacements.append( (engine, "analyze_files", _strict_analysis(engine.analyze_files, verbose, seen)) ) if verbose: return replacements + if command in ("crap", "dry"): + replacements.append((engine, "write_metrics", _relative(engine.write_metrics))) if command == "crap": return replacements + [ (engine, "run_coverage", _quiet(engine.run_coverage)), @@ -206,10 +260,10 @@ def _replacements(command: str, engine, verbose: bool) -> list: mutator = import_module("ub_cli.vendor.mutator.engine") return replacements + [ (runners, "run_coverage", _quiet(runners.run_coverage)), - (engine, "format_site_log", _site_log(engine.format_site_log)), + (engine, "format_site_log", site_log), (engine, "format_results", mutation_summary), (engine, "mutate_file", _unwritten(engine.mutate_file)), - (mutator, "format_scan", scan_summary), + (mutator, "format_scan", _scan_summary(seen)), ] diff --git a/tests/test_check.py b/tests/test_check.py index 7409610..66d8d40 100644 --- a/tests/test_check.py +++ b/tests/test_check.py @@ -82,13 +82,13 @@ def test_surviving_mutant_fails_the_gate(self): self.coverage() status, output = self.run_check("pass") self.assertEqual(1, status, output) - self.assertIn("surviv", output.lower()) + self.assertIn("\n src/example.py:2 survived + -> -\n", output) def test_uncovered_site_fails_even_without_survivors(self): self.coverage(hits=0) status, output = self.run_check("pass") self.assertEqual(1, status, output) - self.assertIn("has 0 surviving and 1 uncovered mutants", output) + self.assertIn("\n src/example.py:2 uncovered + -> -\n", output) def test_failed_baseline_is_incomplete(self): self.coverage() @@ -136,12 +136,12 @@ def test_fully_covered_crap_ten_fails_the_combined_command(self): "assert [choose(value) for value in range(10)] == list(range(10))" ) self.assertEqual(1, status, output) - self.assertIn("CRAP 10.0 >= 10", output) + self.assertIn("\n 10.0 CRAP, 10 CC, 100% covered: example/choose\n", output) metrics = (self.root / ".metrics" / "crap.edn").read_text(encoding="utf-8") self.assertIn(":complexity 10", metrics) self.assertIn(":coverage 100.0", metrics) self.assertIn(":crap 10.0", metrics) - self.assertNotIn("surviving and", output) + self.assertNotRegex(output, r"\.py:\d+ (survived|uncovered) ") def test_combined_command_uses_point_eight_duplication_threshold(self): self.coverage() @@ -207,8 +207,15 @@ def test_report_without_executed_lines_is_incomplete(self): self.lcov("src/example.py", 0) status, output = self.run_check("pass") self.assertEqual(2, status, output) - self.assertIn("no executed lines", output) - self.assertNotIn("uncovered mutants", output) + self.assertIn("Did the coverage command run the tests?", output) + self.assertNotIn("Mutation:", output) + + def test_report_without_executed_lines_names_the_coverage_command(self): + fresh = self.lcov("src/example.py", 0, path="fresh.info") + command = self.copy_command(fresh, "target/coverage/python/lcov.info") + status, output = self.run_check("pass", ["--coverage-command", command]) + self.assertEqual(2, status, output) + self.assertIn(f"Did `{command}` run the tests?", output) def test_known_gate_failures_print_before_incomplete_coverage(self): self.original = "def choose(a):\n" + "".join( @@ -224,7 +231,7 @@ def test_known_gate_failures_print_before_incomplete_coverage(self): self.coverage() status, output = self.run_check("pass") self.assertEqual(2, status, output) - self.assertIn("CRAP 10.0 >= 10 in example/choose", output) + self.assertIn("10.0 CRAP, 10 CC, 100% covered: example/choose", output) self.assertIn("Missing coverage for src/other.py:1", output) self.assertNotIn("other/other", output) @@ -315,11 +322,22 @@ def test_gate_prints_twenty_failures_without_a_tail(self): def test_crap_failures_print_one_decimal(self): entries = [ - SimpleNamespace(crap=35.2693, namespace="pkg", name="hot"), - SimpleNamespace(crap=9.99, namespace="pkg", name="cool"), - SimpleNamespace(crap=None, namespace="pkg", name="unknown"), + SimpleNamespace(crap=35.2693, complexity=7, coverage=49.6, namespace="pkg", name="hot"), + SimpleNamespace(crap=9.99, complexity=9, coverage=100.0, namespace="pkg", name="cool"), + SimpleNamespace(crap=None, complexity=1, coverage=None, namespace="pkg", name="unknown"), ] - self.assertEqual(["CRAP 35.3 >= 10 in pkg/hot"], check._crap_failures(entries)) + self.assertEqual(["35.3 CRAP, 7 CC, 50% covered: pkg/hot"], check._crap_failures(entries)) + + def test_mutation_failures_list_each_unkilled_mutant(self): + sites = [ + SimpleNamespace(mutation_id=key, file="src/a.py", line=line, description="> -> >=") + for key, line in (("k", 1), ("s", 2), ("u", 3), ("none", 4)) + ] + result = SimpleNamespace(sites=sites, statuses={"k": "killed", "s": "survived", "u": "uncovered"}) + self.assertEqual( + ["src/a.py:2 survived > -> >=", "src/a.py:3 uncovered > -> >=", "src/a.py:4 survived > -> >="], + check._mutation_failures([result]), + ) def test_quietly_shows_output_when_the_call_raises(self): def fail(): diff --git a/tests/test_engines.py b/tests/test_engines.py index fcbc81e..b47c271 100644 --- a/tests/test_engines.py +++ b/tests/test_engines.py @@ -6,7 +6,13 @@ from pathlib import Path from test_cli import invoke +from types import SimpleNamespace +from unittest.mock import patch + +from ub_cli import check, engines from ub_cli.cli import run +from ub_cli.vendor.crapper import runners +from ub_cli.vendor.mutator import engine as mutator SOURCE = "def add(a, b):\n return a + b\n" KILLING_TEST = ( @@ -51,7 +57,13 @@ def test_crap_without_executed_lines_stops_with_one_cause(self): self.assertEqual(2, completed.returncode, completed.stderr) self.assertEqual("", completed.stdout) self.assertEqual(1, completed.stderr.count("\n"), completed.stderr) - self.assertIn("no executed lines", completed.stderr) + self.assertIn(f"Did `{self.coverage_command(0)}` run the tests?", completed.stderr) + + def test_crap_without_executed_lines_hints_at_verbose(self): + command = self.coverage_command(0) + status, output, error = invoke(run, ["crap", "--root", str(self.root), "--coverage-command", command]) + self.assertEqual((2, ""), (status, output)) + self.assertTrue(error.endswith(" run the tests? Rerun with --verbose to see its output.\n"), error) def test_crap_reports_real_zero_coverage_of_a_named_file(self): command = self.coverage_command(0) @@ -79,7 +91,7 @@ def test_crap_keeps_coverage_output_off_stdout(self): completed = ub("crap", "--root", str(self.root), "--coverage-command", self.coverage_command(1)) self.assertEqual(0, completed.returncode, completed.stderr) self.assertEqual("CRAP: 0 of 1 functions >= 10\n", completed.stdout) - self.assertNotIn("Collecting", completed.stderr) + self.assertEqual("Wrote .metrics/crap.edn\n", completed.stderr) completed = ub( "crap", "--root", str(self.root), "--coverage-command", self.coverage_command(1), "--verbose" @@ -115,6 +127,7 @@ def test_dry_prints_one_line_per_pair(self): status, output, error = invoke(run, ["dry", "--root", str(self.root)]) self.assertEqual(0, status, error) self.assertEqual("Duplication: 1 candidate pairs\n 1.00 first.py:1-9 second.py:1-9\n", output) + self.assertEqual("Wrote .metrics/dry.edn\n", error) def test_mutate_hides_killed_mutants_unless_verbose(self): arguments = [ @@ -139,11 +152,32 @@ def test_mutate_hides_killed_mutants_unless_verbose(self): self.assertIn("KILLED", output) self.assertIn("Wrote", error) + def test_mutate_lists_each_unkilled_mutant(self): + status, output, _ = invoke( + run, + ["mutate", "--root", str(self.root), "--no-coverage", "--mutate-all", "--test-command", "true"], + ) + self.assertEqual(3, status, output) + self.assertIn("example.py:2 survived + -> -\n", output) + self.assertNotIn("SURVIVED", output) + def test_mutate_scan_prints_one_line_per_file(self): status, output, _ = invoke(run, ["mutate", "--root", str(self.root), "--scan", "--no-coverage"]) self.assertEqual(0, status) self.assertRegex(output, r"^Scan: \d+ mutation sites in example.py\n$") + def test_mutate_scan_without_a_report_says_coverage_is_unknown(self): + status, output, _ = invoke(run, ["mutate", "--root", str(self.root), "--scan"]) + self.assertEqual(0, status) + self.assertRegex(output, r"^Scan: \d+ mutation sites in example.py \(coverage unknown\)\n$") + + report = self.root / "coverage" / "lcov.info" + report.parent.mkdir() + report.write_text("SF:example.py\nDA:1,1\nDA:2,0\nend_of_record\n", encoding="utf-8") + status, output, _ = invoke(run, ["mutate", "--root", str(self.root), "--scan"]) + self.assertEqual(0, status) + self.assertRegex(output, r"^Scan: (\d+) mutation sites in example.py \(\1 uncovered\)\n$") + def test_argument_matching_nothing_fails_and_names_it(self): for command in ("crap", "dry", "mutate"): with self.subTest(command=command): @@ -160,5 +194,99 @@ def test_bare_run_on_an_empty_project_is_unchanged(self): self.assertEqual((0, "No source files to analyze.\n"), (status, output)) +def entry(crap, complexity, coverage, name): + return SimpleNamespace(crap=crap, complexity=complexity, coverage=coverage, namespace="pkg", name=name) + + +class CrapReportTests(unittest.TestCase): + def test_lists_functions_at_ten_or_above_the_threshold(self): + entries = [entry(10.0, 10, 100.0, "hot"), entry(9.9, 9, 100.0, "cool"), entry(None, 1, None, "gone")] + self.assertEqual( + "CRAP: 1 of 3 functions >= 10\n 10.0 CRAP, 10 CC, 100% covered: pkg/hot\n", + engines.crap_report(entries), + ) + self.assertEqual( + "CRAP: 0 of 3 functions > 10\n", engines.crap_report(entries, threshold=10.0) + ) + self.assertEqual( + "CRAP: 2 of 3 functions > 9.5\n 10.0 CRAP, 10 CC, 100% covered: pkg/hot\n" + " 9.9 CRAP, 9 CC, 100% covered: pkg/cool\n", + engines.crap_report(entries, threshold=9.5), + ) + + def test_caps_the_list_after_ten(self): + for count, tail in ((10, []), (11, [" ... and 1 more; --verbose for all"])): + lines = engines.crap_report([entry(10.0, 10, 100.0, "hot")] * count).splitlines() + self.assertEqual(1 + 10 + len(tail), len(lines)) + self.assertEqual(tail, lines[11:]) + + def test_mutation_summary_scores_killed_over_executed(self): + forms = [SimpleNamespace(killed=3, survived=1, uncovered=2)] + self.assertEqual( + "Mutation: 3 killed, 1 survived, 2 uncovered in 1 functions, score 75.0%. " + "--verbose lists every mutant and function.\n", + engines.mutation_summary(forms), + ) + + def test_lists_complexity_when_coverage_is_not_measured(self): + entries = [entry(None, 10, None, "tangled"), entry(None, 9, None, "plain")] + self.assertEqual( + "Complexity: 1 of 2 functions >= 10, coverage not measured\n 10 CC: pkg/tangled\n", + engines.crap_report(entries), + ) + + +class PythonTestsTests(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + (self.root / "example.py").write_text(SOURCE, encoding="utf-8") + + def rewrite(self, command): + return engines._tests_dir(command, self.root) + + def test_default_discovery_moves_to_a_tests_dir_that_dot_cannot_find(self): + coverage = ["py", "-m", "coverage", "run", "-m", "unittest", "discover", "-s", "."] + plain = ["py", "-m", "unittest", "discover"] + self.assertEqual(coverage, self.rewrite(coverage)) + for name in ("test", "tests"): + (self.root / name).mkdir() + self.assertEqual(coverage[:-1] + [name], self.rewrite(coverage)) + self.assertEqual(plain + ["-s", name], self.rewrite(plain)) + + def test_default_discovery_stays_when_dot_finds_tests(self): + command = ["py", "-m", "unittest", "discover"] + (self.root / "tests").mkdir() + (self.root / "test").mkdir() + (self.root / "tests" / "__init__.py").write_text("") + self.assertEqual(command, self.rewrite(command)) + (self.root / "tests" / "__init__.py").unlink() + (self.root / "test_top.py").write_text("") + self.assertEqual(command, self.rewrite(command)) + + def test_other_commands_stay(self): + (self.root / "tests").mkdir() + for command in ("python -m unittest discover", ["py", "-m", "pytest"], ["py", "-m", "unittest", "discover", "-s", "src"]): + self.assertEqual(command, self.rewrite(command)) + + def test_swaps_rewrite_runs_and_record_coverage_commands(self): + (self.root / "tests").mkdir() + calls = [] + with patch.object(runners, "run_shell", lambda command, cwd: calls.append(command) or 0): + ran = [] + swaps = engines.python_tests(ran) + shell, plan = swaps[0][2], swaps[1][2] + self.assertEqual([runners, mutator, check], [module for module, _, _ in swaps]) + self.assertEqual(0, shell(["py", "-m", "coverage", "run", "-m", "unittest", "discover", "-s", "."], self.root)) + shell(["py", "-c", "import coverage"], self.root) + shell("make coverage", self.root) + self.assertEqual(["py -m coverage run -m unittest discover -s tests", "make coverage"], ran) + self.assertEqual(["py", "-m", "coverage", "run", "-m", "unittest", "discover", "-s", "tests"], calls[0]) + command, directory = plan(self.root, self.root / "example.py", "python", None) + self.assertEqual(["-s", "tests"], command[-2:]) + self.assertEqual(self.root.resolve(), directory) + + if __name__ == "__main__": unittest.main() From c3c36668c2750626c09f3a2070cf3a5bba1ea0e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Juan=20Gait=C3=A1n-Villamizar?= Date: Tue, 17 Nov 2026 18:15:44 +0100 Subject: [PATCH 2/2] Keep -s . when unittest would find tests inside importable packages --- README.md | 6 +++--- src/ub_cli/engines.py | 25 +++++++++++++++++++------ tests/test_engines.py | 7 +++++++ 3 files changed, 29 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index e0e3737..7410345 100644 --- a/README.md +++ b/README.md @@ -81,9 +81,9 @@ names `ub COMMAND` instead of the engine. Coverage and mutation runs use the target project's toolchain. Upstream coverage runners can install missing coverage tools. To read coverage already collected by your CI, use `ub check --use-existing-coverage` or `ub crap --use-existing-coverage`. -When the default Python run uses `unittest discover` and the project's top level -holds no tests, ub points it at a `tests/` or `test/` directory that has no -`__init__.py`, which plain discovery would skip. +When the default Python run uses `unittest discover` and discovery from the +project root would find no `test*.py`, ub points it at a `tests/` or `test/` +directory, which plain discovery skips when it has no `__init__.py`. By default each command prints a summary line and the items that need work: `ub crap` lists functions with CRAP ≥ 10, or above `--threshold` (complexity diff --git a/src/ub_cli/engines.py b/src/ub_cli/engines.py index de9c21c..ca24735 100644 --- a/src/ub_cli/engines.py +++ b/src/ub_cli/engines.py @@ -11,6 +11,7 @@ import contextlib import dataclasses +import fnmatch import shlex import sys from importlib import import_module @@ -198,20 +199,32 @@ def written(entries, root): return written +def _discoverable(directory: Path) -> bool: + """Whether `unittest discover -s .` finds a test*.py: at the top or inside importable packages.""" + + # shortcut: walks files like unittest does but ignores load_tests hooks; + # ask unittest itself if a project relies on them. + folders = [directory] + while folders: + for path in folders.pop().iterdir(): + if path.is_file() and fnmatch.fnmatch(path.name, "test*.py"): + return True + if path.is_dir() and (path / "__init__.py").is_file(): + folders.append(path) + return False + + def _tests_dir(command, directory: Path): - """Point a default `unittest discover` at tests/ or test/ when the top level has no tests.""" + """Point a default `unittest discover` at tests/ or test/ when `-s .` finds no tests.""" - # shortcut: assumes `-s .` finds nothing without top-level test*.py or an - # importable tests package; ask unittest itself if a layout proves this wrong. if not isinstance(command, list): return command base = command[:-2] if command[-2:] == ["-s", "."] else command - if base[-2:] != ["unittest", "discover"] or any(directory.glob("test*.py")): + if base[-2:] != ["unittest", "discover"] or _discoverable(directory): return command for name in ("tests", "test"): if (directory / name).is_dir(): - # An importable package is one `-s .` already finds. - return command if (directory / name / "__init__.py").is_file() else base + ["-s", name] + return base + ["-s", name] return command diff --git a/tests/test_engines.py b/tests/test_engines.py index b47c271..c721d82 100644 --- a/tests/test_engines.py +++ b/tests/test_engines.py @@ -260,8 +260,15 @@ def test_default_discovery_stays_when_dot_finds_tests(self): (self.root / "tests").mkdir() (self.root / "test").mkdir() (self.root / "tests" / "__init__.py").write_text("") + (self.root / "tests" / "test_a.py").write_text("") self.assertEqual(command, self.rewrite(command)) (self.root / "tests" / "__init__.py").unlink() + (self.root / "pkg" / "inner").mkdir(parents=True) + for name in ("pkg/__init__.py", "pkg/inner/__init__.py", "pkg/inner/test_deep.py"): + (self.root / name).write_text("") + self.assertEqual(command, self.rewrite(command)) + (self.root / "pkg" / "inner" / "__init__.py").unlink() + self.assertEqual(command + ["-s", "tests"], self.rewrite(command)) (self.root / "test_top.py").write_text("") self.assertEqual(command, self.rewrite(command))