Merge remote-tracking branch 'origin/main' into item-531
CI / tests (pull_request) Has been cancelled
CI / tests (pull_request) Has been cancelled
# Conflicts: # CHANGELOG.md # README.md # docs/reading-cost.md
This commit is contained in:
@@ -108,8 +108,10 @@ def median(column: Column, results: list[Result]) -> float | None:
|
||||
|
||||
|
||||
def row(task: str, side: str, results: list[Result]) -> str:
|
||||
"""A task's row for one side. A `|` in the task's name is escaped, since cargo-mutants names a mutant by its operator, as in
|
||||
`replace || with &&`, and a bare one would end the cell."""
|
||||
passed = f"{sum(result.passed for result in results)}/{len(results)}"
|
||||
return cells([task, side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
|
||||
return cells([task.replace("|", "\\|"), side, passed, *("-" if (found := median(column, results)) is None else number(found) for column in COLUMNS)])
|
||||
|
||||
|
||||
def change(bugs: list[tuple[list[Result], list[Result]]]) -> str:
|
||||
|
||||
+21
-14
@@ -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`. No other language is planted
|
||||
in so far. 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, and
|
||||
`cargo test` without --nocapture. Any other mutant is passed over, so a change to the very lines of a bug is not benched.
|
||||
- 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
|
||||
@@ -28,23 +29,29 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
|
||||
Claude home is new and empty, so the project's own CLAUDE.md, or AGENTS.md, in the copy is all the setup that loads. Its network
|
||||
reaches api.anthropic.com and nothing else. A fix ends after 30 minutes.
|
||||
- Check. The test command runs over the planted tree with each file that is no test as Haiku left it; a fix passes where it exits 0.
|
||||
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder.
|
||||
A test Haiku changed, removed or added doesn't count, and neither does a file under a `testdata` folder. A Rust test that
|
||||
stands in the file of the code it tests is the exception: the bench takes that file whole, so a change to such a test counts.
|
||||
|
||||
--image is the project's development image, such as golang:1.27.4. The bench adds Claude Code to it, as its installer installs it,
|
||||
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, Gremlins' first and
|
||||
cargo-mutants' last, 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 \
|
||||
@@ -140,7 +147,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.
|
||||
@@ -346,11 +353,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"]))
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ 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. cargo-mutants' own name for a mutant holds all of it."""
|
||||
|
||||
path: str
|
||||
line: int
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""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 cargo test prints twice: before the first failed test's section, and before the list of the failed tests' names.
|
||||
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 holds no change, or more than one hunk, 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
|
||||
# cargo-mutants writes no outcomes where it finds no mutant, as in a file that holds only types.
|
||||
outcomes = json.loads(listed.read_bytes())["outcomes"] if (listed := out / "outcomes.json").is_file() else []
|
||||
# The run of the unmutated tree is an outcome too. Its scenario is the text `Baseline`, which holds no mutant, so the summary is
|
||||
# checked first.
|
||||
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
|
||||
# Each line before the first changed one is a line of the tree.
|
||||
first = int(hunks[0]) + 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 has the module's name before its own, 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
|
||||
@@ -85,6 +85,11 @@ def run(task: int, side: str, number: int, passed: bool, input_: int = 100, turn
|
||||
|
||||
|
||||
class TableTest(unittest.TestCase):
|
||||
def test_escapes_a_bar_in_a_tasks_name_so_its_row_keeps_the_headings_cells(self):
|
||||
rows = table([run(1, "base", 1, True, input_=100, turns=10, seconds=60, reads=3)], {1: "src/pick.rs:7:20: replace || with && in keep"}, "bug")
|
||||
self.assertTrue(rows[2].startswith(r"| 1: src/pick.rs:7:20: replace \|\| with && in keep | base | 1/1 |"))
|
||||
self.assertEqual(rows[2].replace(r"\|", "").count("|"), rows[0].count("|"))
|
||||
|
||||
def test_prints_a_row_per_task_and_side_with_the_pass_count_and_each_median_then_all_tasks_and_the_heads_change(self):
|
||||
results = [
|
||||
run(1, "base", 1, True, input_=100, turns=10, seconds=60, reads=3),
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
"""task-bench's Rust planter: which files cargo-mutants mutates, how its diffs become mutants and what cargo test's output tells Haiku.
|
||||
|
||||
PICK's two diffs, ASSERTION and TWO_FAILED are what cargo-mutants 27.1.0 and Rust 1.100.0 wrote for a small project, and OUTCOMES
|
||||
holds the keys the planter reads of that run's outcomes. The other diffs and outputs are made up in the same form."""
|
||||
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
|
||||
}
|
||||
"""
|
||||
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")):
|
||||
with self.subTest(line=line):
|
||||
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")
|
||||
self.assertEqual(task_text(output.replace("tests::adds", "pick::tests::adds")), "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):
|
||||
after_the_list = section("totals", "summing 3 items") + "thread 'main' (7) panicked at src/main.rs:2:5:\nno arguments\n"
|
||||
self.assertIsNone(task_text(after_the_list))
|
||||
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 (({"outcomes": [{"summary": "CaughtMutant"}]}, self.DIFFS), ("no outcomes", self.DIFFS), (self.OUTCOMES, {})):
|
||||
with self.subTest(outcomes=outcomes, diffs=diffs):
|
||||
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)
|
||||
|
||||
def test_finds_no_mutant_where_cargo_mutants_wrote_no_outcomes_as_it_does_where_it_finds_none(self):
|
||||
self.assertEqual(killed_mutants(self.top, ["src/pick.rs"], self.cargo_mutants(None), 3), [])
|
||||
self.assertEqual(list(pathlib.Path(self.top).iterdir()), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -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))
|
||||
@@ -306,10 +306,10 @@ class BenchTest(unittest.TestCase):
|
||||
self.assertEqual(report[0], f"task-bench: base {self.head[:12]}, head {self.head[:12]}. 1 bug, each run 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
|
||||
self.assertEqual(report[4:6], ["| 1: calc.go:5:11 ARITHMETIC_BASE | base | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |", "| 1: calc.go:5:11 ARITHMETIC_BASE | head | 1/1 | 40 | 9000 | 52000 | 800 | 3 | 61.5 | 1 |"])
|
||||
|
||||
def test_fails_where_the_places_name_no_go_or_python_file_of_the_base(self):
|
||||
def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(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):
|
||||
|
||||
Reference in New Issue
Block a user