Plant bugs for task-bench in Rust, from the mutants cargo-mutants kills
CI / tests (pull_request) Successful in 4m35s

This commit is contained in:
2026-11-24 02:13:14 +01:00
parent 6fbfd54821
commit 49d16378e8
9 changed files with 394 additions and 26 deletions
+2 -2
View File
@@ -228,7 +228,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go and Python files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. It passes over a feature whose branch landed by fast-forward. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, Python and Rust files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. It passes over a feature whose branch landed by fast-forward. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
@@ -278,7 +278,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go and Python files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, Python and Rust files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `test_env.py` serves the tests.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
+12 -5
View File
@@ -32,11 +32,10 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git,
return scratch
try:
pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8")
relative = os.path.relpath(scratch, top)
ran = run(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES}
out = cargo_mutants_out(top, scratch, ["--in-diff", os.path.join(os.path.relpath(scratch, top), "branch.diff")], run, jobs)
if isinstance(out, Failure):
return out
outcomes = {outcome: outcome_lines(out / f"{outcome}.txt") for outcome in CARGO_OUTCOMES}
except OSError as failure:
return Failure(f"could not hand cargo-mutants the diff or read its outcomes in {scratch}: {failure}")
finally:
@@ -45,6 +44,14 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git,
return [f"cargo-mutants: {sum(map(len, outcomes.values()))} mutants on changed lines, {len(uncaught)} not caught.", *uncaught]
def cargo_mutants_out(top: str, scratch: str, arguments: list[str], run: Run, jobs: int) -> pathlib.Path | Failure:
"""The `mutants.out` folder that `cargo mutants <arguments>`, which runs in top, writes in scratch, a folder in top."""
ran = run(["cargo", "mutants", *arguments, "--output", os.path.relpath(scratch, top), "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
return pathlib.Path(scratch, "mutants.out")
class Mutant(typing.NamedTuple):
"""A mutant in Gremlins' report, in the order the report prints them."""
+19 -13
View File
@@ -14,13 +14,14 @@ origin's as last fetched, else main or master. Where --base names the head's own
No model judges anything: the bench runs programs, and reads Haiku's own stream.
- Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places`
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, and mutmut 3 over
the Python files, as `mutmut run`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over
the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where,
planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message
from `go test`'s output for a Go file and from pytest's for a Python file, so --test must run the tests of each language the
places name, with that runner: pytest as it prints by default, or with --tb=short. Any other mutant is passed over, so a
change to the very lines of a bug is not benched. Go and Python are the languages so far.
from `go test`'s output for a Go file, from pytest's for a Python file and from `cargo test`'s for a Rust file, so --test must
run the tests of each language the places name, with that runner: pytest as it prints by default, or with --tb=short. Any
other mutant is passed over, so a change to the very lines of a bug is not benched. Go, Python and Rust are the languages so
far.
- Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's
tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p
--strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every
@@ -34,17 +35,22 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at
the copy's top, with no network, so the image must hold what the tests would otherwise download.
--prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs `<prefix> "$@"` with
the tool's command as "$@", such as `gremlins unleash ...` or `mutmut run ...`. Gremlins runs in the copy of the base, and mutmut
in a copy of the folder there that holds its settings; $PWD is the folder the tool runs in. Without --prefix, the bench runs
the `gremlins` or the `mutmut` on the host's PATH. For example, for Go and then for Python:
the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and
cargo-mutants run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; $PWD is the folder
the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut` or the `cargo` on the host's PATH. For example,
for Go, for Python and then for Rust:
docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
sh -c 'shift; exec go run github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 "$@"' sh
uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"
Where the places name files in both languages, the one prefix gets both tools' commands, Gremlins' first, and a tool it
cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins` or `mutmut`:
docker run --rm --memory 16g --memory-swap 16g --user "$(id -u):$(id -g)" -e CARGO_HOME=/tmp/cargo -v "$PWD:$PWD" -w "$PWD" \
rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh
Where the places name files in more than one language, the one prefix gets each tool's command, in the order above, and a tool
it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, `mutmut` or `cargo`, as here for Go
and Python:
sh -c 'case "$1" in
gremlins) shift; exec docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
@@ -136,7 +142,7 @@ not, unless a bench or a gather is using it. So gather a bench before the next o
Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole
number from 1, a --tasks that is none of bugs, features, data-sources and shipped-features, or no token; and where git, docker or a mutation tool
fails, the seats' places don't name any Go or Python file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
fails, the seats' places don't name any Go, Python or Rust file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no
`bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable
file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts.
@@ -342,11 +348,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
"""What plans a bench of bugs: of the mutants the tests kill in the Go and Python files of the tree at base that hold a place
"""What plans a bench of bugs: of the mutants the tests kill in the Go, Python and Rust files of the tree at base that hold a place
in places, those --seed draws first become bugs, until --bugs of them have."""
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
if not files:
return Failure("The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug.")
return Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(base, files, run, CPUS_PER_SLOT)
return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"]))
+2 -1
View File
@@ -6,7 +6,7 @@ import re
import typing
from failure import Failure
from task_bench import go_bugs, python_bugs
from task_bench import go_bugs, python_bugs, rust_bugs
from mutate_changes.changed_lines import is_test
from task_bench.planted_mutant import Mutant
from mutate_changes.tool_process import Run
@@ -29,6 +29,7 @@ class Language(typing.NamedTuple):
LANGUAGES = (
Language("Go", (".go",), go_bugs.killed_mutants, go_bugs.task_text),
Language("Python", (".py",), python_bugs.killed_mutants, python_bugs.task_text),
Language("Rust", (".rs",), rust_bugs.killed_mutants, rust_bugs.task_text),
)
+2 -1
View File
@@ -11,7 +11,8 @@ class Mutant(typing.NamedTuple):
"""A mutant the project's tests killed, as the lines it changes in the tree its tool ran in: the number of the first, from 1,
those lines as the tree has them, and what the mutant has in their place. Where it only adds lines, the number is that of the
line they go in before. name is what the report calls the bug it becomes: the path and line, then what the tool tells the
mutant by, which is Gremlins' column and mutator, or mutmut's name."""
mutant by, which is Gremlins' column and mutator, or mutmut's name. A Rust mutant's name is the one cargo-mutants gives it, which holds
the path and line."""
path: str
line: int
+92
View File
@@ -0,0 +1,92 @@
"""The bugs task-bench plants in Rust: the mutants cargo-mutants reports as caught, each read from the diff it writes, and the message
cargo test prints when a test panics on one."""
import json
import re
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.planted_mutant import Mutant
from mutate_changes.tool_process import remove, Run, scratch_folder
# What cargo-mutants 27.1.0 writes after the code it put in, as in `sum -= /* ~ changed by cargo-mutants ~ */ item;`. A planted
# bug leaves it out, since it would show Haiku the line.
MARK = b" /* ~ changed by cargo-mutants ~ */"
HUNK = re.compile(rb"@@ -(\d+)")
# The heading of what a failed test printed, in cargo test's output: `---- tests::adds stdout ----`.
SECTION = re.compile(r"^---- (\S+) std(?:out|err) ----$")
# The line before a panic's message: `thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:`. An older Rust prints no
# thread id.
PANICKED = re.compile(r"^thread '.*' (?:\(\d+\) )?panicked at .*:$")
# What follows a panic's message: a hint to ask for a backtrace, or the backtrace.
AFTER_MESSAGE = ("note: run with `RUST_BACKTRACE", "stack backtrace:")
# The heading of the list that names the failed tests, after the last test's section.
FAILED_TESTS = "failures:"
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as cargo-mutants finds them there, each under the name
cargo-mutants gives it. One whose diff is not one run of changed lines is left out."""
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
try:
out = in_diff_tools.cargo_mutants_out(top, scratch, [argument for path in files for argument in ("--file", path)], run, jobs)
if isinstance(out, Failure):
return out
outcomes = json.loads((out / "outcomes.json").read_bytes())["outcomes"]
# The run of the unmutated tree is an outcome too, whose scenario is no mutant.
caught = [(mutant, outcome["diff_path"]) for outcome in outcomes if outcome["summary"] == "CaughtMutant" and (mutant := outcome["scenario"]["Mutant"])["file"] in files]
lines = [(mutant, changed((out / diff).read_bytes())) for mutant, diff in caught]
return [Mutant(mutant["file"], found[0], mutant["name"], found[1], found[2]) for mutant, found in lines if found]
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"could not read cargo-mutants' outcomes in {scratch}: {failure}")
finally:
remove(scratch)
def changed(diff: bytes) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes, from the diff cargo-mutants writes for it: the number of the first, from 1, those lines as the
tree has them, and what the mutant has in their place, without MARK. An unchanged line between two changed ones is in both.
None where the diff holds no change, or more than one hunk."""
header, *hunks = HUNK.split(diff)
if len(hunks) != 2:
return None
# A line that starts with a backslash says the file ends without a line end.
body = [line for line in hunks[1].split(b"\n")[1:] if not line.startswith(b"\\")]
at = [index for index, line in enumerate(body) if line[:1] in (b"-", b"+")]
if not at:
return None
first = int(hunks[0]) + sum(not line.startswith(b"+") for line in body[:at[0]])
span = body[at[0]:at[-1] + 1]
was = tuple(line[1:] for line in span if not line.startswith(b"+"))
now = tuple(line[1:].replace(MARK, b"") for line in span if not line.startswith(b"-"))
return first, was, now
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the message of the first panic in a failed test's section of cargo test's output,
without the test's name or the file and line that panicked, so it says what goes wrong and not where.
None where no failed test's section holds a panic with a message, as on a passing run or a build that broke, or where the
message only names the test."""
test, within = "", False
message: list[str] = []
for line in output.splitlines():
heading = SECTION.match(line)
if message and (heading or line == FAILED_TESTS):
break
if heading:
test, within = heading[1], False
elif line == FAILED_TESTS:
test, within = "", False
elif test and not message and PANICKED.match(line):
within = True
elif within and line.startswith(AFTER_MESSAGE):
within = False
elif within:
message.append(line.strip())
# A test in a module is named after it, as `tests::adds`; a message may name the whole or the test alone. A Rust test's own
# name is often a plain word, such as `big`, so a longer identifier that holds it, such as `is_big`, doesn't name the test.
names = [re.compile(rf"(?<!\w){re.escape(name)}(?!\w)") for name in {test, test.rpartition("::")[2]} - {""}]
kept = [text for text in message if text and not any(name.search(text) for name in names)]
return "\n".join(kept) or None
+3 -2
View File
@@ -84,10 +84,11 @@ class LanguagesTest(unittest.TestCase):
class ShippedLanguagesTest(unittest.TestCase):
def test_go_reads_go_tests_output_and_python_pytests(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",))])
def test_each_language_reads_its_own_test_runners_output(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",)), ("Rust", (".rs",))])
self.assertEqual(task_text("calc.go", "--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
self.assertEqual(task_text("calc.py", "==== FAILURES ====\n___ test_pick ___\nE assert 3 == 4\n"), "assert 3 == 4")
self.assertEqual(task_text("calc.rs", "---- picks stdout ----\nthread 'picks' (7) panicked at src/calc.rs:9:5:\ngot 3, want 4\n"), "got 3, want 4")
if __name__ == "__main__":
+260
View File
@@ -0,0 +1,260 @@
"""task-bench's Rust planter: which files cargo-mutants mutates, how its diffs become mutants and what cargo test's output tells Haiku.
The diffs, the outcomes and cargo test's output are what cargo-mutants 27.1.0 and Rust 1.100.0 wrote for a small project."""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.rust_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
PICK = b"""pub fn first(items: &[i32]) -> Option<i32> {
if items.is_empty() {
return None;
}
Some(items[0])
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
}
"""
# A mutant that swaps an operator, and one that replaces a function's body.
OPERATOR_DIFF = b"""--- src/pick.rs
+++ replace += with -= in total
@@ -3,12 +3,12 @@
return None;
}
Some(items[0])
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
- sum += item;
+ sum -= /* ~ changed by cargo-mutants ~ */ item;
}
sum
}
"""
BODY_DIFF = b"""--- src/pick.rs
+++ replace first -> Option<i32> with None
@@ -1,13 +1,10 @@
pub fn first(items: &[i32]) -> Option<i32> {
- if items.is_empty() {
- return None;
- }
- Some(items[0])
+ None /* ~ changed by cargo-mutants ~ */
}
pub fn total(items: &[i32]) -> i32 {
let mut sum = 0;
for item in items {
sum += item;
}
sum
"""
# cargo test's report of a test in the code's own file whose assertion failed.
ASSERTION = """running 2 tests
test tests::adds ... FAILED
test tests::big ... ok
failures:
---- tests::adds stdout ----
thread 'tests::adds' (3058) panicked at src/lib.rs:21:9:
assertion `left == right` failed
left: 0
right: 3
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::adds
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
error: test failed, to rerun pass `-p calc --lib`
"""
# Two failed tests: one that panicked with its own message, and one that unwrapped an error.
TWO_FAILED = """running 3 tests
test first_of_some ... ok
test totals ... FAILED
test unwraps ... FAILED
failures:
---- totals stdout ----
thread 'totals' (5813) panicked at tests/picks.rs:13:9:
total of 1, 2, 3 is -6, want 6
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
---- unwraps stdout ----
thread 'unwraps' (5814) panicked at tests/picks.rs:20:7:
called `Result::unwrap()` on an `Err` value: "bad total"
failures:
totals
unwraps
test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
"""
PASSING = """running 1 test
test totals ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
"""
def section(test: str, *lines: str) -> str:
return "\n".join(["failures:", "", f"---- {test} stdout ----", *lines, "", "", "failures:", f" {test}", ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_an_operator_mutant_changes_without_cargo_mutants_mark(self):
self.assertEqual(changed(OPERATOR_DIFF), (11, (b" sum += item;",), (b" sum -= item;",)))
def test_is_every_line_a_replaced_body_spans(self):
was = (b" if items.is_empty() {", b" return None;", b" }", b" Some(items[0])")
self.assertEqual(changed(BODY_DIFF), (2, was, (b" None",)))
def test_the_tree_with_the_mutant_applied_is_the_code_cargo_mutants_tested_without_its_mark(self):
for diff, line in ((OPERATOR_DIFF, b" sum -= item;"), (BODY_DIFF, b" None")):
line_number, was, now = changed(diff)
planted = mutated(PICK, Mutant("src/pick.rs", line_number, "a name", was, now))
self.assertIn(line, planted.split(b"\n"))
self.assertNotIn(b"cargo-mutants", planted)
def test_keeps_an_unchanged_line_between_two_changed_ones_on_both_sides(self):
diff = b"--- a.rs\n+++ a name\n@@ -4,5 +4,4 @@\n fn f() {\n- a\n b\n- c\n+ d /* ~ changed by cargo-mutants ~ */\n }\n"
self.assertEqual(changed(diff), (5, (b" a", b" b", b" c"), (b" b", b" d")))
def test_a_mutant_that_only_removes_lines_has_no_line_in_their_place(self):
diff = b"--- a.rs\n+++ a name\n@@ -4,3 +4,2 @@\n fn f() {\n- a\n }\n"
self.assertEqual(changed(diff), (5, (b" a",), ()))
def test_skips_the_line_that_says_the_file_ends_without_a_line_end(self):
diff = b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n fn f() {\n-a }\n\\ No newline at end of file\n+b /* ~ changed by cargo-mutants ~ */ }\n\\ No newline at end of file\n"
self.assertEqual(changed(diff), (2, (b"a }",), (b"b }",)))
def test_is_none_for_a_diff_of_no_change_or_of_more_than_one_hunk(self):
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n"))
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n a\n b\n"))
self.assertIsNone(changed(b"--- a.rs\n+++ a name\n@@ -1,2 +1,2 @@\n a\n-b\n+c\n@@ -9,2 +9,2 @@\n a\n-b\n+c\n"))
class TaskTextTest(unittest.TestCase):
def test_is_the_failed_tests_panic_message_without_the_tests_name_file_or_line(self):
self.assertEqual(task_text(ASSERTION), "assertion `left == right` failed\nleft: 0\nright: 3")
def test_takes_the_first_failed_test_that_has_a_message(self):
self.assertEqual(task_text(TWO_FAILED), "total of 1, 2, 3 is -6, want 6")
self.assertEqual(task_text(TWO_FAILED.replace("total of 1, 2, 3 is -6, want 6\n", "")), 'called `Result::unwrap()` on an `Err` value: "bad total"')
def test_a_message_ends_at_the_next_tests_section_where_no_note_follows_it(self):
self.assertEqual(task_text(TWO_FAILED.replace("note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace\n", "")), "total of 1, 2, 3 is -6, want 6")
def test_takes_the_panic_not_what_the_test_printed_before_it(self):
output = section("totals", "summing 3 items", "", "thread 'totals' (7) panicked at tests/picks.rs:13:9:", "got -6, want 6")
self.assertEqual(task_text(output), "got -6, want 6")
def test_tells_a_panic_in_the_code_under_test(self):
output = section("first_of_none", "", "thread 'first_of_none' (7) panicked at src/pick.rs:5:10:", "index out of bounds: the len is 0 but the index is 0")
self.assertEqual(task_text(output), "index out of bounds: the len is 0 but the index is 0")
def test_leaves_out_each_line_that_names_the_test(self):
output = section("tests::adds", "", "thread 'tests::adds' (7) panicked at src/lib.rs:21:9:", "adds: got 0", "want 3")
self.assertEqual(task_text(output), "want 3")
self.assertEqual(task_text(output.replace("adds: got 0", "tests::adds broke")), "want 3")
def test_a_message_may_hold_the_tests_name_inside_a_longer_identifier(self):
output = section("tests::big", "", "thread 'tests::big' (7) panicked at src/lib.rs:27:9:", "assertion failed: !is_big(10)")
self.assertEqual(task_text(output), "assertion failed: !is_big(10)")
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(section("totals", "", "thread 'totals' (7) panicked at tests/picks.rs:13:9:", "totals failed")))
def test_is_none_where_no_test_panicked_as_on_a_passing_run_or_a_build_that_broke(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("error[E0308]: mismatched types\n --> src/lib.rs:4:5\nerror: could not compile `calc` (lib) due to 1 previous error\n"))
self.assertIsNone(task_text(""))
def test_a_panic_outside_a_failed_tests_section_is_no_message(self):
self.assertIsNone(task_text("thread 'main' (7) panicked at src/main.rs:2:5:\nno arguments\n"))
class KilledMutantsTest(unittest.TestCase):
OUTCOMES = {"outcomes": [
{"scenario": "Baseline", "summary": "Success"},
{"scenario": {"Mutant": {"name": "src/pick.rs:11:13: replace += with -= in total", "file": "src/pick.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/operator.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:2:5: replace first -> Option<i32> with None", "file": "src/pick.rs"}}, "summary": "MissedMutant", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:9:5: replace total -> i32 with 0", "file": "src/pick.rs"}}, "summary": "Timeout", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/lib.rs:2:5: replace first -> Option<i32> with None", "file": "src/lib.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/body.diff"},
{"scenario": {"Mutant": {"name": "src/pick.rs:1:1: a mutant whose diff holds no change", "file": "src/pick.rs"}}, "summary": "CaughtMutant", "diff_path": "diff/empty.diff"},
]}
DIFFS = {"operator.diff": OPERATOR_DIFF, "body.diff": BODY_DIFF, "empty.diff": b"--- src/pick.rs\n+++ a name\n"}
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = folder.name
self.ran: list[tuple[list[str], str]] = []
def cargo_mutants(self, outcomes: object, code: int = 0, diffs: dict[str, bytes] = DIFFS):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
out = pathlib.Path(cwd, argv[argv.index("--output") + 1], "mutants.out")
(out / "diff").mkdir(parents=True)
for name, diff in diffs.items():
(out / "diff" / name).write_bytes(diff)
if outcomes is not None:
(out / "outcomes.json").write_text(json.dumps(outcomes))
return Ran(code, "cargo-mutants said so")
return run
def test_runs_cargo_mutants_at_the_top_over_the_files_asked_for(self):
killed_mutants(self.top, ["src/pick.rs", "src/lib.rs"], self.cargo_mutants({"outcomes": []}), 3)
argv, cwd = self.ran[0]
self.assertEqual(cwd, self.top)
self.assertEqual(argv[:6], ["cargo", "mutants", "--file", "src/pick.rs", "--file", "src/lib.rs"])
self.assertEqual((argv[6], argv[8:]), ("--output", ["--jobs", "3"]))
def test_keeps_the_caught_mutants_of_the_files_asked_for_as_the_lines_each_changes_under_cargo_mutants_name(self):
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES, code=2), 3)
self.assertEqual(found, [Mutant("src/pick.rs", 11, "src/pick.rs:11:13: replace += with -= in total", (b" sum += item;",), (b" sum -= item;",))])
def test_removes_its_scratch_folder(self):
killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES), 3)
self.assertEqual(list(pathlib.Path(self.top).iterdir()), [])
def test_a_cargo_mutants_that_does_not_finish_is_a_failure_with_what_it_printed(self):
# 4 is its exit code where the tests fail before any mutant.
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(self.OUTCOMES, code=4), 3)
self.assertIsInstance(found, Failure)
self.assertIn("cargo-mutants said so", found.reason)
def test_outcomes_or_a_diff_that_cannot_be_read_are_a_failure_that_names_the_folder(self):
for outcomes, diffs in ((None, self.DIFFS), ({"outcomes": [{"summary": "CaughtMutant"}]}, self.DIFFS), ("no outcomes", self.DIFFS), (self.OUTCOMES, {})):
found = killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(outcomes, diffs=diffs), 3)
self.assertIsInstance(found, Failure)
self.assertIn(f"could not read cargo-mutants' outcomes in {self.top}", found.reason)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -236,7 +236,7 @@ class BenchTest(unittest.TestCase):
def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug.\n")):
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.\n")):
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors:
self.assertEqual(main.main(argv, self.env, lambda home: places), 1)
self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said))
@@ -309,7 +309,7 @@ class BenchTest(unittest.TestCase):
def test_fails_where_the_places_name_no_go_or_python_file_of_the_base(self):
with contextlib.redirect_stderr(io.StringIO()):
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
self.assertEqual(found, Failure("The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug."))
self.assertEqual(found, Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug."))
self.assertFalse(self.log.exists())
def test_fails_where_the_tests_fail_without_a_bug(self):