Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 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
≥ 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
Expand All @@ -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.

Expand Down
66 changes: 42 additions & 24 deletions src/ub_cli/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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]:
Expand All @@ -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]]:
Expand Down Expand Up @@ -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)
Expand All @@ -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(
Expand All @@ -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)
Expand All @@ -305,20 +319,20 @@ 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)
mutation_failures, incomplete = _mutation_gate(root, files, bundle, runner, baselines, options)
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}")
Expand All @@ -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:
Expand Down Expand Up @@ -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
127 changes: 97 additions & 30 deletions src/ub_cli/engines.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
"""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 fnmatch
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 = {
Expand Down Expand Up @@ -52,7 +56,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:
Expand Down Expand Up @@ -80,7 +84,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
Expand Down Expand Up @@ -117,11 +121,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 = (
Expand All @@ -143,12 +143,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:
Expand All @@ -165,17 +167,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):
Expand All @@ -185,15 +192,75 @@ 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 _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 `-s .` finds no tests."""

if not isinstance(command, list):
return command
base = command[:-2] if command[-2:] == ["-s", "."] else command
if base[-2:] != ["unittest", "discover"] or _discoverable(directory):
return command
for name in ("tests", "test"):
if (directory / name).is_dir():
return 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)),
Expand All @@ -206,10 +273,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)),
]


Expand Down
Loading
Loading