Files
claude-config/bin/task_bench/bugs/test_rust_bugs.py
T

270 lines
12 KiB
Python

"""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[2]))
from task_bench.bugs.rust_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.bugs.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()