diff --git a/.github/workflows/mutation-audit.yml b/.github/workflows/mutation-audit.yml new file mode 100644 index 0000000..c29f5fc --- /dev/null +++ b/.github/workflows/mutation-audit.yml @@ -0,0 +1,56 @@ +name: Mutation pool audit + +on: + schedule: + - cron: '0 6 * * 1' + workflow_dispatch: + +permissions: + contents: read + +jobs: + full_pool: + name: Full pool + uses: $/.github/workflows/mutation.yml + with: + test-group: full + test-selection: full + test-order: collection + full-source: true + fast_pool: + name: Fast pool + uses: $/.github/workflows/mutation.yml + with: + test-group: fast + test-selection: coverage + full-source: true + compare: + name: Compare full and fast pools + needs: [full_pool, fast_pool] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: '0.13.9' + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: '3.13' + - run: npm ci + - run: uv sync --locked --all-groups --extra binary + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: mutation-report-*-full-shard-* + path: coverage/parity/full + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: mutation-report-*-fast-shard-* + path: coverage/parity/fast + - run: uv run --locked python -m tests.compare_mutations coverage/parity/full coverage/parity/fast > coverage/parity/comparison.json + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + if: always() + with: + name: mutation-pool-comparison + path: coverage/parity/comparison.json diff --git a/.github/workflows/mutation.yml b/.github/workflows/mutation.yml index 5a3bee1..9070f9a 100644 --- a/.github/workflows/mutation.yml +++ b/.github/workflows/mutation.yml @@ -6,15 +6,41 @@ on: pull_request: branches: [main] workflow_dispatch: + inputs: + test-group: + type: choice + options: [fast, full] + default: fast + test-selection: + type: choice + options: [coverage, full] + default: coverage + workflow_call: + inputs: + test-group: + type: string + default: fast + test-selection: + type: string + default: coverage + test-order: + type: string + default: component + full-source: + type: boolean + default: false concurrency: - group: mutation-${{ github.event_name == 'pull_request' && github.ref || github.run_id }} + group: mutation-${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}-${{ inputs.test-group || 'fast' }}-${{ inputs.test-selection || 'coverage' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} permissions: contents: read env: + MUTATION_TEST_GROUP: ${{ inputs.test-group || 'fast' }} + MUTATION_TEST_SELECTION: ${{ inputs.test-selection || 'coverage' }} + MUTATION_TEST_ORDER: ${{ inputs.test-order || 'component' }} PYTHONHASHSEED: "0" TRAILMARK_REQUIRE_BINARY_TOOLS: "1" TRAILMARK_LLVM_OBJDUMP: /usr/bin/llvm-objdump @@ -38,6 +64,7 @@ jobs: id: scope env: PR_BASE_SHA: ${{ github.event.pull_request.base.sha }} + FULL_SOURCE: ${{ inputs.full-source }} run: | reviewed=false if [[ "$GITHUB_EVENT_NAME" == pull_request ]]; then @@ -47,6 +74,7 @@ jobs: reviewed=false fi fi + if [[ "$FULL_SOURCE" == true ]]; then reviewed=false; fi echo "reviewed=$reviewed" >> "$GITHUB_OUTPUT" baselines: @@ -73,11 +101,11 @@ jobs: run: | scope=() if [[ "$MUTATION_REVIEWED" == true ]]; then scope+=(--reviewed); fi - uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --baseline-shard="$BASELINE_SHARD" + uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --test-group="$MUTATION_TEST_GROUP" --test-selection="$MUTATION_TEST_SELECTION" --test-order="$MUTATION_TEST_ORDER" --baseline-shard="$BASELINE_SHARD" - name: Upload validated baselines uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: mutation-baseline + name: mutation-baseline-${{ env.MUTATION_TEST_GROUP }} overwrite: true path: | coverage/gremlins/baseline-*.json @@ -114,13 +142,13 @@ jobs: - run: uv sync --locked --all-groups --extra binary - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - name: mutation-baseline + name: mutation-baseline-${{ env.MUTATION_TEST_GROUP }} path: coverage/gremlins/baselines - name: Run mutation campaign with shared baselines run: | scope=() if [[ "$MUTATION_REVIEWED" == true ]]; then scope+=(--reviewed); fi - uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --workers=4 --shard="$MUTATION_SHARD" --baselines=coverage/gremlins/baselines + uv run --locked --extra binary python -m tests.run_mutations "${scope[@]}" --test-group="$MUTATION_TEST_GROUP" --test-selection="$MUTATION_TEST_SELECTION" --test-order="$MUTATION_TEST_ORDER" --workers=4 --shard="$MUTATION_SHARD" --baselines=coverage/gremlins/baselines - name: Enforce reviewed mutation baseline run: uv run --locked --extra binary python -m tests.mutation_gate --shard="$MUTATION_SHARD" @@ -135,7 +163,7 @@ jobs: if: always() uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: mutation-report-${{ github.sha }}-shard-${{ matrix.shard }} + name: mutation-report-${{ github.sha }}-${{ env.MUTATION_TEST_GROUP }}-shard-${{ matrix.shard }} overwrite: true path: coverage/gremlins/ if-no-files-found: error diff --git a/.gitignore b/.gitignore index 6314433..0cb023d 100644 --- a/.gitignore +++ b/.gitignore @@ -13,8 +13,10 @@ mutants/ src/trailmark/tree_sitter_custom/**/*.so src/trailmark/tree_sitter_custom/**/*.pyd +# Native cache outputs remain generated artifacts when mutations corrupt their suffix. +/src/trailmark/tree_sitter_custom/*/_binding_* .gremlins_cache/ -coverage/gremlins/ +coverage/ # Keep raw audit reports, probes, and validation logs local. /docs/audits/ /pr-audits/ diff --git a/AGENTS.md b/AGENTS.md index d02724b..c493bd0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -108,10 +108,10 @@ uv run python -m tests.mutation_gate The runner uses real pytest subprocesses and coverage-driven test selection. It validates clean and instrumented baselines, expands shared-fixture coverage to every consumer, and retains tests whose subprocesses or tracing obscure -coverage. Import-time and unmapped mutations run the full suite. Ordinary kills -require a passing neutral failure-prefix check or a matching validated full-suite -order. The control retains the full selected collection and fixture teardown. Use it -rather than invoking the pinned plugin directly. Omit +coverage. Import-time and unmapped mutations run the entire selected pool. +Ordinary kills require a passing neutral failure-prefix check or a matching +validated complete-pool order. The control retains the full selected collection +and fixture teardown. Use it rather than invoking the pinned plugin directly. Omit `--reviewed` for a full repository campaign; CI runs that after merges and on manual dispatch. `--workers` already enables parallel execution. CI produces one baseline receipt and coverage plan from a single instrumented @@ -119,9 +119,9 @@ coverage pass. Its 32 mutation jobs reuse that evidence and execute mutants without replaying full baselines or prevalidating selected subsets. Local runs validate their own baselines by default. To reproduce a partition, pass the same `--shard=1/32` (one-based index/total) to both commands. -Use `--test-selection=full` for a full-suite reference campaign. Shared coverage -preparation uses `--baseline-shard=1/1`; copy both `baseline-1-of-1.json` and -`coverage-plan.json` together when using `--baselines=PATH`. +Use `--test-group=full --test-selection=full` for an unfiltered full-suite reference. +Shared coverage preparation uses `--baseline-shard=1/1`; copy both +`baseline-1-of-1.json` and `coverage-plan.json` together when using `--baselines=PATH`. See `CONTRIBUTING.md` for baseline sharing and failure-prefix confirmation. Do not enable `TRAILMARK_UPDATE_SNAPSHOTS` during CI or mutation testing. @@ -137,3 +137,8 @@ Do not enable `TRAILMARK_UPDATE_SNAPSHOTS` during CI or mutation testing. `test_query.py`, plus focused parser/analysis/doc regression tests. - Update `README.md` and the matching regression tests if adding or changing user-facing API. + +The `mutation_fast` pool is the default; use `--test-group=full` for the full pool. +Pull requests run one mutation campaign, using the fast pool. Weekly and manual +audits compare it with the unfiltered full pool. See CONTRIBUTING.md for comparisons +and release audits. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3ff2dde..9b9ce78 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -145,11 +145,11 @@ child processes or replace Python tracing are retained for every mutant. Known native GNU/LLVM tools, C compilers, and the fixed `git -C ROOT rev-parse HEAD` provenance query are recognized through fingerprints of their executable contents. Other Git commands and Python or script wrappers remain opaque. Import-time and -unmapped locations use the full suite. +unmapped locations use the entire selected test pool. After mutant execution, ordinary test failures receive a neutral failure-prefix check. The control collects the same selected tests, executes only through the -test that failed, and includes fixture teardown. Matching full-suite orders reuse +test that failed, and includes fixture teardown. Matching complete-pool orders reuse the passing baseline. For each remaining selected collection, one successful longest prefix also validates its shorter failure prefixes. These controls use the same worker budget after the mutant pool closes. A failing neutral prefix @@ -171,14 +171,14 @@ Collection-time `SystemExit` counts as a kill only when its traceback includes an instrumented application source and the unmutated test selection loads successfully. Harness failures and unrelated internal errors remain errors. -Each mutant subprocess may run for 240 seconds so the full fallback suite can +Each mutant subprocess may run for 240 seconds so the complete fallback pool can finish with four workers competing for CI resources. A timeout is not counted as a kill unless the unmutated confirmation run establishes sufficient headroom; inconclusive outcomes still fail the gate. **Test ordering.** Within a coverage-selected subset, component unit tests run first, stopping at the first failure. Shared-helper mutants retain tests from every -language that covers the mutation. Full-suite fallbacks keep collection order so +language that covers the mutation. Complete-pool fallbacks keep collection order so they can reuse the shared neutral baseline. Tests stay in their existing files; `tests/mutation_order.py` defines the ordering, and unknown components keep collection order. Use `--test-order=collection` to @@ -196,11 +196,64 @@ mutants prioritize binding-boundary and PHP callable tests; shared parser mutant prioritize directory-linking regressions after their utility tests. **Focusing a campaign.** Pass `--targets` with comma-separated source paths, -followed by the relevant test files. +followed by the relevant test files. Use `--test-group=full` when those tests have +no `mutation_fast` marker. Snapshot updates (`TRAILMARK_UPDATE_SNAPSHOTS=1`) are disabled during CI and mutation runs; do not enable them there. +### Mutation test pools + +Mutation campaigns use the fast pool by default. It marks existing tests with +`pytest.mark.mutation_fast`; tests stay in their original modules and ordinary CI +continues to run every test. Select it explicitly with `--test-group=fast`, or use +`--test-group=full` to run mutations against the full pool. + +```bash +uv run pytest -q -m mutation_fast tests/ +uv run python -m tests.run_mutations --workers=4 --report-dir=coverage/fast +uv run python -m tests.mutation_gate --report-dir=coverage/fast + +# Full-pool comparison using the same coverage selection as routine mutation runs. +uv run python -m tests.run_mutations --test-group=full --workers=4 --report-dir=coverage/full +uv run python -m tests.compare_mutations coverage/full coverage/fast --allow-coverage-reference + +# Unfiltered reference: test pool and coverage selection are independent controls. +uv run python -m tests.run_mutations --test-group=full --test-selection=full --test-order=collection --report-dir=coverage/reference +uv run python -m tests.compare_mutations coverage/reference coverage/fast + +# Optional controlled benchmark: three serialized repetitions per configuration. +# Configure the native tool paths listed above before starting this long benchmark. +uv run python -m tests.benchmark_mutations --workers=4 --repeat=3 --output-dir=coverage/pool-benchmark +``` + +Report directories must be distinct for independent campaigns; put them under +ignored `coverage/` or outside the checkout. Comparisons require the exact source +checkout that produced the reports. They reconstruct the complete mutation inventory, +validate disjoint shard coverage and matching inputs, reject inconclusive outcomes, +and report each outcome difference rather than comparing percentages alone. +The benchmark includes clean baselines, instrumented coverage preparation, +collection, mutation execution, confirmations, and report validation. It includes +plain unsharded pytest-gremlins only as a measurement reference; normal mutation +work must use the repository runner. Result caching is disabled in these comparisons. + +The seed pool comes from the v0.9.1 campaign's recorded failing-test witnesses. +These witnesses are candidates, not evidence that each test kills independently. +Keep integration tests and collection import witnesses that provide unique kills. +When an audit loses a kill, restore the relevant existing test to the marked pool +or add a small behavioral regression, then rerun the comparison. Do not expand +equivalent-mutant exceptions or narrow the mutated application to repair parity. +Timing measurements belong in the benchmark, never in correctness assertions. + +Pull requests run one mutation campaign, using the fast pool. +`mutation-audit.yml` runs weekly on Monday at 06:00 UTC and on its manual trigger. +Each audit compares the fast pool with an unfiltered full-pool reference. Run that +manual audit against each release candidate as well. Each pool uses 32 mutation +shards and its own matching baseline. Restore every lost kill before accepting a +failed audit. Coverage-selected references require the explicit +`--allow-coverage-reference` comparison flag; the default comparison requires an +unfiltered full-pool reference. + ## Audit artifacts Keep implementations, minimized behavioral regressions, and concise decisions in diff --git a/pyproject.toml b/pyproject.toml index b62c503..0f7225d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -96,6 +96,7 @@ known-third-party = ["coverage"] [tool.pytest.ini_options] testpaths = ["tests"] markers = [ + "mutation_fast: default mutation test pool; retain full-pool parity audits", "mutation_infrastructure: validate the runner once in its clean baseline", "binary_tools: integration checks requiring the binary extra and native host tools", ] diff --git a/tests/benchmark_mutations.py b/tests/benchmark_mutations.py new file mode 100644 index 0000000..08845e4 --- /dev/null +++ b/tests/benchmark_mutations.py @@ -0,0 +1,191 @@ +"""Measure mutation pools end to end; never use elapsed time as a pytest assertion.""" + +from __future__ import annotations + +import argparse +import gzip +import json +import os +import shutil +import statistics +import subprocess +import sys +import time +from pathlib import Path +from typing import Any + +from tests.compare_mutations import compare, load_campaign +from tests.mutation_controls import input_fingerprint + + +def archive_report(directory: Path) -> None: + """Keep full test selections while avoiding multi-gigabyte duplicate reports.""" + path = directory / "gremlins.json" + with path.open("rb") as source, gzip.open(path.with_suffix(".json.gz"), "wb") as destination: + shutil.copyfileobj(source, destination) + path.unlink() + + +def benchmark(output: Path, *, repeat: int, workers: int) -> dict[str, Any]: + """Run one unfiltered reference and alternating, uncached unsharded measurements.""" + root = Path.cwd() + output = output.resolve() + if output.is_relative_to(root) and not output.is_relative_to(root / "coverage"): + raise ValueError("Put benchmark output outside the checkout or under coverage/") + output.mkdir(parents=True, exist_ok=False) + os.environ["TRAILMARK_MUTATION_TESTING"] = "1" + os.environ["TRAILMARK_REQUIRE_BINARY_TOOLS"] = "1" + if os.environ.get("PYTEST_ADDOPTS"): + raise ValueError("Unset PYTEST_ADDOPTS for the controlled benchmark") + fingerprint = input_fingerprint(root) + timings: list[dict[str, Any]] = [] + + def execute(command: list[str], destination: Path) -> float: + started = time.perf_counter() + with destination.open("w") as log: + completed = subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=False) # noqa: S603 + if completed.returncode: + raise ValueError(f"Benchmark command failed; see {destination}") + if input_fingerprint(root) != fingerprint: + raise ValueError("Benchmark inputs changed") + return time.perf_counter() - started + + def campaign(name: str, *, group: str, selection: str = "coverage") -> Path: + directory = output / name + command = [ + sys.executable, + "-m", + "tests.run_mutations", + f"--test-group={group}", + f"--test-selection={selection}", + f"--workers={workers}", + f"--report-dir={directory}", + ] + if selection == "full": + command.append("--test-order=collection") + execute(command, output / f"{name}.log") + return directory + + reference = campaign("reference", group="full", selection="full") + _, reference_rows = load_campaign(reference) + archive_report(reference) + for iteration in range(repeat): + order = ("full", "fast", "stock") if iteration % 2 == 0 else ("stock", "fast", "full") + for group in order: + name = f"{iteration + 1}-{group}" + print(f"Measuring {name}", flush=True) + clean = [ + sys.executable, + "-m", + "pytest", + "-q", + "tests", + "-m", + "mutation_fast and not mutation_infrastructure" + if group == "fast" + else "not mutation_infrastructure", + ] + clean_seconds = execute(clean, output / f"{name}-clean.log") + started = time.perf_counter() + if group != "stock": + directory = campaign(name, group=group) + comparison = compare(reference, directory) + (output / f"{name}-comparison.json").write_text( + json.dumps(comparison, indent=2) + "\n" + ) + if comparison["lost_kills"]: + raise ValueError(f"Lost kills in {name}; inspect its comparison report") + archive_report(directory) + else: + directory = output / name + command = [ + *clean, + "--gremlins", + "--gremlin-executor=subprocess", + f"--gremlin-workers={workers}", + "--gremlin-targets=src/trailmark", + "--gremlin-report=json", + f"--gremlins-html-dir={directory}", + ] + execute(command, output / f"{name}.log") + # The pinned plugin hardcodes its JSON path independently of html-dir. + directory.mkdir(parents=True, exist_ok=True) + shutil.copyfile( + root / "coverage/gremlins/gremlins.json", directory / "gremlins.json" + ) + stock = json.loads((directory / "gremlins.json").read_text()) + by_id = {row["gremlin_id"]: row for row in stock["results"]} + if len(by_id) != len(reference_rows) or set(by_id) != { + row["gremlin_id"] for row in reference_rows.values() + }: + raise ValueError("Stock mutation inventory differs") + # Persist stock outcomes for a comparison after every arm has finished. + (output / f"{name}-outcomes.json").write_text( + json.dumps({key: row["status"] for key, row in by_id.items()}) + "\n" + ) + archive_report(directory) + (root / "coverage/gremlins/gremlins.json").unlink() + timings.append( + { + "repeat": iteration + 1, + "group": group, + "clean_baseline_seconds": clean_seconds, + "campaign_and_validation_seconds": time.perf_counter() - started, + "total_seconds": clean_seconds + time.perf_counter() - started, + } + ) + (output / "timings.json").write_text(json.dumps(timings, indent=2) + "\n") + _, candidate_rows = load_campaign(output / f"{iteration + 1}-fast") + fast_by_id = {row["gremlin_id"]: row for row in candidate_rows.values()} + stock_rows = json.loads((output / f"{iteration + 1}-stock-outcomes.json").read_text()) + differences = [ + {"gremlin_id": key, "stock": status, "fast": fast_by_id[key]["status"]} + for key, status in stock_rows.items() + if status != fast_by_id[key]["status"] + ] + (output / f"{iteration + 1}-stock-comparison.json").write_text( + json.dumps(differences, indent=2) + "\n" + ) + if any(row["stock"] == "zapped" and row["fast"] != "zapped" for row in differences): + raise ValueError("Fast pool lost a stock-plugin kill") + medians = { + group: statistics.median(row["total_seconds"] for row in timings if row["group"] == group) + for group in ("full", "fast", "stock") + } + pairs = [ + {row["group"]: row["total_seconds"] for row in timings if row["repeat"] == index} + for index in range(1, repeat + 1) + ] + reduction = 1 - medians["fast"] / medians["full"] + return { + "inputs": fingerprint, + "workers": workers, + "repeat": repeat, + "median_seconds": medians, + "reduction": reduction, + "release_eligible": repeat >= 3 + and workers == 4 + and reduction >= 0.20 + and all(pair["fast"] < pair["full"] for pair in pairs), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--repeat", type=int, default=3) + parser.add_argument("--workers", type=int, default=4) + args = parser.parse_args() + if args.repeat < 1 or args.workers < 1: + parser.error("Repeat and workers must be positive") + try: + result = benchmark(args.output_dir, repeat=args.repeat, workers=args.workers) + except (OSError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"Mutation benchmark failed: {exc}\n") + (args.output_dir / "summary.json").write_text(json.dumps(result, indent=2) + "\n") + print(json.dumps(result, indent=2)) + return int(not result["release_eligible"]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/compare_mutations.py b/tests/compare_mutations.py new file mode 100644 index 0000000..7d9b487 --- /dev/null +++ b/tests/compare_mutations.py @@ -0,0 +1,181 @@ +"""Compare complete mutation campaigns without treating missing evidence as success.""" + +from __future__ import annotations + +import argparse +import gzip +import hashlib +import json +from collections import Counter +from pathlib import Path +from typing import Any + +from pytest_gremlins.instrumentation.transformer import transform_source + +from tests.mutation_inventory import inventory + + +def read_report(path: Path) -> Any: + """Accept archived reports without requiring a second uncompressed copy.""" + if path.exists(): + return json.loads(path.read_text()) + with gzip.open(path.with_suffix(path.suffix + ".gz"), "rt") as source: + return json.load(source) + + +def load_campaign(directory: Path) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: + """Load one campaign, or a complete set of its disjoint shard directories.""" + paths = ( + [directory] + if (directory / "run.json").is_file() + else sorted(path.parent for path in directory.rglob("run.json")) + ) + if not paths: + raise ValueError("Missing campaign reports") + context = None + shards = set() + results = {} + total_shards = 0 + for path in paths: + run = json.loads((path / "run.json").read_text()) + index, count = run["shard"] + if not 1 <= index <= count or (index, count) in shards: + raise ValueError("Duplicate or invalid campaign shard") + shards.add((index, count)) + total_shards = count + current = { + key: run[key] + for key in ( + "inputs", + "sources", + "targets", + "tests", + "runner", + "pytest_gremlins", + "test_order", + "test_selection", + "test_group", + "workers", + "kill_confirmation", + ) + } + if context is not None and current != context: + raise ValueError("Mismatched campaign shards") + context = current + if run["baseline_validation"] not in {"local", "shared"} or run[ + "kill_confirmation" + ] not in {"baseline-orders", "failure-prefix"}: + raise ValueError("Missing validated baseline or confirmation") + report = read_report(path / "gremlins.json") + inventory = json.loads((path / "inventory.json").read_text()) + rows = report["results"] + by_id = {row["gremlin_id"]: row for row in rows} + expected = {row["gremlin_id"]: row for row in inventory} + if ( + len(by_id) != len(rows) + or len(expected) != len(inventory) + or by_id.keys() != expected.keys() + or report.get("skipped_files") + ): + raise ValueError("Incomplete or duplicate mutation inventory") + counts = Counter(row["status"] for row in rows) + if report["summary"]["total"] != len(rows) or any( + report["summary"].get(status, 0) != count for status, count in counts.items() + ): + raise ValueError("Inconsistent mutation summary") + for identifier, row in by_id.items(): + if row["status"] not in {"zapped", "survived"} or not row["selected_tests"]: + raise ValueError("Inconclusive mutation outcome") + detail = expected[identifier] + fingerprint = detail["fingerprint"] + if fingerprint in results: + raise ValueError("Duplicate mutation fingerprint") + results[fingerprint] = { + **detail, + "status": row["status"], + "killing_test": row.get("killing_test"), + } + if shards != {(index, total_shards) for index in range(1, total_shards + 1)}: + raise ValueError("Incomplete campaign shards") + assert context is not None + return context, results + + +def compare( + reference: Path, + candidate: Path, + *, + root: Path | None = None, + require_full_reference: bool = True, +) -> dict[str, Any]: + """Report every difference, rejecting incomparable sources and test inputs.""" + before, full = load_campaign(reference) + after, fast = load_campaign(candidate) + for key in ("inputs", "sources", "targets", "tests", "runner", "pytest_gremlins", "workers"): + if before[key] != after[key]: + raise ValueError(f"Incomparable campaign {key}") + if before["test_group"] != "full" or before["test_selection"] not in {"full", "coverage"}: + raise ValueError("Reference must use the full test pool") + if require_full_reference and before["test_selection"] != "full": + raise ValueError("Reference must use the full test pool without coverage filtering") + if full.keys() != fast.keys() or not full: + raise ValueError("Campaign mutation inventories differ or are empty") + root = (root or Path.cwd()).resolve() + mutations = [] + for name, expected_hash in before["sources"].items(): + path = (root / name).resolve() + if ( + not path.is_relative_to(root) + or hashlib.sha256(path.read_bytes()).hexdigest() != expected_hash + ): + raise ValueError(f"Missing or changed campaign source: {name}") + discovered, _ = transform_source(path.read_text(), str(path)) + mutations.extend(discovered) + actual = {row["fingerprint"] for row in inventory(mutations, root)} + if actual != full.keys(): + raise ValueError("Campaign inventory does not match application sources") + differences = [ + { + "fingerprint": key, + "path": row["path"], + "function": row["function"], + "line": row["line"], + "reference": row["status"], + "candidate": fast[key]["status"], + } + for key, row in sorted(full.items()) + if row["status"] != fast[key]["status"] + ] + return { + "mutants": len(full), + "reference_kills": sum(row["status"] == "zapped" for row in full.values()), + "candidate_kills": sum(row["status"] == "zapped" for row in fast.values()), + "lost_kills": sum(row["reference"] == "zapped" for row in differences), + "differences": differences, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("reference", type=Path) + parser.add_argument("candidate", type=Path) + parser.add_argument( + "--allow-coverage-reference", + action="store_true", + help="Compare against coverage-selected full-pool results instead of an unfiltered audit", + ) + args = parser.parse_args() + try: + result = compare( + args.reference, + args.candidate, + require_full_reference=not args.allow_coverage_reference, + ) + except (OSError, ValueError, KeyError, TypeError) as exc: + parser.exit(1, f"Mutation comparison failed: {exc}\n") + print(json.dumps(result, indent=2)) + return int(bool(result["lost_kills"])) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/mutation_bootstrap.py b/tests/mutation_bootstrap.py index 3c91187..15a0df2 100644 --- a/tests/mutation_bootstrap.py +++ b/tests/mutation_bootstrap.py @@ -81,6 +81,7 @@ def record_test_execution(directory: Path) -> None: def __init__(self): self.started = [] self.failed = False + self.failures = [] self.stopped = False self.limit = int(os.environ.get('TRAILMARK_PREFIX_LIMIT', '0')) @@ -90,6 +91,7 @@ def pytest_runtest_logstart(self, nodeid): def pytest_runtest_logreport(self, report): if report.failed: self.failed = True + self.failures.append({'test': report.nodeid, 'phase': report.when}) @pytest.hookimpl(wrapper=True, tryfirst=True) def pytest_runtest_protocol(self, item): @@ -111,6 +113,7 @@ def pytest_runtest_protocol(self, item): if destination: with open(destination + '.tmp', 'w') as output: json.dump({'tests': execution.started, 'failed': execution.failed, + 'failures': execution.failures, 'stopped': execution.stopped, 'exit_code': int(exit_code)}, output) os.replace(destination + '.tmp', destination) """ diff --git a/tests/mutation_confirmation.py b/tests/mutation_confirmation.py index aa6cb06..7487964 100644 --- a/tests/mutation_confirmation.py +++ b/tests/mutation_confirmation.py @@ -52,6 +52,7 @@ def __init__(self, workers: int, output: Path, *, checked_orders: bool = False) self.output = output self.checked_orders = checked_orders self.pending: list[_PendingKill] = [] + self.witnesses: dict[str, dict[str, str]] = {} def defer( self, @@ -79,6 +80,9 @@ def flush(self, session: plugin.GremlinSession, record: _Recorder) -> None: try: evidence = _read_execution(_execution_path(directory, gremlin.gremlin_id)) executions[gremlin.gremlin_id] = evidence + failures = evidence.get("failures", []) + if failures: + self.witnesses[gremlin.gremlin_id] = failures[0] except (OSError, ValueError): evidence = None output.write( @@ -91,6 +95,7 @@ def flush(self, session: plugin.GremlinSession, record: _Recorder) -> None: ), "failed": evidence["failed"] if evidence else None, "exit_code": evidence["exit_code"] if evidence else None, + "failure": self.witnesses.get(gremlin.gremlin_id), } ) + "\n" diff --git a/tests/mutation_gate.py b/tests/mutation_gate.py index 1b8970c..5d5420a 100644 --- a/tests/mutation_gate.py +++ b/tests/mutation_gate.py @@ -130,10 +130,13 @@ def _validate_versions(run: dict[str, Any], baseline: dict[str, Any]) -> None: raise ValueError("Report lacks validated pytest failure confirmation") -def _validate_test_selection(root: Path, report: dict[str, Any], run: dict[str, Any]) -> None: +def _validate_test_selection( + root: Path, report: dict[str, Any], run: dict[str, Any], report_dir: Path | None = None +) -> None: if run["test_selection"] == "full": return - envelope = json.loads((root / "coverage/gremlins/coverage-plan.json").read_text()) + directory = report_dir if report_dir is not None else root / "coverage/gremlins" + envelope = json.loads((directory / "coverage-plan.json").read_text()) expected = { key: run[key] for key in ( @@ -147,6 +150,7 @@ def _validate_test_selection(root: Path, report: dict[str, Any], run: dict[str, ) } expected["addopts"] = envelope["context"]["addopts"] + expected["test_group"] = run.get("test_group", "full") expected["coverage_plan"] = run["selection_plan"] tests = envelope["plan"]["tests"] plan = validate_plan(envelope, expected, tests, set(run["sources"])) @@ -238,12 +242,13 @@ def check( baseline: dict[str, Any], *, shard: tuple[int, int] = (1, 1), + report_dir: Path | None = None, ) -> list[str]: _validate_versions(run, baseline) if run.get("shard") != list(shard): raise ValueError("Mutation report shard does not match the requested partition") _validate_report(report, baseline, allow_empty=shard[1] > 1) - _validate_test_selection(root, report, run) + _validate_test_selection(root, report, run, report_dir) inconclusive = [ { "path": row["file_path"], @@ -280,13 +285,14 @@ def check( def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--shard", type=parse_shard, default=(1, 1)) + parser.add_argument("--report-dir", type=Path, default=Path("coverage/gremlins")) args = parser.parse_args() root = Path.cwd() try: - report = json.loads((root / "coverage/gremlins/gremlins.json").read_text()) - run = json.loads((root / "coverage/gremlins/run.json").read_text()) + report = json.loads((args.report_dir / "gremlins.json").read_text()) + run = json.loads((args.report_dir / "run.json").read_text()) baseline = json.loads((root / "tests/mutation_baseline.json").read_text()) - failures = check(root, report, run, baseline, shard=args.shard) + failures = check(root, report, run, baseline, shard=args.shard, report_dir=args.report_dir) except (OSError, ValueError, KeyError, TypeError) as exc: print(f"Mutation gate failed: {exc}", file=sys.stderr) return 1 diff --git a/tests/mutation_inventory.py b/tests/mutation_inventory.py new file mode 100644 index 0000000..7bed0c1 --- /dev/null +++ b/tests/mutation_inventory.py @@ -0,0 +1,27 @@ +"""Stable mutation identities shared by comparison and execution reports.""" + +from __future__ import annotations + +import ast +from pathlib import Path +from typing import Any + +from pytest_gremlins.instrumentation.gremlin import Gremlin + + +def inventory(gremlins: list[Gremlin], root: Path) -> list[dict[str, Any]]: + """Describe every assigned mutation using its source rather than its ordinal ID.""" + from tests.mutation_gate import describe, functions_in + + sources = {} + result = [] + for gremlin in gremlins: + path = Path(gremlin.file_path).resolve() + if path not in sources: + source = path.read_text() + tree = ast.parse(source) + sources[path] = source, (tree, list(functions_in(tree))) + source, context = sources[path] + detail = describe(gremlin, source, path.relative_to(root.resolve()).as_posix(), context) + result.append({"gremlin_id": gremlin.gremlin_id, **detail}) + return result diff --git a/tests/run_mutations.py b/tests/run_mutations.py index cf66c98..8ab571f 100644 --- a/tests/run_mutations.py +++ b/tests/run_mutations.py @@ -14,8 +14,10 @@ import os import subprocess import sys +import time from collections import defaultdict from collections.abc import Callable, Sequence +from dataclasses import replace from importlib.metadata import version from pathlib import Path from typing import Any @@ -39,7 +41,7 @@ from tests.mutation_order import prioritize_tests, relative_node_ids VERSION = "1.14.3" -RUNNER = "trailmark-pytest-coverage-v9" +RUNNER = "trailmark-pytest-coverage-v10" def parse_shard(value: str) -> tuple[int, int]: @@ -74,6 +76,8 @@ def _arguments() -> argparse.Namespace: ) parser.add_argument("--test-order", choices=["component", "collection"], default="component") parser.add_argument("--test-selection", choices=["coverage", "full"], default="coverage") + parser.add_argument("--test-group", choices=["fast", "full"], default="fast") + parser.add_argument("--report-dir", type=Path, default=Path("coverage/gremlins")) controls = parser.add_mutually_exclusive_group() controls.add_argument( "--baseline-shard", @@ -87,6 +91,10 @@ def _arguments() -> argparse.Namespace: ) parser.add_argument("tests", nargs="*", default=["tests"]) args = parser.parse_args() + destination = args.report_dir.resolve() + root = Path.cwd().resolve() + if destination.is_relative_to(root) and not destination.is_relative_to(root / "coverage"): + parser.error("Report directories must be under coverage/ or outside the checkout") if args.workers < 1: parser.error("--workers must be positive") if version("pytest-gremlins") != VERSION: @@ -146,6 +154,7 @@ def _check_instrumented_orders( "tests": args.tests, "test_order": args.test_order, "test_selection": args.test_selection, + "test_group": args.test_group, "addopts": session.preserved_addopts, } if args.test_selection == "coverage": @@ -218,9 +227,11 @@ def write_and_check( raise pytest.UsageError(f"Mutation instrumentation skipped files: {unwritable}") record_source_collection_exits(directory) record_test_execution(directory) + started = time.perf_counter() receipts.append( _check_instrumented_orders(directory, instrumented_asts, args, fingerprint, plans) ) + args.timings["instrumented_preparation_seconds"] = time.perf_counter() - started return directory return write_and_check @@ -230,6 +241,12 @@ class _RequireCompleteInstrumentation: def __init__(self, args: argparse.Namespace) -> None: self.args = args self.empty_shard = False + self.inventory: list[dict[str, Any]] = [] + self.started = time.perf_counter() + + @pytest.hookimpl(tryfirst=True) + def pytest_collection_modifyitems(self) -> None: + self.args.timings["collection_and_startup_seconds"] = time.perf_counter() - self.started @pytest.hookimpl(trylast=True) def pytest_collection_finish(self) -> None: @@ -243,6 +260,9 @@ def pytest_collection_finish(self) -> None: if self.args.baseline_shard: session.enabled = False selected = select_shard(session.gremlins, self.args.shard) + from tests.mutation_inventory import inventory + + self.inventory = inventory(selected, Path.cwd()) self.empty_shard = bool(session.gremlins) and not selected session.gremlins = selected @@ -266,6 +286,7 @@ def _run_campaign( cache_result = plugin._cache_gremlin_result dispatch = plugin._dispatch_mutation_run selections: dict[str, list[str]] = {} + confirmed: dict[str, plugin.GremlinResult] = {} def record_confirmed_result( gremlin: Gremlin, @@ -275,6 +296,10 @@ def record_confirmed_result( ) -> None: # Native collection/timeout checks and our failure-prefix checks have # finished before a result reaches this publication point. + witness = controls.witnesses.get(gremlin.gremlin_id) + if witness is not None: + result = replace(result, killing_test=witness["test"]) + confirmed[gremlin.gremlin_id] = result cache_result(gremlin, selected_tests, result, session) with (report_dir / "progress.jsonl").open("a") as progress: progress.write( @@ -287,6 +312,8 @@ def record_confirmed_result( "status": result.status.value, "selected_test_count": len(result.selected_tests), "execution_time_ms": result.execution_time_ms, + "killing_test": result.killing_test, + "failure_phase": witness["phase"] if witness else None, } ) + "\n" @@ -304,9 +331,13 @@ def record_result( def dispatch_and_confirm( session: pytest.Session, gremlin_session: plugin.GremlinSession ) -> list[plugin.GremlinResult]: + started = time.perf_counter() results = dispatch(session, gremlin_session) + args.timings["mutation_execution_seconds"] = time.perf_counter() - started + started = time.perf_counter() controls.flush(gremlin_session, record_confirmed_result) - return results + args.timings["confirmation_seconds"] = time.perf_counter() - started + return [confirmed.get(result.gremlin.gremlin_id, result) for result in results] def uncached_tests(gremlin: Gremlin, session: plugin.GremlinSession) -> list[str]: tests = list(session.test_node_ids) @@ -333,6 +364,16 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: if args.test_selection == "coverage": print("Reusing coverage from the validated baseline", flush=True) + def write_json( + score: plugin.MutationScore, + rootdir: Path, + *, + skipped_files: dict[str, str] | None = None, + ) -> Path: + destination = report_dir / "gremlins.json" + plugin.JsonReporter().write_report(score, destination, skipped_files=skipped_files) + return destination + instrumentation = _RequireCompleteInstrumentation(args) with ( patch.object( @@ -345,13 +386,18 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: patch.object(plugin, "_collect_coverage", side_effect=reuse_coverage), patch.object(plugin, "_cache_gremlin_result", side_effect=record_result), patch.object(plugin, "_dispatch_mutation_run", side_effect=dispatch_and_confirm), + patch.object(plugin, "_write_json_report", side_effect=write_json), ): result = pytest.main( [ "-q", *args.tests, "-m", - "not mutation_infrastructure", + ( + "mutation_fast and not mutation_infrastructure" + if args.test_group == "fast" + else "not mutation_infrastructure" + ), "--gremlins", "--gremlin-executor=subprocess", *(["--gremlin-no-coverage-filter"] if args.test_selection == "full" else []), @@ -362,6 +408,10 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: ], plugins=[instrumentation], ) + if result == 0 and not args.baseline_shard: + (report_dir / "inventory.json").write_text( + json.dumps(instrumentation.inventory, indent=2) + "\n" + ) if result == 0 and instrumentation.empty_shard and not args.baseline_shard: (report_dir / "gremlins.json").write_text( json.dumps({"summary": {"total": 0}, "results": []}) + "\n" @@ -370,9 +420,11 @@ def reuse_coverage(session: plugin.GremlinSession, rootdir: Path) -> None: def main() -> int: + started = time.perf_counter() args = _arguments() + args.timings = {} os.environ["TRAILMARK_MUTATION_TESTING"] = "1" - report_dir = Path("coverage/gremlins") + report_dir = args.report_dir report_dir.mkdir(parents=True, exist_ok=True) for name in ( "run.json", @@ -381,6 +433,7 @@ def main() -> int: "coverage-plan.json", "prefix-summary.json", "executions.jsonl", + "inventory.json", ): (report_dir / name).unlink(missing_ok=True) receipt_path = None @@ -412,11 +465,15 @@ def main() -> int: "inputs": fingerprint, "test_order": args.test_order, "test_selection": args.test_selection, + "test_group": args.test_group, + "workers": args.workers, "selection_plan": plans[0]["digest"] if plans else None, "shard": args.shard, "targets": args.targets, "sources": hashes, "tests": args.tests, + "wall_seconds": time.perf_counter() - started, + "timings": args.timings, "baseline_validation": "shared" if args.baselines is not None else "local", "kill_confirmation": ( "baseline-orders" if args.test_selection == "full" else "failure-prefix" diff --git a/tests/test_aiken_parser.py b/tests/test_aiken_parser.py index 50a8d00..8d71726 100644 --- a/tests/test_aiken_parser.py +++ b/tests/test_aiken_parser.py @@ -21,6 +21,7 @@ def _source(tmp_path: Path, text: str) -> Path: return path +@pytest.mark.mutation_fast @pytest.mark.parametrize( ("owner", "expected"), [("sample", "sample:run"), ("sample:validator", "sample:validator.run")] ) @@ -29,6 +30,7 @@ def test_callable_ids_keep_the_module_and_lexical_owner(owner: str, expected: st assert extractor.child_id(owner, "run") == expected +@pytest.mark.mutation_fast def test_types_signatures_imports_and_branches(tmp_path: Path) -> None: path = _source( tmp_path, @@ -62,6 +64,7 @@ def test_types_signatures_imports_and_branches(tmp_path: Path) -> None: ) +@pytest.mark.mutation_fast @pytest.mark.parametrize( "purpose", ["mint", "spend", "withdraw", "publish", "vote", "propose", "else"] ) @@ -83,6 +86,7 @@ def test_handlers_are_reachable_entrypoints(tmp_path: Path, purpose: str) -> Non assert engine.entrypoint_paths_to("helper") +@pytest.mark.mutation_fast def test_pipeline_calls_once_per_stage(tmp_path: Path) -> None: path = _source( tmp_path, "fn first(x) { x } fn second(x, y) { x } fn f(x) { x |> first |> second(1) }" @@ -95,6 +99,7 @@ def test_pipeline_calls_once_per_stage(tmp_path: Path) -> None: ] +@pytest.mark.mutation_fast def test_callback_and_import_do_not_bind_to_namesakes(tmp_path: Path) -> None: _source( tmp_path, @@ -141,6 +146,7 @@ def test_sibling_validator_handlers_stay_distinct(tmp_path: Path) -> None: } +@pytest.mark.mutation_fast def test_parse_errors_warn(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None: path = tmp_path / "broken.ak" path.write_text("validator broken { spend(") diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 4e68ff5..17dbd57 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -28,6 +28,7 @@ FIXTURES = Path(__file__).parent / "fixtures" / "audit" +@pytest.mark.mutation_fast def test_proto_nested_fields_and_public_import() -> None: graph = parse_file(str(FIXTURES / "proto/cases/schema.proto"), "proto") for owner in ("Request", "Response"): @@ -48,6 +49,7 @@ def test_proto_nested_fields_and_public_import() -> None: assert not any(e.kind == EdgeKind.CALLS for e in graph.edges) +@pytest.mark.mutation_fast def test_graphql_effective_roots() -> None: engine = QueryEngine.from_directory( str(FIXTURES / "graphql/explicit_roots"), language="graphql" @@ -60,6 +62,7 @@ def test_graphql_effective_roots() -> None: } +@pytest.mark.mutation_fast def test_graphql_wrapped_type_dependencies() -> None: graph = parse_file(str(FIXTURES / "graphql/signatures/schema.graphql"), "graphql") wrapped = [ @@ -77,6 +80,7 @@ def test_graphql_wrapped_type_dependencies() -> None: ) +@pytest.mark.mutation_fast @pytest.mark.parametrize("mode", ["single", "split"]) def test_graphql_extensions(mode: str) -> None: graph = parse_directory(str(FIXTURES / "graphql/extensions" / mode), "graphql") @@ -85,6 +89,7 @@ def test_graphql_extensions(mode: str) -> None: assert not any(edge.kind == EdgeKind.CALLS for edge in graph.edges) +@pytest.mark.mutation_fast @pytest.mark.parametrize("artifact", [{"index": 0}, {"uri": "app.py", "uriBaseId": "SRC"}]) def test_sarif_run_locations_bind_correct_source(tmp_path: Path, artifact: dict) -> None: graph = CodeGraph(root_path=str(tmp_path)) @@ -123,6 +128,7 @@ def test_sarif_run_locations_bind_correct_source(tmp_path: Path, artifact: dict) assert set(graph.annotations) == {"lib"} +@pytest.mark.mutation_fast def test_thrift_file_identity_and_signature_types() -> None: graph = parse_directory(str(FIXTURES / "thrift/identity"), "thrift") requests = [unit for unit in graph.nodes.values() if unit.name == "Request"] @@ -155,6 +161,7 @@ def test_thrift_file_identity_and_signature_types() -> None: ) +@pytest.mark.mutation_fast @pytest.mark.parametrize("case", ["contract", "contract_inline", "impl_self"]) def test_sway_implemented_abi_entrypoints(case: str) -> None: engine = QueryEngine.from_directory(str(FIXTURES / "sway" / case), language="sway") @@ -162,6 +169,7 @@ def test_sway_implemented_abi_entrypoints(case: str) -> None: assert engine.entrypoint_paths_to("sink") +@pytest.mark.mutation_fast def test_sway_generic_impl_owners() -> None: graph = parse_directory(str(FIXTURES / "sway/generic"), "sway") assert "main:get" not in graph.nodes @@ -175,6 +183,7 @@ def test_sway_generic_impl_owners() -> None: } == {f"main:{sink}"} +@pytest.mark.mutation_fast def test_func_method_variants_and_lexical_callbacks() -> None: graph = parse_file(str(FIXTURES / "func/methods.fc"), "func") @@ -200,6 +209,7 @@ def callees(name: str) -> set[str]: assert sum(edge.target_id == "methods:helper" for edge in scoped_edges) == 1 +@pytest.mark.mutation_fast def test_func_semantic_getters_and_reserved_handlers() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "func"), language="func") ids = {row["node_id"] for row in engine.attack_surface()} @@ -207,6 +217,7 @@ def test_func_semantic_getters_and_reserved_handlers() -> None: assert "constructs:get_private" not in ids +@pytest.mark.mutation_fast @pytest.mark.parametrize( "language,name,source", [("python", "bad.py", "def broken(:\n pass\n"), ("c", "bad.c", "int f() { return 1 }\n")], @@ -255,6 +266,7 @@ def test_cli_strict_analysis( assert "Incomplete source analysis" in output.err +@pytest.mark.mutation_fast @pytest.mark.parametrize("directory", [False, True]) def test_python_callable_ownership_and_shadowing(tmp_path: Path, directory: bool) -> None: path = tmp_path / "owned.py" @@ -307,6 +319,7 @@ def static(self, cls): pass assert [p.name for p in graph.nodes["owned:C.static"].parameters] == ["self", "cls"] +@pytest.mark.mutation_fast @pytest.mark.parametrize("language,extension", [("javascript", ".js"), ("typescript", ".ts")]) def test_ecmascript_nested_callable_ownership( tmp_path: Path, language: str, extension: str @@ -334,6 +347,7 @@ def test_ecmascript_nested_callable_ownership( assert not graph.parse_diagnostics +@pytest.mark.mutation_fast def test_typescript_tsx_and_interface_signatures() -> None: graph = parse_file(str(FIXTURES / "typescript/tsx/case.tsx"), "typescript", strict=True) calls = {(e.source_id, e.target_id) for e in graph.edges if e.kind == EdgeKind.CALLS} @@ -345,6 +359,7 @@ def test_typescript_tsx_and_interface_signatures() -> None: assert member.type_parameters[0].name == "U" +@pytest.mark.mutation_fast def test_typescript_receiver_invalidations() -> None: graph = parse_directory(str(FIXTURES / "typescript/receivers"), "typescript") calls = [e for e in graph.edges if e.kind == EdgeKind.CALLS] @@ -365,6 +380,7 @@ def _calls(graph: CodeGraph, source: str) -> list[str]: return [e.target_id for e in graph.edges if e.source_id == source and e.kind == EdgeKind.CALLS] +@pytest.mark.mutation_fast def test_sql_identity_body_ownership_and_identifier_matching() -> None: graph = parse_directory(str(FIXTURES / "sql/identities"), "sql") overloads = [n for n in graph.nodes.values() if n.name == "lookup"] @@ -403,6 +419,7 @@ def test_sql_identity_body_ownership_and_identifier_matching() -> None: assert ("z_views:app.mixed_distinct", 'a_tables:app."MiXeD"') not in dependencies +@pytest.mark.mutation_fast def test_r_binding_order_mutation_and_quoted_syntax() -> None: graph = parse_file(str(FIXTURES / "r/scope/main.R"), "r") calls = [e for e in graph.edges if e.source_id == "main:main" and e.kind == EdgeKind.CALLS] @@ -415,6 +432,7 @@ def test_r_binding_order_mutation_and_quoted_syntax() -> None: assert engine.paths_between("main:main", "main:helper") == [] +@pytest.mark.mutation_fast def test_miden_invocation_kinds_qualified_names_and_entrypoints() -> None: graph = parse_directory(str(FIXTURES / "masm/qualified"), "masm") assert "client:check" not in _calls(graph, "client:caller") @@ -431,6 +449,7 @@ def test_miden_invocation_kinds_qualified_names_and_entrypoints() -> None: assert {row["node_id"] for row in engine.attack_surface()} == {"library:api", "program:begin"} +@pytest.mark.mutation_fast def test_zig_identifiers_signatures_and_destructured_binding_guard() -> None: graph = parse_file(str(FIXTURES / "zig/quoted.zig"), "zig") assert _calls(graph, "quoted:main") == [ @@ -450,6 +469,7 @@ def test_zig_identifiers_signatures_and_destructured_binding_guard() -> None: assert graph.nodes[calls[0]].kind == NodeKind.PROXY +@pytest.mark.mutation_fast def test_aiken_labels_and_deferred_captures() -> None: graph = parse_directory(str(FIXTURES / "aiken/labels"), "aiken") assert [p.name for p in graph.nodes["sample:another"].parameters] == ["helper"] @@ -460,6 +480,7 @@ def test_aiken_labels_and_deferred_captures() -> None: assert _calls(graph, "sample:passed") == ["sample:receives"] +@pytest.mark.mutation_fast def test_lua_local_assignments_and_environment() -> None: graph = parse_directory(str(FIXTURES / "lua/lexical"), "lua") assert all( @@ -471,6 +492,7 @@ def test_lua_local_assignments_and_environment() -> None: assert "environment:helper" not in _calls(graph, "environment:main") +@pytest.mark.mutation_fast @pytest.mark.parametrize("case", ["quoted_eval", "escaped_eval", "quoted_source", "quoted_unset"]) def test_bash_static_command_words_invalidate_bindings(case: str) -> None: graph = parse_directory(str(FIXTURES / "bash/cases" / case), "bash") @@ -479,6 +501,7 @@ def test_bash_static_command_words_invalidate_bindings(case: str) -> None: assert "./library.bash" in graph.dependencies +@pytest.mark.mutation_fast def test_bash_coproc_and_time_ownership() -> None: graph = parse_file(str(FIXTURES / "bash/cases/coproc/sample.sh"), "bash", strict=True) assert graph.nodes["sample:main"].location.end_line == 8 @@ -487,6 +510,7 @@ def test_bash_coproc_and_time_ownership() -> None: assert _calls(graph, "sample:main").count("sample:helper") == 2 +@pytest.mark.mutation_fast def test_go_generics_signatures_and_package_boundaries() -> None: graph = parse_directory(str(FIXTURES / "go"), "go") assert _calls(graph, "features:genericCaller") == ["features:identity"] @@ -517,12 +541,14 @@ def test_rust_impl_bodies_remain_distinct(case: str) -> None: assert graph.nodes[_calls(graph, method.id)[0]].name in {"first_sink", "second_sink"} +@pytest.mark.mutation_fast def test_rust_2024_exports() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "rust/ffi2024"), language="rust") names = {row["node_id"].split(":")[-1] for row in engine.attack_surface()} assert {"hidden_export", "rust_abi_export", "signature_control"} <= names +@pytest.mark.mutation_fast def test_cairo_module_ownership_and_embedded_abi() -> None: graph = parse_directory(str(FIXTURES / "cairo/core/src"), "cairo") assert _calls(graph, "lib:local.caller") == ["lib:local.helper"] @@ -546,6 +572,7 @@ def test_cairo_module_ownership_and_embedded_abi() -> None: } +@pytest.mark.mutation_fast def test_php_namespace_and_callable_ownership() -> None: graph = parse_file(str(FIXTURES / "php/namespaces.php"), "php", strict=True) for namespace in ("Alpha", "Beta"): @@ -569,6 +596,7 @@ def test_php_namespace_and_callable_ownership() -> None: assert "call_forms:Base.parentAction" in calls +@pytest.mark.mutation_fast def test_perl_package_context_defaults_and_bare_calls() -> None: graph = parse_directory(str(FIXTURES / "perl/fixtures/qualified_body"), "perl") assert _calls(graph, "qualified_body:Beta.main") == ["qualified_body:Alpha.helper"] @@ -591,6 +619,7 @@ def test_powershell_mutators_keep_stale_functions_unresolved(case: str) -> None: ) +@pytest.mark.mutation_fast def test_powershell_callback_signatures_and_header_defaults() -> None: graph = parse_directory(str(FIXTURES / "powershell/parameters"), "powershell") for name, annotation in (("Invoke-Work", "string"), ("Invoke-Header", "int")): @@ -613,6 +642,7 @@ def test_powershell_callback_signatures_and_header_defaults() -> None: assert _calls(graph, callback.id) == ["sample:Get-Default"] +@pytest.mark.mutation_fast def test_vb_field_and_property_shadows() -> None: graph = parse_directory(str(FIXTURES / "vb/field_shadow"), "vb") assert "sample:Sink.Execute" not in _calls(graph, "sample:App.Run") @@ -627,6 +657,7 @@ def test_vb_field_and_property_shadows() -> None: assert dict(graph.nodes[f"sample:App.Value.{accessor}"].attributes)["vb_shared"] is True +@pytest.mark.mutation_fast def test_vb_array_declarators_retain_main_entrypoint() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "vb/array_main"), language="vb") assert engine.entrypoint_paths_to("sample:App.Helper") == [ @@ -636,6 +667,7 @@ def test_vb_array_declarators_retain_main_entrypoint() -> None: assert graph.nodes["sample:App.Main"].parameters[0].type_ref == TypeRef("String()") +@pytest.mark.mutation_fast def test_julia_destructuring_quotes_and_callable_methods(tmp_path: Path) -> None: engine = QueryEngine.from_directory( str(FIXTURES / "julia/cases/destructuring"), language="julia" @@ -665,6 +697,7 @@ def test_julia_destructuring_quotes_and_callable_methods(tmp_path: Path) -> None assert graph.nodes["case:Handler.__call__"].parameters[0] == Parameter("h", TypeRef("Handler")) +@pytest.mark.mutation_fast def test_c_indirect_calls_and_tag_namespaces() -> None: graph = parse_directory(str(FIXTURES / "c/shadowing"), "c") for name in ("dispatch", "explicit_indirect", "local_shadow"): @@ -681,6 +714,7 @@ def test_c_indirect_calls_and_tag_namespaces() -> None: assert target != f"{module}:{name}" +@pytest.mark.mutation_fast def test_solidity_call_options_and_declaration_arguments() -> None: graph = parse_directory(str(FIXTURES / "solidity/call_options"), "solidity") calls = [e for e in graph.edges if e.kind == EdgeKind.CALLS] @@ -699,6 +733,7 @@ def test_solidity_call_options_and_declaration_arguments() -> None: ] +@pytest.mark.mutation_fast def test_cpp_namespace_identity_and_deferred_ownership(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "cpp/namespace_scope"), "cpp") for namespace in ("alpha", "beta"): @@ -728,6 +763,7 @@ def test_cpp_namespace_identity_and_deferred_ownership(tmp_path: Path) -> None: assert "case:Holder.callback" not in _calls(graph, f"case:{name}") +@pytest.mark.mutation_fast def test_csharp_namespaces_shadowing_and_call_forms() -> None: graph = parse_directory(str(FIXTURES / "c_sharp/fixtures"), "c_sharp") for namespace, method in (("First", "FirstOnly"), ("Second", "SecondOnly")): @@ -745,6 +781,7 @@ def test_csharp_namespaces_shadowing_and_call_forms() -> None: assert graph.nodes[_calls(graph, f"{prefix}.Nullable")[0]].kind == NodeKind.PROXY +@pytest.mark.mutation_fast def test_java_deferred_owners_explicit_construction_and_servlets(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "java/ownership"), "java") for name in ("deferred", "local", "anonymous"): @@ -770,6 +807,7 @@ def test_java_deferred_owners_explicit_construction_and_servlets(tmp_path: Path) assert {e["node_id"] for e in engine.attack_surface()} == {"Servlets:Web.doGet"} +@pytest.mark.mutation_fast def test_swift_extensions_scopes_and_deferred_bodies(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "swift/extensions"), "swift") assert graph.nodes["probe:Service"].kind == NodeKind.STRUCT @@ -793,6 +831,7 @@ def test_swift_extensions_scopes_and_deferred_bodies(tmp_path: Path) -> None: ) +@pytest.mark.mutation_fast def test_kotlin_nested_companions_and_local_owners() -> None: graph = parse_directory(str(FIXTURES / "kotlin/fixtures"), "kotlin") _assert_deferred_reachable(graph, "Ownership:caller") @@ -806,6 +845,7 @@ def test_kotlin_nested_companions_and_local_owners() -> None: assert "Ownership:Outer.Companion.main" in {e["node_id"] for e in engine.attack_surface()} +@pytest.mark.mutation_fast def test_objc_selectors_dispatch_identity_and_blocks() -> None: graph = parse_directory(str(FIXTURES / "objc/fixtures/selectors"), "objc") assert _calls(graph, "Selectors:Worker.+touch") == ["Selectors:class_sink"] @@ -833,6 +873,7 @@ def test_objc_selectors_dispatch_identity_and_blocks() -> None: assert _calls(graph, block.id) == ["Blocks:callback_sink"] +@pytest.mark.mutation_fast def test_dart_constructors_arrows_and_lexical_binding() -> None: graph = parse_file(str(FIXTURES / "dart/constructors.dart"), "dart", strict=True) constructors = [n for n in graph.nodes.values() if dict(n.attributes).get("dart_constructor")] @@ -854,6 +895,7 @@ def test_dart_constructors_arrows_and_lexical_binding() -> None: _assert_deferred_reachable(graph, "binding:deferred") +@pytest.mark.mutation_fast def test_circom_include_visibility_discard_and_main_arguments(tmp_path: Path) -> None: graph = parse_directory(str(FIXTURES / "circom/includes"), "circom") assert set(_calls(graph, "circuit:Root")) == {"lib.child:Child", "lib.child:width"} @@ -871,6 +913,7 @@ def test_circom_include_visibility_discard_and_main_arguments(tmp_path: Path) -> assert all(target not in {"a:Child", "b:Child"} for target in _calls(graph, "root:main")) +@pytest.mark.mutation_fast def test_move_qualified_generics_callbacks_and_modules() -> None: graph = parse_directory(str(FIXTURES / "move/bindings"), "move") assert _calls(graph, "caller:0x42::caller:run").count("caller:0x42::caller:transfer") == 1 @@ -898,6 +941,7 @@ def test_move_qualified_generics_callbacks_and_modules() -> None: ) +@pytest.mark.mutation_fast def test_move_entrypoint_modifiers_and_generic_comparison_control(tmp_path: Path) -> None: engine = QueryEngine.from_directory(str(FIXTURES / "move/entrypoints"), language="move") assert {row["node_id"].rsplit(":", 1)[-1] for row in engine.attack_surface()} == { @@ -914,6 +958,7 @@ def test_move_entrypoint_modifiers_and_generic_comparison_control(tmp_path: Path assert _calls(graph, "nested:0x1::test:run") == ["nested:0x1::test:id"] +@pytest.mark.mutation_fast def test_tact_static_member_binding_and_receiver_signatures() -> None: graph = parse_file(str(FIXTURES / "tact/binding/wallet.tact"), "tact") targets = _calls(graph, "wallet:Wallet.receive") @@ -928,6 +973,7 @@ def test_tact_static_member_binding_and_receiver_signatures() -> None: assert graph.nodes["wallet:Wallet.current"].return_type == TypeRef("Int") +@pytest.mark.mutation_fast @pytest.mark.parametrize( "case,package", [("repeated", "repeated"), ("cross_clause", "crossclause")] ) @@ -951,6 +997,7 @@ def test_rego_else_and_head_calls_stay_with_clause() -> None: assert _calls(graph, clause) == ["multibody:helper"] +@pytest.mark.mutation_fast @pytest.mark.parametrize( "language,path", [ @@ -969,6 +1016,7 @@ def test_unsupported_syntax_reports_diagnostics_and_strict_rejects( parse_file(str(FIXTURES / path), language, strict=True) +@pytest.mark.mutation_fast def test_ruby_owners_vcalls_and_entrypoint_visibility() -> None: graph = parse_file(str(FIXTURES / "ruby/fixtures/namespaces.rb"), "ruby") assert { @@ -998,6 +1046,7 @@ def test_ruby_owners_vcalls_and_entrypoint_visibility() -> None: assert not any(target.endswith(":item") for target in _calls(graph, "modern:iterate")) +@pytest.mark.mutation_fast def test_erlang_arity_exports_specs_and_qualified_calls() -> None: graph = parse_file(str(FIXTURES / "erlang/arity/arity_demo.erl"), "erlang") assert _calls(graph, "arity_demo:choose/0") == ["arity_demo:zero_sink/0"] @@ -1019,6 +1068,7 @@ def test_erlang_arity_exports_specs_and_qualified_calls() -> None: assert not engine.paths_between("caller:dynamic/2", "local_target:hit/0") +@pytest.mark.mutation_fast def test_erlang_closure_creation_capture_and_target_evaluation() -> None: graph = parse_file(str(FIXTURES / "erlang/closures/closure_demo.erl"), "erlang") for source in ("capture/0", "remote_capture/0"): @@ -1032,6 +1082,7 @@ def test_erlang_closure_creation_capture_and_target_evaluation() -> None: assert "closure_demo:maker/0" in _calls(graph, "closure_demo:factory_call/0") +@pytest.mark.mutation_fast def test_haskell_lexical_owners_binding_and_call_syntax() -> None: engine = QueryEngine.from_directory(str(FIXTURES / "haskell/fixtures"), language="haskell") graph = parse_directory(str(FIXTURES / "haskell/fixtures"), "haskell") @@ -1053,6 +1104,7 @@ def test_haskell_lexical_owners_binding_and_call_syntax() -> None: assert all(target.startswith("proxy.") for target in _calls(graph, "Syntax:viaDollar")) +@pytest.mark.mutation_fast def test_go_directory_linking_respects_package_even_in_polyglot(tmp_path: Path) -> None: (tmp_path / "app.go").write_text("package app\nfunc Run() { missing() }") (tmp_path / "other_test.go").write_text("package app_test\nfunc missing() {}") @@ -1072,6 +1124,7 @@ def test_skipped_verus_reports_structured_diagnostic(tmp_path: Path) -> None: parse_file(str(path), "rust", strict=True) +@pytest.mark.mutation_fast def test_solidity_inherited_callable_storage_blocks_free_binding(tmp_path: Path) -> None: (tmp_path / "base.sol").write_text( "contract Base { function() internal work; function helper() internal {} }" @@ -1086,6 +1139,7 @@ def test_solidity_inherited_callable_storage_blocks_free_binding(tmp_path: Path) assert any("$binding.work" in target for target in _calls(graph, "child:Child.run")) +@pytest.mark.mutation_fast def test_sql_replacement_signature_excludes_default_and_normalizes_schema(tmp_path: Path) -> None: path = tmp_path / "replace.sql" path.write_text( @@ -1108,6 +1162,7 @@ def test_sql_replacement_signature_excludes_default_and_normalizes_schema(tmp_pa assert routine.parameters[0].type_ref == TypeRef("integer") +@pytest.mark.mutation_fast @pytest.mark.parametrize( "artifact", [ @@ -1136,6 +1191,7 @@ def test_sarif_invalid_bases_and_indices_remain_unmatched(tmp_path: Path, artifa assert not graph.annotations +@pytest.mark.mutation_fast @pytest.mark.parametrize("definition", ["struct same;", "struct same { int value; };"]) def test_c_tag_collision_retains_both_containment_edges(tmp_path: Path, definition: str) -> None: source = tmp_path / "tag.c" @@ -1151,6 +1207,7 @@ def test_c_tag_collision_retains_both_containment_edges(tmp_path: Path, definiti assert {"tag:same", function.id} <= children +@pytest.mark.mutation_fast def test_ruby_named_visibility_is_local_to_its_class(tmp_path: Path) -> None: (tmp_path / "nested.rb").write_text( "class Outer < ApplicationController\n def show; end\n" @@ -1160,6 +1217,7 @@ def test_ruby_named_visibility_is_local_to_its_class(tmp_path: Path) -> None: assert {row["node_id"] for row in engine.attack_surface()} == {"nested:Outer.Inner.show"} +@pytest.mark.mutation_fast def test_static_namespace_linking_keeps_file_local_visibility(tmp_path: Path) -> None: (tmp_path / "owner.cpp").write_text( "namespace Util { static void local() {} static void remote() {} }\n" @@ -1171,6 +1229,7 @@ def test_static_namespace_linking_keeps_file_local_visibility(tmp_path: Path) -> assert "owner:Util.remote" not in _calls(graph, "other:other") +@pytest.mark.mutation_fast def test_cross_file_linking_go_same_package_and_python_import(tmp_path: Path) -> None: (tmp_path / "app.go").write_text("package app\nfunc Run() { helper() }") (tmp_path / "helper.go").write_text("package app\nfunc helper() {}") @@ -1184,6 +1243,7 @@ def test_cross_file_linking_go_same_package_and_python_import(tmp_path: Path) -> assert _calls(graph, "app:run") == ["pkg.helper:helper"] +@pytest.mark.mutation_fast @pytest.mark.parametrize("kind,blocked", [(EdgeKind.CALLS, True), (EdgeKind.READS, False)]) def test_rust_alias_resolution_preserves_blocked_and_noncall_edges( tmp_path: Path, kind: EdgeKind, blocked: bool diff --git a/tests/test_augment.py b/tests/test_augment.py index 089e3fa..f671cc4 100644 --- a/tests/test_augment.py +++ b/tests/test_augment.py @@ -77,13 +77,16 @@ def _write_json(tmp_path: Any, name: str, data: dict[str, Any]) -> str: class TestNormalizePath: + @pytest.mark.mutation_fast def test_relative_path(self) -> None: assert _normalize_path("src/handler.py", _ROOT) == "src/handler.py" + @pytest.mark.mutation_fast def test_absolute_path(self) -> None: result = _normalize_path("/project/src/handler.py", _ROOT) assert result == "src/handler.py" + @pytest.mark.mutation_fast def test_file_uri(self) -> None: result = _normalize_path( "file:///project/src/handler.py", @@ -105,6 +108,7 @@ def test_absolute_path_outside_root(self) -> None: class TestFindOverlappingNodes: + @pytest.mark.mutation_fast def test_exact_match(self) -> None: graph = _build_graph() nodes = _find_overlapping_nodes(graph, "src/handler.py", 10, 30) @@ -116,6 +120,7 @@ def test_partial_overlap(self) -> None: assert "mod:func_a" in nodes assert "mod:func_b" in nodes + @pytest.mark.mutation_fast def test_no_overlap(self) -> None: graph = _build_graph() nodes = _find_overlapping_nodes(graph, "src/handler.py", 51, 60) @@ -123,6 +128,7 @@ def test_no_overlap(self) -> None: ids = [n for n in nodes if "func" in n] assert ids == [] + @pytest.mark.mutation_fast def test_wrong_file(self) -> None: graph = _build_graph() nodes = _find_overlapping_nodes(graph, "src/other.py", 10, 30) @@ -186,6 +192,7 @@ def _sarif_result( class TestAugmentFromSarif: + @pytest.mark.mutation_fast def test_matches_finding_to_node(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -205,6 +212,7 @@ def test_matches_finding_to_node(self, tmp_path: Any) -> None: assert result["matched_findings"] == 1 assert result["unmatched_findings"] == 0 + @pytest.mark.mutation_fast def test_annotation_format(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -361,6 +369,7 @@ def _weaudit_entry( class TestAugmentFromWeaudit: + @pytest.mark.mutation_fast def test_matches_finding_with_line_conversion( self, tmp_path: Any, @@ -379,6 +388,7 @@ def test_matches_finding_with_line_conversion( result = augment_from_weaudit(store, path) assert result["matched_findings"] == 1 + @pytest.mark.mutation_fast def test_finding_annotation_kind(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -393,6 +403,7 @@ def test_finding_annotation_kind(self, tmp_path: Any) -> None: anns = graph.annotations.get("mod:func_a", []) assert any(a.kind == AnnotationKind.FINDING for a in anns) + @pytest.mark.mutation_fast def test_note_annotation_kind(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -427,6 +438,7 @@ def test_source_includes_author(self, tmp_path: Any) -> None: anns = graph.annotations.get("mod:func_a", []) assert any(a.source == "weaudit:alice" for a in anns) + @pytest.mark.mutation_fast def test_severity_subgraphs(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -455,6 +467,7 @@ def test_severity_subgraphs(self, tmp_path: Any) -> None: assert "weaudit:low" in result["subgraphs_created"] assert "weaudit:findings" in result["subgraphs_created"] + @pytest.mark.mutation_fast def test_description_format(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -489,6 +502,7 @@ def test_resolved_entries_included(self, tmp_path: Any) -> None: class TestClearAugmented: + @pytest.mark.mutation_fast def test_clear_sarif(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -524,6 +538,7 @@ def test_clear_removes_subgraphs(self, tmp_path: Any) -> None: clear_augmented(store, "sarif") assert not any(k.startswith("sarif:") for k in graph.subgraphs) + @pytest.mark.mutation_fast def test_reaugment_idempotent(self, tmp_path: Any) -> None: graph = _build_graph() store = GraphStore(graph) @@ -546,6 +561,7 @@ def test_reaugment_idempotent(self, tmp_path: Any) -> None: # ── QueryEngine integration ────────────────────────────────────────── +@pytest.mark.mutation_fast @pytest.mark.parametrize("source", ["sarif", "weaudit"]) @pytest.mark.parametrize("replace_existing", [None, False, True]) def test_multiple_finding_imports_apply_replacement_policy( @@ -574,6 +590,7 @@ def test_multiple_finding_imports_apply_replacement_policy( assert set(graph["subgraphs"][severity_subgraph]) == expected +@pytest.mark.mutation_fast @pytest.mark.parametrize("source", ["sarif", "weaudit"]) @pytest.mark.parametrize("replace_existing", [False, True]) @pytest.mark.parametrize("failure", ["missing", "malformed_json", "invalid_record"]) @@ -614,6 +631,7 @@ def test_failed_finding_import_preserves_existing_graph( assert engine.findings() == findings_before +@pytest.mark.mutation_fast @pytest.mark.parametrize("source", ["sarif", "weaudit"]) @pytest.mark.parametrize("root_kind", ["dot", "relative", "absolute"]) @pytest.mark.parametrize("language", ["python", "auto"]) @@ -741,6 +759,7 @@ def test_findings_method(self, tmp_path: Any) -> None: assert "findings" in findings[0] assert findings[0]["findings"][0]["kind"] == "finding" + @pytest.mark.mutation_fast def test_findings_filter_by_kind(self, tmp_path: Any) -> None: graph = _build_graph() engine = QueryEngine.from_graph(graph) diff --git a/tests/test_bash_nested_bindings.py b/tests/test_bash_nested_bindings.py index 5b03d90..2e484a7 100644 --- a/tests/test_bash_nested_bindings.py +++ b/tests/test_bash_nested_bindings.py @@ -24,6 +24,7 @@ def _helpers(tmp_path: Path, source: str) -> tuple[CodeGraph, list[CodeEdge]]: return graph, calls +@pytest.mark.mutation_fast def test_nested_helper_definition_dominates_its_call(tmp_path: Path) -> None: graph, calls = _helpers(tmp_path, "outer() {\n helper() { :; }\n helper\n}\n") call = next(edge for edge in calls if edge.source_id == "nested:outer") @@ -32,6 +33,7 @@ def test_nested_helper_definition_dominates_its_call(tmp_path: Path) -> None: assert call.confidence == EdgeConfidence.INFERRED +@pytest.mark.mutation_fast @pytest.mark.parametrize("alias", ["alias helper=other", "alias ${CMD:-x}=other"]) def test_later_alias_cannot_rewrite_an_already_parsed_function_body( tmp_path: Path, alias: str @@ -41,6 +43,7 @@ def test_later_alias_cannot_rewrite_an_already_parsed_function_body( assert call.target_id == "nested:outer.helper" +@pytest.mark.mutation_fast @pytest.mark.parametrize( "body", [ diff --git a/tests/test_bash_parser.py b/tests/test_bash_parser.py index b8a57cf..5f4485c 100644 --- a/tests/test_bash_parser.py +++ b/tests/test_bash_parser.py @@ -19,6 +19,7 @@ def _file(tmp_path: Path, source: str) -> Path: return path +@pytest.mark.mutation_fast def test_script_functions_substitutions_and_ownership(tmp_path: Path) -> None: path = _file( tmp_path, @@ -36,6 +37,7 @@ def test_script_functions_substitutions_and_ownership(tmp_path: Path) -> None: assert any(e.source_id == "sample: