Answer architecture round 1: 0 🔴, 6 🟡 (0 misread); count a release review only where it names the next release, split task_bench into bugs, features and figures, group README's packages
CI / tests (pull_request) Successful in 4m55s

This commit is contained in:
2026-11-27 11:23:08 +01:00
parent d1b01c76c8
commit b563a597f1
55 changed files with 293 additions and 198 deletions
View File
+103
View File
@@ -0,0 +1,103 @@
"""The bugs task-bench plants in Go: Gremlins' killed mutants, re-applied from its report, and the message go test prints when a test
fails on one."""
import os
import pathlib
import re
from failure import Failure
from mutate_changes import in_diff_tools
from mutate_changes.changed_lines import is_test
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Run
# What each of Gremlins v0.6.0's mutators writes in place of a token: `tokenMutations` in its internal/engine/mappings.go, under the
# names its report gives the mutators, from internal/mutator/mutator.go.
MUTATIONS: dict[str, dict[bytes, bytes]] = {
"ARITHMETIC_BASE": {b"+": b"-", b"*": b"/", b"/": b"*", b"%": b"*", b"-": b"+"},
"CONDITIONALS_BOUNDARY": {b">=": b">", b">": b">=", b"<=": b"<", b"<": b"<="},
"CONDITIONALS_NEGATION": {b"==": b"!=", b">=": b"<", b">": b"<=", b"<=": b">", b"<": b">=", b"!=": b"=="},
"INCREMENT_DECREMENT": {b"--": b"++", b"++": b"--"},
"INVERT_ASSIGNMENTS": {b"+=": b"-=", b"*=": b"/=", b"/=": b"*=", b"-=": b"+="},
"INVERT_BITWISE": {b"&": b"|", b"|": b"&", b"^": b"&", b"&^": b"&", b"<<": b">>", b">>": b"<<"},
"INVERT_BWASSIGN": {b"&=": b"|=", b"|=": b"&=", b"^=": b"&=", b"&^=": b"&=", b"<<=": b">>=", b">>=": b"<<="},
"INVERT_LOGICAL": {b"&&": b"||", b"||": b"&&"},
"INVERT_LOOPCTRL": {b"break": b"continue", b"continue": b"break"},
"INVERT_NEGATIVES": {b"-": b"+"},
"REMOVE_SELF_ASSIGNMENTS": dict.fromkeys((b"+=", b"&=", b"&^=", b"*=", b"|=", b"/=", b"%=", b"<<=", b">>=", b"-=", b"^="), b"="),
}
# What a test printed, as go test shows it: ` pick_test.go:42: got 3, want 4`. A failed assertion and a log line look the same.
PRINTED = re.compile(r"^( *)\S*_test\.go:\d+:(.*)$")
# The lines that say whose output follows: `=== RUN TestPick` with -v, and `--- FAIL: TestPick (0.00s)` with and without it.
TEST_MARK = re.compile(r"^( *)(?:=== (?:RUN|CONT|NAME)|--- (?:FAIL|PASS|SKIP):)\s+(\S+)")
FAILED_TEST = re.compile(r"^\s*--- FAIL: (\S+)", re.MULTILINE)
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 Gremlins finds them there. One whose line and column hold
no token its mutator changes is left out.
Gremlins takes no list of files to mutate, only patterns to leave out, so it gets one for each other Go file of the tree."""
others = sorted(path for path in go_files(top) if path not in files)
found = in_diff_tools.gremlins_mutants(top, [argument for path in others for argument in ("--exclude-files", f"^{re.escape(path)}$")], run, jobs)
if isinstance(found, Failure):
return found
killed = [mutant for mutant in found if mutant.status == "KILLED" and mutant.path in files]
try:
lines = {path: pathlib.Path(top, path).read_bytes().split(b"\n") for path in {mutant.path for mutant in killed}}
except OSError as failure:
return Failure(f"could not read the files Gremlins mutated in {top}: {failure}")
return [mutant for reported in killed if (mutant := reapplied(reported, lines[reported.path]))]
def go_files(top: str) -> list[str]:
"""Each Go file under top that Gremlins would mutate, by its path from top."""
paths = (os.path.relpath(os.path.join(folder, name), top) for folder, _, names in os.walk(top) for name in names)
return [path for path in paths if path.endswith(".go") and not is_test(path)]
def reapplied(reported: in_diff_tools.Mutant, lines: list[bytes]) -> Mutant | None:
"""The mutant Gremlins reported, as the line it changes; `lines` are its file's. Gremlins names the mutator and where the token
it changed starts: a line, and a column in bytes, both from 1. None where no token the mutator changes starts there."""
if not (1 <= reported.line <= len(lines) and reported.column >= 1):
return None
line = lines[reported.line - 1]
rest = line[reported.column - 1:]
# The longest token first: `>=` holds `>`, and Gremlins names the mutant by the whole token.
token = max((token for token in MUTATIONS.get(reported.mutator, {}) if rest.startswith(token)), key=len, default=None)
if token is None:
return None
now = line[:reported.column - 1] + MUTATIONS[reported.mutator][token] + rest[len(token):]
return Mutant(reported.path, reported.line, f"{reported.path}:{reported.line}:{reported.column} {reported.mutator}", (line,), (now,))
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the failing assertion's message in go test's output, without the test's name, file or
line, so it says what goes wrong and not where. That is the last message of the first failed test that printed one, since a
test logs before it asserts. A test with a failed subtest is left out, since it fails with the subtest.
None where no failed test printed a message, as on a panic, a build that broke or a passing run, or where the message only
names the test."""
lines = output.splitlines()
failed = set(FAILED_TEST.findall(output))
# A subtest is named `TestPick/empty_input`; a message may name the whole or the test it belongs to.
tests = {part for name in failed for part in (name, name.partition("/")[0])}
marks: list[tuple[int, str]] = []
last: dict[str, tuple[int, re.Match[str]]] = {}
for index, line in enumerate(lines):
if mark := TEST_MARK.match(line):
marks.append((len(mark[1]), mark[2]))
elif printed := PRINTED.match(line):
# A test's output is indented deeper than its mark, so a line after a subtest's may be its parent's.
test = next((name for indent, name in reversed(marks) if indent < len(printed[1])), None)
if test is not None and test in failed and not any(other.startswith(f"{test}/") for other in failed):
last[test] = index, printed
if not last:
return None
index, found = next(iter(last.values()))
indent = len(found[1])
# A message's later lines are indented deeper than its first.
later = lines[index + 1:]
ends = next((at for at, text in enumerate(later) if len(text) - len(text.lstrip(" ")) <= indent), len(later))
message = [text.strip() for text in (found[2], *later[:ends])]
kept = [text for text in message if text and "_test.go" not in text and not any(name in text for name in tests)]
return "\n".join(kept) or None
+104
View File
@@ -0,0 +1,104 @@
"""The bugs task-bench plants in PHP: Infection's killed mutants, each read from the two sources in its JSON log, and the message
PHPUnit prints when a test fails on one."""
import json
import pathlib
import re
from mutate_changes.tool_process import failed, remove, Run
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.bugs.planted_mutant import Mutant
from task_bench.bugs.scratch_copy import scratch_copy
# Where Infection writes its JSON log, from the copy's top.
LOG = "infection-log.json"
# The heading of PHPUnit's list of the tests that failed, or of those that threw: `There were 3 failures:`.
LISTED = re.compile(r"^There (?:was|were) \d+ (?:error|failure)s?:$")
# The heading of another list PHPUnit prints in the same form: `There was 1 risky test:`, `1 test triggered 1 deprecation:`.
OTHER_LIST = re.compile(r"^(?:There (?:was|were) \d+ |\d+ tests? triggered \d+ ).+:$")
# A listed test, by its number in the list: `1) Probe\Tests\PickTest::testNamesOne`, or with ` with data set #0 (1, 'one')` after it.
TEST = re.compile(r"^\d+\) (\S+)")
# What ends a listed test's message: the file and line that failed, as `/w/tests/PickTest.php:12`, the line between the two
# lists, or the summary's heading.
AFTER_MESSAGE = re.compile(r"^(?:\S.*\.php:\d+|--|ERRORS!|FAILURES!)$")
TEST_FILE = re.compile(r"Test\.php\b")
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 Infection finds them in a copy of that tree.
Infection runs at the copy's top, with the Infection config there. It ends without an error whatever score that config
asks for, since the files' score is not the project's."""
copied = scratch_copy(top)
if isinstance(copied, Failure):
return copied
scratch, copy = copied
try:
ran = run([in_diff_tools.INFECTION, f"--filter={','.join(files)}", f"--threads={jobs}", "--no-progress", "--min-msi=0", "--min-covered-msi=0", f"--logger-json={LOG}"], copy)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else failed("Infection", ran)
killed = [logged["mutator"] for logged in json.loads(pathlib.Path(copy, LOG).read_bytes())["killed"]]
return [mutant for mutator in killed if (mutant := planted(mutator, files))]
except (OSError, ValueError, KeyError, TypeError, AttributeError) as failure:
return Failure(f"could not read Infection's log, {LOG} in {copy}: {failure}")
finally:
remove(scratch)
def planted(mutator: dict, files: list[str]) -> Mutant | None:
"""A mutant of Infection's log as the lines it changes, or None where it is in none of `files` or doesn't change any line.
The log names a file by its whole path where Infection ran. That path ends with the file's path from the top, and where it
ends with more than one of `files`, the longest is the file."""
logged = mutator["originalFilePath"]
path = max((path for path in files if logged == path or logged.endswith(f"/{path}")), key=len, default=None)
if path is None:
return None
found = changed(mutator["originalSourceCode"], mutator["mutatedSourceCode"])
return Mutant(path, found[0], f"{path}:{mutator['originalStartLine']} {mutator['mutatorName']}", found[1], found[2]) if found else None
def changed(original: str, mutated: str) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes, from the file's source and the mutant's, both of which Infection 0.35.12 logs: the number of
the first line that differs, from 1, the file's lines from there to the last that differs, and what the mutant has in their
place. An unchanged line between two changed ones is in both. None where the two sources are the same."""
was, now = original.split("\n"), mutated.split("\n")
if was == now:
return None
shorter = min(len(was), len(now))
first = next((index for index in range(shorter) if was[index] != now[index]), shorter)
after = next((count for count in range(shorter - first) if was[-1 - count] != now[-1 - count]), shorter - first)
return first + 1, tuple(line.encode() for line in was[first:len(was) - after]), tuple(line.encode() for line in now[first:len(now) - after])
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the message of the first test that has a message in PHPUnit's list of the tests that
threw or failed, without the test's name, class or file, so it says what goes wrong and not which test shows it. A test in
another of PHPUnit's lists, such as the risky tests, did not fail.
None where PHPUnit lists no such test, as on a passing run, a file that fails to parse or a run with --testdox, or where each
message only names its test."""
messages: list[tuple[str, list[str]]] = []
listing = within = False
for line in output.splitlines():
if LISTED.match(line):
listing, within = True, False
elif OTHER_LIST.match(line):
listing = within = False
elif listing and (test := TEST.match(line)):
messages.append((test[1], []))
within = True
elif AFTER_MESSAGE.match(line):
within = False
elif within:
messages[-1][1].append(line)
kept = (kept_lines(test, message) for test, message in messages)
return next(("\n".join(lines) for lines in kept if lines), None)
def kept_lines(test: str, message: list[str]) -> list[str]:
"""A message's lines, without the empty ones and those that name the test: the whole of `Probe\\Tests\\PickTest::testNamesOne`,
its class with or without the namespace, its method, or a test's file."""
of_class, _, method = test.partition("::")
names = {test, of_class, of_class.rpartition("\\")[2], method} - {""}
return [text for text in message if text and not TEST_FILE.search(text) and not any(name in text for name in names)]
+71
View File
@@ -0,0 +1,71 @@
"""Pick the bugs task-bench plants: the mutants the tests kill in the files that hold the places the comprehension seats found
hard, each with the failing test's message that tells Haiku what goes wrong. Each language has a module that runs its mutation
tool and reads its test runner's output."""
import random
import re
import typing
from failure import Failure
from task_bench.bugs import go_bugs, php_bugs, python_bugs, rust_bugs, typescript_bugs
from mutate_changes.changed_lines import is_test, STRYKER
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Run
# A place as `larv-review places` prints it: `<path>:<line>` in backticks.
PLACE = re.compile(r"`([^`\s:]+):\d+`")
class Language(typing.NamedTuple):
"""A language the bench plants bugs in, by its files' suffixes. killed takes a tree's top, the files to mutate there, what
runs the mutation tool and how many tests it may run at once, and returns the mutants the tree's tests kill. told takes the
test command's output over a planted bug, and returns the failing test's message, or None where it printed none."""
name: str
suffixes: tuple[str, ...]
killed: typing.Callable[[str, list[str], Run, int], list[Mutant] | Failure]
told: typing.Callable[[str], str | None]
LANGUAGES = (
Language("Go", (".go",), go_bugs.killed_mutants, go_bugs.task_text),
Language("PHP", (".php",), php_bugs.killed_mutants, php_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),
# Stryker mutates JavaScript as it does TypeScript, and `node --test` reports both alike.
Language("TypeScript", STRYKER, typescript_bugs.killed_mutants, typescript_bugs.task_text),
)
def language_of(path: str, languages: tuple[Language, ...] = LANGUAGES) -> Language | None:
return next((language for language in languages if path.endswith(language.suffixes)), None)
def place_files(places: str) -> list[str]:
"""The files that hold a place in what `larv-review places` prints and are in a language of LANGUAGES, test files left out, in
the order of their paths."""
return sorted({path for path in PLACE.findall(places) if language_of(path) and not is_test(path)})
def killed_mutants(top: str, files: list[str], run: Run, jobs: int, languages: tuple[Language, ...] = LANGUAGES) -> list[Mutant] | Failure:
"""The mutants in `files`, which place_files named, that the tests of the tree at top kill: each language's tool runs over
the files in that language."""
killed: list[Mutant] = []
for language in languages:
own = [path for path in files if language_of(path, languages) is language]
found = language.killed(top, own, run, jobs) if own else []
if isinstance(found, Failure):
return found
killed += found
return killed
def drawn(mutants: list[Mutant], seed: int) -> list[Mutant]:
"""The mutants in the order the seed draws them, whatever order the tools listed them in."""
return random.Random(seed).sample(sorted(set(mutants)), len(set(mutants)))
def task_text(path: str, output: str, languages: tuple[Language, ...] = LANGUAGES) -> str | None:
"""What Haiku is told of a bug planted in the file at path, one place_files named. output is what the test command printed;
the file's language picks the failing test's message out of it. None where it finds none."""
language = language_of(path, languages)
return language.told(output) if language else None
+76
View File
@@ -0,0 +1,76 @@
"""A mutant task-bench plants as a bug, and how it is re-applied at the base and at the head: as the same change to the same lines."""
import re
import typing
from task_bench.figures.figures import Side
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
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' or Stryker's column and mutator, Infection's mutator, or mutmut's name. cargo-mutants' own name for a mutant
holds all of it."""
path: str
line: int
name: str
was: tuple[bytes, ...]
now: tuple[bytes, ...]
def mutated(source: bytes, mutant: Mutant) -> bytes | None:
"""A file's source with the mutant applied, or None where the lines the mutant changes don't stand at the mutant's line.
A mutant's lines hold no `\\r` where its tool read the file as text, as mutmut does, and hold it where the tool split the bytes on
`\\n`, as Gremlins' planter does. Both match a file's lines, and a new line without `\\r` gets the line end of the file's first line."""
lines = source.split(b"\n")
first = mutant.line - 1
end = first + len(mutant.was)
if not 0 <= first <= len(lines) or tuple(line.removesuffix(b"\r") for line in lines[first:end]) != tuple(line.removesuffix(b"\r") for line in mutant.was):
return None
line_end = b"\r" if lines[0].endswith(b"\r") else b""
new = [line if line.endswith(b"\r") else line + line_end for line in mutant.now]
# Where the mutant's lines end the file, the last of them has no line end.
if new and end >= len(lines):
new[-1] = mutant.now[-1]
lines[first:end] = new
return b"\n".join(lines)
def bug_at_sides(mutant: Mutant, diff: str, sources: dict[Side, bytes | None]) -> dict[Side, bytes] | None:
"""The file of mutant with the bug in it, at the base and at the head. None where the mutant doesn't become a bug at one side
or the other.
sources holds the file at each side, None where the side lacks it; diff is the file's diff from base to head.
The bug is the same change to the same lines at both sides, so only the code around it differs between them."""
at_head = line_at_head(diff, mutant.line)
if at_head is None:
return None
bugs: dict[Side, bytes] = {}
placings: tuple[tuple[Side, Mutant], ...] = (("base", mutant), ("head", mutant._replace(line=at_head)))
for side, placed in placings:
changed = None if (source := sources[side]) is None else mutated(source, placed)
if changed is None:
return None
bugs[side] = changed
return bugs
def line_at_head(diff: str, line: int) -> int | None:
"""The number at the head of a file's line `line` at the base, or None where the head changed or removed that line.
diff is `git diff -U0 <base> <head> -- <file>`, so each hunk holds changed lines only."""
moved = 0
for old_start, old_count, new_start, new_count in ((int(a), int(b or 1), int(c), int(d or 1)) for a, b, c, d in HUNK.findall(diff)):
# A hunk that only adds lines names the line it adds them after. One that only removes lines names the line the gap follows.
old_end = old_start + old_count if old_count else old_start + 1
new_end = new_start + new_count if new_count else new_start + 1
if old_count and old_start <= line < old_end:
return None
if line >= old_end:
moved = new_end - old_end
return line + moved
+59
View File
@@ -0,0 +1,59 @@
"""The bugs task-bench plants in Python: mutmut's killed mutants, re-applied from the copy of each file it writes, and the message
pytest prints when a test fails on one."""
import re
from failure import Failure
from mutate_changes.mutmut_tool import killed_by_mutmut
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Run
# pytest's report of the failed tests, in its default form or with --tb=short: under this heading, a section per test.
FAILURES = re.compile(r"^=+ FAILURES =+$", re.MULTILINE)
# A section's heading, such as `_____ test_pick _____` or `_____ PickTest.test_empty _____`. A traceback's `_ _ _ _` between
# two frames is none.
SECTION = re.compile(r"^_+ (?!_)(.+?) _+$")
# The heading of what follows the failed tests, such as `===== short test summary info =====`.
NEXT_PART = re.compile(r"^=+ .+ =+$")
# A line of the error a test failed with: `E assert 3 == 4`, and `E + where 3 = pick([])` below it.
ERROR = re.compile(r"^E(?: (.*)|\s*)$")
# The heading of what a failed test printed, such as `----- Captured stdout call -----`, which may hold a line that looks like an error's.
CAPTURED = re.compile(r"^-+ Captured .+ -+$")
TEST_FILE = re.compile(r"\btest_\w*\.py|\w+_test\.py|\bconftest\.py")
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 mutmut finds them there."""
killed = killed_by_mutmut(top, files, run, jobs)
if isinstance(killed, Failure):
return killed
return [Mutant(path, change.line, f"{path}:{change.line} {name.rpartition('.')[2]}", encoded(change.was), encoded(change.now)) for path, name, change in killed]
def encoded(lines: tuple[str, ...]) -> tuple[bytes, ...]:
return tuple(line.encode() for line in lines)
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the error of the first failed test that has one in pytest's output, without the test's
name or file, so it says what goes wrong and not which test shows it. None where pytest reports no failed test with an
error, as on a passing run, a file that fails to import or a run with --tb=no, or where the error only names the test."""
failures = FAILURES.split(output, maxsplit=1)
if len(failures) < 2:
return None
test, captured = "", False
error: list[str] = []
for line in failures[1].splitlines():
heading = SECTION.match(line)
if NEXT_PART.match(line) or heading and error:
break
if heading:
test, captured = heading[1], False
elif CAPTURED.match(line):
captured = True
elif test and not captured and (said := ERROR.match(line)):
error.append((said[1] or "").strip())
# A heading names a method after its class, and a parametrized test or a subtest before its `[case]` or ` (case)`.
whole = re.split(r"[\s\[(]", test)[0]
names = {whole, *whole.split(".")} - {""}
kept = [text for text in error if text and not TEST_FILE.search(text) and not any(name in text for name in names)]
return "\n".join(kept) or None
+95
View File
@@ -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.bugs.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
+99
View File
@@ -0,0 +1,99 @@
"""The `#[cfg(test)]` modules of a Rust file, which stand in the file of the code they test. Here are where each is, and a file with
the modules of another file put in place of its own. A file is bytes: a Rust file is UTF-8, and a module is found by ASCII text alone."""
import re
# What the scan steps over or stops at. A string, a char and a comment may hold a brace.
SCAN = re.compile(
rb"""//[^\n]*"""
rb"""|/\*"""
rb"""|(?<![A-Za-z0-9_])b?r(?P<hashes>\#*)\""""
rb"""|\""""
rb"""|'(?:\\(?:u\{[0-9a-fA-F_]+\}|x[0-9a-fA-F]{2}|.)|[^\\'\n])'"""
rb"""|[{}]"""
rb"""|\#\[cfg\(test\)\]""",
re.DOTALL,
)
STRING_BODY = re.compile(rb'(?:[^"\\]|\\.)*"', re.DOTALL)
COMMENT_EDGE = re.compile(rb"/\*|\*/")
# What follows the attribute that starts an inline module: any other attributes, an optional visibility, then `mod name {`.
MODULE = re.compile(rb"\s*(?:#\[[^\]]*\]\s*)*(?:pub(?:\([^)]*\))?\s+)?mod\s+(?P<name>\w+)\s*\{")
def tells_apart(path: str, source: bytes) -> bool:
"""Whether source, the file at path, is no Rust file, or holds test modules that `modules` can tell apart."""
return not path.endswith(".rs") or modules(source) is not None
def modules(source: bytes) -> dict[bytes, tuple[int, int]] | None:
"""Each inline `#[cfg(test)] mod name { ... }` of source by its name, with the offsets of its first byte, the attribute's, and of the
byte after its closing brace. A module inside a test module and a `#[cfg(test)]` on anything but an inline module are not listed.
None where the modules cannot be told apart: two share a name, or a brace, string or comment is never closed."""
found: dict[bytes, tuple[int, int]] = {}
depth = 0
# The module being read: its name, the offset of its attribute and the depth outside it.
inside: tuple[bytes, int, int] | None = None
position: int | None = 0
while position is not None and (match := SCAN.search(source, position)):
token, position = match.group(), match.end()
if token == b"/*":
position = after_comment(source, position)
elif token == b'"':
position = after_string(source, position)
elif match.group("hashes") is not None:
position = after_raw_string(source, position, match.group("hashes"))
elif token == b"{":
depth += 1
elif token == b"}":
depth -= 1
if inside and depth == inside[2]:
if inside[0] in found:
return None
found[inside[0]], inside = (inside[1], position), None
elif token.startswith(b"#[") and inside is None and (module := MODULE.match(source, position)):
inside, position = (module.group("name"), match.start(), depth), module.end()
depth += 1
return found if position is not None and depth == 0 and inside is None else None
def after_comment(source: bytes, position: int) -> int | None:
"""The offset after the block comment whose `/*` ends at position, None where it is never closed. Block comments nest in Rust."""
level = 1
while level and (match := COMMENT_EDGE.search(source, position)):
level += 1 if match.group() == b"/*" else -1
position = match.end()
return position if level == 0 else None
def after_string(source: bytes, position: int) -> int | None:
"""The offset after the string whose opening quote ends at position, None where it is never closed. A backslash escapes the next byte."""
closed = STRING_BODY.match(source, position)
return closed.end() if closed else None
def after_raw_string(source: bytes, position: int, hashes: bytes) -> int | None:
"""The offset after the raw string, `r` or `br` then hashes and a quote, whose opening ends at position, None where it is never closed.
It has no escapes."""
closed = re.compile(b'"' + hashes).search(source, position)
return closed.end() if closed else None
def with_tests_of(planted: bytes, copy: bytes) -> bytes:
"""copy with each of its test modules replaced by the one of that name in planted, and each that planted lacks left out. So a test a
fix changed, removed or added doesn't count.
Where planted's modules cannot be told apart, or planted has none and copy's cannot be told apart, copy is returned as it is. Where
planted has some and copy's cannot be told apart, or copy lacks one of planted's, planted is returned: Haiku's file has no module
to put them in."""
before, after = modules(planted), modules(copy)
# Haiku's file stands where planted's modules can't be told apart. The bench never plants a bug in such a file, and a guess at
# which module is which could swap one test for another. Haiku's file is also what the check took before the bench put back
# planted test modules, so a fix that passed then still passes.
if before is None or (after is None and not before):
return copy
if after is None or before.keys() - after.keys():
return planted
text, last = b"", 0
for (start, end), name in sorted((span, name) for name, span in after.items()):
text += copy[last:start] + (planted[before[name][0]:before[name][1]] if name in before else b"")
last = end
return text + copy[last:]
+24
View File
@@ -0,0 +1,24 @@
"""A copy of a tree for a mutation tool to run in, so that what the tool writes there goes with the copy."""
import os
import shutil
from failure import Failure
from mutate_changes.tool_process import remove, scratch_folder
def scratch_copy(top: str) -> tuple[str, str] | Failure:
"""A new scratch folder in top, and in it a copy of top's other entries, links kept as links: the two folders' paths. The
caller removes the scratch folder.
A mutation tool leaves files where it runs: its cache, and each log the project's config asks for, which tells where every
mutant is. A bug's tree is a copy of top, so the tool runs in this copy and top stays as it was."""
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
copy = os.path.join(scratch, "copy")
try:
shutil.copytree(top, copy, symlinks=True, ignore=shutil.ignore_patterns(os.path.basename(scratch)))
except OSError as failure:
remove(scratch)
return Failure(f"could not copy {top} into {scratch}: {failure}")
return scratch, copy
+180
View File
@@ -0,0 +1,180 @@
"""task-bench's Go planter: which files Gremlins mutates, how its mutants are re-applied and what go test's output tells Haiku."""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.bugs.go_bugs import go_files, killed_mutants, reapplied, task_text
from mutate_changes import in_diff_tools
from task_bench.bugs.planted_mutant import Mutant
from mutate_changes.tool_process import Ran
# go test's report of an assertion that failed in a subtest, then of one whose message runs over two lines.
GO_FAILURE = """ok \texample.com/calc/cli\t0.004s
--- FAIL: TestPick (0.00s)
--- FAIL: TestPick/empty_input (0.00s)
pick_test.go:42: Pick() = 3,
want 4
pick_test.go:50: got 1 row, want 2
FAIL
FAIL\texample.com/calc/render\t0.012s
FAIL
"""
# testify prints the test's file and name inside the message.
TESTIFY_FAILURE = """--- FAIL: TestTotal (0.00s)
total_test.go:12:
\tError Trace:\t/work/total_test.go:12
\tError: \tNot equal:
\t \texpected: 1
\t \tactual : 2
\tTest: \tTestTotal
FAIL
"""
PANIC = """--- FAIL: TestPick (0.00s)
panic: runtime error: index out of range [3] with length 3 [recovered]
FAIL\texample.com/calc/render\t0.012s
"""
class ReappliedTest(unittest.TestCase):
SOURCE = b"package calc\n\nfunc f(a, b int) int {\n\tif a >= b {\n\t\treturn a - b\n\t}\n\tn -= 1\n\treturn a\n}\n"
def planted(self, line: int, column: int, mutator: str, source: bytes = SOURCE) -> str | None:
found = reapplied(in_diff_tools.Mutant("calc.go", line, column, "KILLED", mutator), source.split(b"\n"))
return None if found is None else b"\n".join(found.now).decode()
def test_swaps_the_token_at_the_line_and_column_as_gremlins_mutator_does(self):
self.assertEqual(self.planted(4, 7, "CONDITIONALS_NEGATION"), "\tif a < b {")
self.assertEqual(self.planted(4, 7, "CONDITIONALS_BOUNDARY"), "\tif a > b {")
self.assertEqual(self.planted(5, 12, "ARITHMETIC_BASE"), "\t\treturn a + b")
self.assertEqual(self.planted(7, 4, "INVERT_ASSIGNMENTS"), "\tn += 1")
self.assertEqual(self.planted(7, 4, "REMOVE_SELF_ASSIGNMENTS"), "\tn = 1")
def test_names_the_mutant_by_its_place_and_mutator_and_holds_the_line_it_changes(self):
found = reapplied(in_diff_tools.Mutant("calc.go", 5, 12, "KILLED", "ARITHMETIC_BASE"), self.SOURCE.split(b"\n"))
self.assertEqual(found, Mutant("calc.go", 5, "calc.go:5:12 ARITHMETIC_BASE", (b"\t\treturn a - b",), (b"\t\treturn a + b",)))
def test_the_first_column_is_1(self):
self.assertEqual(self.planted(1, 1, "INVERT_NEGATIVES", b"-x"), "+x")
def test_counts_the_column_in_bytes_as_go_does(self):
self.assertEqual(self.planted(1, 15, "CONDITIONALS_NEGATION", 'x := "åäö" == y\n'.encode()), 'x := "åäö" != y')
def test_is_none_where_the_place_holds_no_token_of_the_mutator(self):
self.assertIsNone(self.planted(4, 6, "CONDITIONALS_NEGATION"))
self.assertIsNone(self.planted(5, 12, "CONDITIONALS_NEGATION"))
self.assertIsNone(self.planted(40, 1, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(0, 1, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(5, 0, "ARITHMETIC_BASE", b"x\n\n\n\n\t\treturn a -"))
self.assertIsNone(self.planted(4, 70, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(4, 7, "A_MUTATOR_GREMLINS_ADDS_LATER"))
def test_takes_the_longest_token_at_the_column(self):
self.assertEqual(self.planted(1, 3, "CONDITIONALS_BOUNDARY", b"a >= b"), "a > b")
self.assertEqual(self.planted(1, 3, "INVERT_BITWISE", b"a &^ b"), "a & b")
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_message_without_the_tests_name_file_or_line(self):
self.assertEqual(task_text(GO_FAILURE), "Pick() = 3,\nwant 4")
def test_leaves_out_each_line_that_names_the_test_or_its_file(self):
self.assertEqual(task_text(TESTIFY_FAILURE), "Error: \tNot equal:\nexpected: 1\nactual : 2")
def test_is_none_where_no_assertion_failed_as_on_a_panic_or_a_passing_run(self):
self.assertIsNone(task_text(PANIC))
self.assertIsNone(task_text("ok \texample.com/calc\t0.004s\n"))
def test_takes_the_message_of_a_test_that_failed_not_what_a_passing_test_logged(self):
output = "=== RUN TestServer\n server_test.go:12: listening on 127.0.0.1:0\n--- PASS: TestServer (0.00s)\n=== RUN TestPick\n pick_test.go:42: got 3, want 4\n--- FAIL: TestPick (0.00s)\nFAIL\n"
self.assertEqual(task_text(output), "got 3, want 4")
def test_takes_the_last_message_of_the_failed_test_since_a_test_logs_before_it_asserts(self):
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:40: input [1 2 3]\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
def test_takes_the_first_failed_test_that_has_a_message(self):
output = "--- FAIL: TestPick (0.00s)\n --- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: got 3\n--- FAIL: TestLast (0.00s)\n pick_test.go:50: got 5\nFAIL\n"
self.assertEqual(task_text(output), "got 3")
def test_a_line_printed_before_any_tests_mark_is_no_tests_message(self):
self.assertEqual(task_text(" setup_test.go:3: starting\n--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\nFAIL\n"), "got 3")
self.assertIsNone(task_text(" setup_test.go:3: starting\n--- FAIL: TestPick (0.00s)\nFAIL\n"))
def test_takes_the_failed_subtests_message_over_what_its_parent_logged_before_it(self):
output = "--- FAIL: TestPick (0.00s)\n pick_test.go:10: three cases\n --- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: got 3\nFAIL\n"
self.assertEqual(task_text(output), "got 3")
def test_is_none_where_only_passing_tests_logged(self):
self.assertIsNone(task_text("=== RUN TestServer\n server_test.go:12: listening\n--- PASS: TestServer (0.00s)\nPASS\n"))
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: TestPick failed\nFAIL\n"))
def test_a_message_ends_at_the_next_line_indented_as_its_first(self):
output = "--- FAIL: TestPick/empty_input (0.00s)\n pick_test.go:42: got 3\n want 4\n--- FAIL: TestLast (0.00s)\n pick_test.go:50: got 5\n"
self.assertEqual(task_text(output), "got 3\nwant 4")
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\n a line the test logged\n"), "got 3")
def test_a_message_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\n want 4"), "got 3\nwant 4")
def test_a_message_may_name_a_part_of_a_subtests_name_that_is_no_test(self):
output = "--- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: empty input: got 3\n in TestPick\n in TestPick/empty\n"
self.assertEqual(task_text(output), "empty input: got 3")
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
for path in ("calc.go", "calc_test.go", "render/pick.go", "render/a+b.go", "render/notes.md", "cli/main.go"):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text("package x\n\n\nfunc f() int {\n\treturn a + b\n}\n")
self.ran: list[tuple[list[str], str]] = []
def gremlins(self, report: dict | None, code: int = 0):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
if report is not None:
pathlib.Path(cwd, argv[argv.index("--output") + 1]).write_text(json.dumps(report))
return Ran(code, "gremlins said so")
return run
def test_names_each_go_file_gremlins_would_mutate_by_its_path_from_the_top(self):
self.assertEqual(sorted(go_files(str(self.top))), ["calc.go", "cli/main.go", "render/a+b.go", "render/pick.go"])
def test_has_gremlins_leave_out_every_other_go_file_by_its_whole_path(self):
killed_mutants(str(self.top), ["render/pick.go"], self.gremlins({"files": []}), 3)
argv, cwd = self.ran[0]
self.assertEqual(cwd, str(self.top))
self.assertEqual(argv[:8], ["gremlins", "unleash", "--exclude-files", r"^calc\.go$", "--exclude-files", r"^cli/main\.go$", "--exclude-files", r"^render/a\+b\.go$"])
self.assertEqual((argv[8], argv[10:]), ("--output", ["--workers", "3"]))
def test_keeps_the_killed_mutants_of_the_files_asked_for_whose_place_holds_the_mutators_token_as_the_line_each_changes(self):
report = {"files": [
{"file_name": "render/pick.go", "mutations": [{"line": 5, "column": 11, "status": "KILLED", "type": "ARITHMETIC_BASE"}, {"line": 4, "column": 1, "status": "KILLED", "type": "ARITHMETIC_BASE"}, {"line": 5, "column": 11, "status": "LIVED", "type": "ARITHMETIC_BASE"}, {"line": 6, "column": 2, "status": "NOT COVERED", "type": "INVERT_LOGICAL"}]},
{"file_name": "calc.go", "mutations": [{"line": 5, "column": 11, "status": "KILLED", "type": "ARITHMETIC_BASE"}]},
]}
self.assertEqual(killed_mutants(str(self.top), ["render/pick.go"], self.gremlins(report), 3), [Mutant("render/pick.go", 5, "render/pick.go:5:11 ARITHMETIC_BASE", (b"\treturn a + b",), (b"\treturn a - b",))])
def test_a_gremlins_that_fails_is_a_failure_with_what_it_printed(self):
found = killed_mutants(str(self.top), ["render/pick.go"], self.gremlins(None, code=1), 3)
self.assertIsInstance(found, Failure)
self.assertIn("gremlins said so", found.reason)
def test_a_mutated_file_that_cannot_be_read_is_a_failure_that_names_the_tree(self):
report = {"files": [{"file_name": "gone.go", "mutations": [{"line": 5, "column": 11, "status": "KILLED", "type": "ARITHMETIC_BASE"}]}]}
found = killed_mutants(str(self.top), ["gone.go"], self.gremlins(report), 3)
self.assertIsInstance(found, Failure)
self.assertIn(f"could not read the files Gremlins mutated in {self.top}", found.reason)
if __name__ == "__main__":
unittest.main()
+275
View File
@@ -0,0 +1,275 @@
"""task-bench's PHP planter: which files Infection mutates, how its log's mutants become lines and what PHPUnit's output tells Haiku.
The four mutants of PICK and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13. Each
logged mutant is cut down to the keys the planter reads. The other mutants 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.php_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 = """<?php
namespace Probe;
final class Pick
{
/** @param list<int> $items */
public static function sum(array $items, int $floor): int
{
$sum = 0;
foreach ($items as $item) {
if ($item >= $floor) {
$sum += $item;
}
}
return $sum;
}
public static function label(int $count): string
{
return $count === 1
? 'one item'
: $count . ' items';
}
}
"""
LINES = PICK.split("\n")
def with_lines(first: int, count: int, *now: str) -> str:
"""PICK with `count` lines from line `first` on replaced by `now`: the mutated source Infection logged for such a mutant."""
return "\n".join([*LINES[:first - 1], *now, *LINES[first - 1 + count:]])
OPERATOR = with_lines(12, 1, "\t\t\tif ($item > $floor) {")
# Infection prints the lines of a statement it rewrote with its own indent, and leaves the ones between them as they were.
FOREACH = with_lines(11, 5, "\t\tforeach ([] as $item) {", " if ($item >= $floor) {", "\t\t\t\t$sum += $item;", "\t\t\t}", " }")
TERNARY = with_lines(21, 3, "\t\treturn $count === 1 ? $count . ' items' : 'one item';")
VISIBILITY = with_lines(19, 1, "\tprotected static function label(int $count): string")
OPERATOR_NOW = (b"\t\t\tif ($item > $floor) {",)
def logged(mutator: str, line: int, mutated_source: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict:
return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "mutatedSourceCode": mutated_source, "originalFilePath": path, "originalStartLine": line}}
FAILING = """PHPUnit 12.5.45 by Sebastian Bergmann and contributors.
Runtime: PHP 8.5.13
Configuration: /w/phpunit.xml
FFF 3 / 3 (100%)
Time: 00:00.002, Memory: 18.00 MB
There were 3 failures:
1) Probe\\Tests\\PickTest::testAddsTheItemsAtOrAboveTheFloor
Failed asserting that 3 is identical to 5.
/w/tests/PickTest.php:12
2) Probe\\Tests\\PickTest::testNamesOne
one is singular
Failed asserting that two strings are identical.
--- Expected
+++ Actual
@@ @@
-'one item'
+''
/w/tests/PickTest.php:17
3) Probe\\Tests\\PickTest::testNamesMany
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
@@ @@
Array (
- 'text' => '3 items'
+ 'text' => '3'
)
/w/tests/PickTest.php:22
FAILURES!
Tests: 3, Assertions: 3, Failures: 3.
"""
PASSING = "PHPUnit 12.5.45 by Sebastian Bergmann and contributors.\n\n... 3 / 3 (100%)\n\nOK (3 tests, 3 assertions)\n"
def failing(test: str, *lines: str) -> str:
return "\n".join(["F 1 / 1 (100%)", "", "There was 1 failure:", "", f"1) {test}", *lines, "", "FAILURES!", "Tests: 1, Assertions: 1, Failures: 1.", ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_an_operator_mutant_changes(self):
self.assertEqual(changed(PICK, OPERATOR), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW))
def test_is_every_line_from_the_first_changed_one_to_the_last(self):
was = tuple(line.encode() for line in LINES[10:15])
now = (b"\t\tforeach ([] as $item) {", b" if ($item >= $floor) {", b"\t\t\t\t$sum += $item;", b"\t\t\t}", b" }")
self.assertEqual(changed(PICK, FOREACH), (11, was, now))
def test_a_mutant_may_have_fewer_lines_than_it_replaces(self):
was = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';")
self.assertEqual(changed(PICK, TERNARY), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)))
def test_a_mutant_may_only_remove_a_line_or_only_add_one(self):
self.assertEqual(changed("a\nb\nc", "a\nc"), (2, (b"b",), ()))
self.assertEqual(changed("a\nc", "a\nb\nc"), (2, (), (b"b",)))
def test_a_line_counts_as_unchanged_before_the_change_or_after_it_never_both(self):
self.assertEqual(changed("a\nb\nb", "a\nb"), (3, (b"b",), ()))
self.assertEqual(changed("b\nb\nc", "b\nc"), (2, (b"b",), ()))
def test_reaches_the_first_line_and_the_last(self):
self.assertEqual(changed("a\nb", "c\nb"), (1, (b"a",), (b"c",)))
self.assertEqual(changed("a\nb", "a\nc"), (2, (b"b",), (b"c",)))
def test_is_none_where_the_mutant_changes_no_line(self):
self.assertIsNone(changed(PICK, PICK))
def test_what_it_returns_plants_as_the_mutant(self):
for source in (OPERATOR, FOREACH, TERNARY, VISIBILITY):
line, was, now = changed(PICK, source)
self.assertEqual(mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)), source.encode())
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
(self.top / "src").mkdir()
(self.top / "src/Pick.php").write_text(PICK, encoding="utf-8")
self.ran: list[tuple[list[str], str, str]] = []
def infection(self, log: dict | str | None, code: int = 0):
"""A run that writes Infection's log where its --logger-json names, or none where log is None, and another log beside it."""
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd, pathlib.Path(cwd, "src/Pick.php").read_text(encoding="utf-8")))
pathlib.Path(cwd, "infection.html").write_text("every mutant", encoding="utf-8")
if log is not None:
path = next(argument.partition("=")[2] for argument in argv if argument.startswith("--logger-json="))
pathlib.Path(cwd, path).write_text(log if isinstance(log, str) else json.dumps(log), encoding="utf-8")
return Ran(code, "the tool's last words\n")
return run
def test_runs_infection_over_the_files_in_a_copy_of_the_tree_with_a_json_log_and_no_score_to_reach(self):
killed_mutants(str(self.top), ["src/Pick.php", "src/Last.php"], self.infection({"killed": []}), 3)
(argv, cwd, source), = self.ran
self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$")
self.assertEqual(source, PICK)
self.assertEqual(argv, ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress", "--min-msi=0", "--min-covered-msi=0", "--logger-json=infection-log.json"])
def test_is_each_killed_mutant_as_the_lines_it_changes(self):
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR), logged("Ternary", 21, TERNARY)], "escaped": [logged("PublicVisibility", 19, VISIBILITY)]}
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1)
ternary = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';")
self.assertEqual(found, [
Mutant("src/Pick.php", 12, "src/Pick.php:12 GreaterThanOrEqualTo", (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW),
Mutant("src/Pick.php", 21, "src/Pick.php:21 Ternary", ternary, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)),
])
def test_names_a_mutant_by_the_line_infection_logs_for_it(self):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": [logged("Foreach_", 11, FOREACH), logged("Ternary", 20, TERNARY)]}), 1)
self.assertEqual([(mutant.line, mutant.name) for mutant in found], [(11, "src/Pick.php:11 Foreach_"), (21, "src/Pick.php:20 Ternary")])
def test_names_a_file_by_its_path_from_the_top_wherever_infection_saw_the_tree(self):
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]}
found = killed_mutants(str(self.top), ["src/Pick.php", "lib/src/Pick.php", "Pick.php"], self.infection(log), 1)
self.assertEqual([mutant.path for mutant in found], ["src/Pick.php", "src/Pick.php", "lib/src/Pick.php"])
def test_leaves_out_a_mutant_that_changes_no_line(self):
log = {"killed": [logged("GreaterThanOrEqualTo", 12, PICK)]}
self.assertEqual(killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1), [])
def test_leaves_the_tree_as_it_was_whatever_infection_wrote(self):
for code in (0, 1):
killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code), 1)
self.assertEqual(sorted(str(path.relative_to(self.top)) for path in self.top.rglob("*")), ["src", "src/Pick.php"])
def test_fails_where_infection_exits_nonzero(self):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code=1), 1)
self.assertEqual(found, Failure("Infection exited 1:\nthe tool's last words"))
def test_passes_on_a_run_that_could_not_start(self):
failure = Failure("vendor/bin/infection could not start: No such file or directory")
self.assertIs(killed_mutants(str(self.top), ["src/Pick.php"], lambda argv, cwd: failure, 1), failure)
def test_fails_where_infection_wrote_no_log_or_one_it_cannot_read(self):
unreadable = (None, "not json", "{}", '{"killed": [{}]}', '{"killed": [7]}', json.dumps({"killed": [{"mutator": {**logged("Ternary", 21, TERNARY)["mutator"], "mutatedSourceCode": 7}}]}))
for log in unreadable:
with self.subTest(log=log):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1)
self.assertIsInstance(found, Failure)
self.assertIn("could not read Infection's log, infection-log.json in ", found.reason)
def test_fails_where_the_tree_cannot_be_copied(self):
found = killed_mutants(str(self.top / "missing"), ["src/Pick.php"], self.infection({"killed": []}), 1)
self.assertIsInstance(found, Failure)
self.assertEqual(self.ran, [])
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_message_without_the_tests_name_or_file(self):
self.assertEqual(task_text(FAILING), "Failed asserting that 3 is identical to 5.")
def test_is_every_line_of_a_message_up_to_the_file_and_line_that_failed(self):
second = FAILING[FAILING.index("2) "):]
expected = "one is singular\nFailed asserting that two strings are identical.\n--- Expected\n+++ Actual\n@@ @@\n-'one item'\n+''"
self.assertEqual(task_text("There was 1 failure:\n\n" + second), expected)
def test_is_none_on_a_passing_run_or_output_that_lists_no_failure(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("PHP Parse error: syntax error, unexpected token \"}\" in /w/src/Pick.php on line 12\n"))
self.assertIsNone(task_text("1) a line that only looks like a listed test\nits message\n"))
self.assertIsNone(task_text(""))
def test_reads_an_error_as_it_reads_a_failure(self):
output = "E\n\nThere was 1 error:\n\n1) Probe\\Tests\\PickTest::testNamesOne\nTypeError: label(): Argument #1 ($count) must be of type int, string given\n\n/w/src/Pick.php:19\n/w/tests/PickTest.php:17\n\nERRORS!\n"
self.assertEqual(task_text(output), "TypeError: label(): Argument #1 ($count) must be of type int, string given")
def test_leaves_out_each_line_that_names_the_test_its_class_or_its_file(self):
lines = ("testNamesOne went wrong", "PickTest saw it", "see tests/LabelTest.php", "got 3, want 5", "", "/w/tests/PickTest.php:17")
self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", *lines)), "got 3, want 5")
self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne with data set #0 (1, 'one')", *lines)), "got 3, want 5")
def test_reads_a_listed_test_that_names_no_class(self):
self.assertEqual(task_text(failing("testNamesOne", "got 3, want 5")), "got 3, want 5")
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", "testNamesOne failed", "", "/w/tests/PickTest.php:17")))
def test_reads_no_test_of_another_list_as_a_failed_one(self):
named = failing("Probe\\Tests\\PickTest::testSum", "PickTest failed", "", "/w/tests/PickTest.php:9").partition("FAILURES!")[0]
for heading in ("There was 1 risky test:", "There were 2 risky tests:", "1 test triggered 1 deprecation:", "2 tests triggered 3 PHPUnit warnings:"):
with self.subTest(heading=heading):
output = "\n".join([named, "--", "", heading, "", "1) Probe\\Tests\\LastTest::testLabels", "This test did not perform any assertions", "", "/w/tests/LastTest.php:20", "", "FAILURES!"])
self.assertIsNone(task_text(output))
def test_reads_the_failures_listed_after_another_list(self):
output = "\n".join(["There was 1 risky test:", "", "1) LastTest::testLabels", "This test did not perform any assertions", "", "--", "", "There was 1 failure:", "", "1) PickTest::testSum", "Failed asserting that 3 is identical to 5.", "", "/w/tests/PickTest.php:9", "", "FAILURES!"])
self.assertEqual(task_text(output), "Failed asserting that 3 is identical to 5.")
def test_takes_the_first_failed_test_that_has_a_message(self):
output = "There were 2 failures:\n\n1) PickTest::testAdds\ntestAdds\n\n/w/tests/PickTest.php:12\n\n2) PickTest::testLabels\nno label\n\n/w/tests/PickTest.php:17\n\nFAILURES!\n"
self.assertEqual(task_text(output), "no label")
def test_a_message_without_a_file_and_line_ends_at_the_next_test_or_the_summary(self):
self.assertEqual(task_text("There were 2 failures:\n\n1) PickTest::testAdds\ngot 3\n\n2) PickTest::testLabels\nno label\n"), "got 3")
self.assertEqual(task_text(failing("PickTest::testAdds", "got 3")), "got 3")
self.assertEqual(task_text("There was 1 error:\n\n1) PickTest::testAdds\ngot 3\n\n--\n\nThere was 1 failure:\n\n1) PickTest::testLabels\nno label\n"), "got 3")
if __name__ == "__main__":
unittest.main()
+97
View File
@@ -0,0 +1,97 @@
"""task-bench's planter: which files it mutates, which language's tool finds the mutants of each, which mutants it draws and whose test output it reads."""
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.bugs.plant import drawn, killed_mutants, Language, LANGUAGES, place_files, task_text
from failure import Failure
from task_bench.bugs.planted_mutant import Mutant
PLACES = """## 2026-11-19T22:33:15Z, PR #646 at a357cc7b
Junior A, hardest first:
- Locality, Shape: `internal/render/pick.go:287` `parked`: three steps held at once
- Shape: `internal/render/pick_test.go:12` `TestPick`: a long table
- Self-sufficiency: `README.md:89` "Round cap": three sections
- Locality: `cli/report.go:41` the comment: points to `cli/gone.go`
Mid A, hardest first:
- Locality: `internal/render/pick.go:354` `resumed`: a loop
- Locality: `data-import/geo.py:3` `load`: a long chain
"""
def mutant(path: str, line: int = 1) -> Mutant:
return Mutant(path, line, f"{path}:{line} x", (b"a + b",), (b"a - b",))
class PlaceFilesTest(unittest.TestCase):
def test_names_each_go_and_python_file_that_holds_a_place_once_and_no_test_file_or_other_language(self):
self.assertEqual(place_files(PLACES), ["cli/report.go", "data-import/geo.py", "internal/render/pick.go"])
def test_names_none_where_the_seats_found_no_places(self):
self.assertEqual(place_files("Seats found no places hard."), [])
def test_names_none_where_the_places_name_only_test_files_or_another_suffix(self):
self.assertEqual(place_files("- `tests/test_geo.py:3` `load`\n- `geo_test.py:3` `load`\n- `notes.pyc:1` `x`\n"), [])
class DrawnTest(unittest.TestCase):
MUTANTS = [mutant("a.go", line) for line in range(1, 40)]
def test_a_seed_draws_the_same_order_whatever_order_the_tool_listed_the_mutants_in(self):
self.assertEqual(drawn(self.MUTANTS, 7), drawn(self.MUTANTS[::-1], 7))
def test_draws_every_mutant_once(self):
self.assertEqual(sorted(drawn(self.MUTANTS + self.MUTANTS[:3], 7)), self.MUTANTS)
def test_another_seed_draws_another_order(self):
self.assertNotEqual(drawn(self.MUTANTS, 7), drawn(self.MUTANTS, 8))
class LanguagesTest(unittest.TestCase):
def setUp(self):
self.asked: list[tuple] = []
self.found: dict[str, list[Mutant] | Failure] = {"Go": [mutant("b.go"), mutant("a.go")], "Python": [mutant("c.py")]}
self.languages = tuple(Language(name, suffixes, self.killed(name), f"{name} read {{}}".format) for name, suffixes in (("Go", (".go",)), ("Python", (".py", ".pyi"))))
def killed(self, name: str):
def killed(top: str, files: list[str], run, jobs: int) -> list[Mutant] | Failure:
self.asked.append((name, top, files, run, jobs))
return self.found[name]
return killed
def test_each_languages_tool_finds_the_mutants_of_the_files_in_that_language(self):
self.assertEqual(killed_mutants("/top", ["a.go", "c.py", "b.go", "d.pyi"], "run", 3, self.languages), [mutant("b.go"), mutant("a.go"), mutant("c.py")])
self.assertEqual(self.asked, [("Go", "/top", ["a.go", "b.go"], "run", 3), ("Python", "/top", ["c.py", "d.pyi"], "run", 3)])
def test_a_language_without_a_file_runs_no_tool(self):
self.assertEqual(killed_mutants("/top", ["c.py"], "run", 3, self.languages), [mutant("c.py")])
self.assertEqual([name for name, *_ in self.asked], ["Python"])
def test_a_tool_that_fails_fails_the_whole(self):
self.found["Go"] = Failure("gremlins broke")
self.assertEqual(killed_mutants("/top", ["a.go", "c.py"], "run", 3, self.languages), Failure("gremlins broke"))
def test_the_language_of_the_bugs_file_reads_the_test_commands_output(self):
self.assertEqual((task_text("pkg/a.go", "output", self.languages), task_text("pkg/c.pyi", "output", self.languages)), ("Go read output", "Python read output"))
self.assertIsNone(task_text("README.md", "output", self.languages))
class ShippedLanguagesTest(unittest.TestCase):
def test_each_language_reads_its_own_test_runners_output(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("PHP", (".php",)), ("Python", (".py",)), ("Rust", (".rs",)), ("TypeScript", (".cjs", ".cts", ".js", ".jsx", ".mjs", ".mts", ".ts", ".tsx"))])
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.php", "There was 1 failure:\n\n1) CalcTest::testPicks\ngot 3, want 4\n\n/w/tests/CalcTest.php:9\n"), "got 3, want 4")
self.assertEqual(task_text("calc.ts", "✖ failing tests:\n\ntest at calc.test.ts:5:1\n✖ picks (1.2ms)\n Error: got 3, want 4\n at pick (file:///w/calc.ts:9:5)\n"), "Error: got 3, want 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__":
unittest.main()
@@ -0,0 +1,99 @@
"""How task-bench re-applies a mutant: as the same change to the same lines at the base and at the head."""
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.bugs.planted_mutant import bug_at_sides, line_at_head, Mutant, mutated
class MutatedTest(unittest.TestCase):
SOURCE = b"a\n\tb + c\n\td,\n\te\n"
def test_puts_the_mutants_lines_in_place_of_the_ones_it_changes_and_changes_no_other_byte(self):
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 2, "calc.py:2 x", (b"\tb + c",), (b"\tb - c",))), b"a\n\tb - c\n\td,\n\te\n")
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 2, "calc.py:2 x", (b"\tb + c", b"\td,"), (b"\tb", b"\t- c", b"\td"))), b"a\n\tb\n\t- c\n\td\n\te\n")
def test_removes_lines_and_adds_them(self):
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 3, "calc.py:3 x", (b"\td,",), ())), b"a\n\tb + c\n\te\n")
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 3, "calc.py:3 x", (), (b"\tf,",))), b"a\n\tb + c\n\tf,\n\td,\n\te\n")
def test_is_none_where_the_line_does_not_start_the_lines_the_mutant_changes(self):
for line, was in ((1, (b"\tb + c",)), (2, (b"\tb + c", b"\te")), (2, (b"b + c",)), (0, (b"a",)), (-1, (b"\te",)), (5, (b"\te", b"")), (9, (b"",)), (7, ())):
with self.subTest(line=line, was=was):
self.assertIsNone(mutated(self.SOURCE, Mutant("calc.py", line, "x", was, (b"z",))))
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 6, "x", (), (b"z",))), self.SOURCE + b"\nz")
def test_mutates_the_last_line_of_a_file(self):
self.assertEqual(mutated(b"a\nb + c", Mutant("calc.go", 2, "x", (b"b + c",), (b"b - c",))), b"a\nb - c")
self.assertIsNone(mutated(b"a\nb + c", Mutant("calc.go", 3, "x", (b"b + c",), (b"b - c",))))
def test_a_crlf_file_matches_a_mutants_lines_without_cr_and_gets_its_new_lines_with_one(self):
source = b"a\r\n\tb + c\r\n\td,\r\n\te\r\n"
self.assertEqual(mutated(source, Mutant("calc.py", 2, "x", (b"\tb + c", b"\td,"), (b"\tb", b"\t- c", b"\td"))), b"a\r\n\tb\r\n\t- c\r\n\td\r\n\te\r\n")
self.assertEqual(mutated(source, Mutant("calc.py", 3, "x", (), (b"\tf,",))), b"a\r\n\tb + c\r\n\tf,\r\n\td,\r\n\te\r\n")
self.assertEqual(mutated(source, Mutant("calc.py", 3, "x", (b"\td,",), ())), b"a\r\n\tb + c\r\n\te\r\n")
self.assertIsNone(mutated(source, Mutant("calc.py", 2, "x", (b"\tb - c",), (b"z",))))
self.assertEqual(mutated(source, Mutant("calc.py", 2, "x", (b"\tb + c", b"\td,"), (b"x", b"y"))), b"a\r\nx\r\ny\r\n\te\r\n")
def test_a_mutant_whose_lines_keep_their_cr_matches_and_goes_in_as_it_is(self):
source = b"a\r\n\tb + c\r\n\te"
self.assertEqual(mutated(source, Mutant("calc.go", 2, "x", (b"\tb + c\r",), (b"\tb - c\r",))), b"a\r\n\tb - c\r\n\te")
self.assertEqual(mutated(source, Mutant("calc.go", 3, "x", (b"\te",), (b"\tf",))), b"a\r\n\tb + c\r\n\tf")
self.assertEqual(mutated(source, Mutant("calc.go", 3, "x", (), (b"\tf\r",))), b"a\r\n\tb + c\r\n\tf\r\n\te")
self.assertEqual(mutated(source, Mutant("calc.go", 3, "x", (), (b"\tf",))), b"a\r\n\tb + c\r\n\tf\r\n\te")
self.assertEqual(mutated(source, Mutant("calc.go", 2, "x", (b"\tb + c", b"\te"), (b"x", b"y"))), b"a\r\nx\r\ny")
def test_a_file_that_mixes_line_ends_takes_the_one_of_its_first_line(self):
self.assertEqual(mutated(b"a\r\nb\nc\n", Mutant("calc.py", 2, "x", (b"b",), (b"z",))), b"a\r\nz\r\nc\n")
self.assertEqual(mutated(b"a\nb\r\nc\r\n", Mutant("calc.py", 2, "x", (b"b",), (b"z",))), b"a\nz\nc\r\n")
def test_the_last_line_of_a_crlf_file_has_no_line_end_to_take(self):
self.assertEqual(mutated(b"a\r\nb + c", Mutant("calc.py", 2, "x", (b"b + c",), (b"b - c",))), b"a\r\nb - c")
class LineAtHeadTest(unittest.TestCase):
# Lines 3 and 4 became one, two lines went in after line 9, and line 20 went.
DIFF = "diff --git a/calc.go b/calc.go\n--- a/calc.go\n+++ b/calc.go\n@@ -3,2 +3 @@\n-a\n-b\n+c\n@@ -9,0 +9,2 @@\n+d\n+e\n@@ -20 +20,0 @@\n-f\n"
def test_a_line_above_every_change_keeps_its_number(self):
self.assertEqual(line_at_head(self.DIFF, 2), 2)
def test_a_line_below_a_change_moves_by_the_lines_it_added_and_removed(self):
self.assertEqual([line_at_head(self.DIFF, line) for line in (5, 9, 10, 19, 21)], [4, 8, 11, 20, 21])
def test_a_line_the_head_changed_or_removed_has_none(self):
self.assertEqual([line_at_head(self.DIFF, line) for line in (3, 4, 20)], [None, None, None])
def test_no_diff_keeps_every_line(self):
self.assertEqual(line_at_head("", 12), 12)
class BugAtSidesTest(unittest.TestCase):
MUTANT = Mutant("calc.go", 3, "calc.go:3:11 ARITHMETIC_BASE", (b"\treturn a + b",), (b"\treturn a - b",))
BASE = b"package calc\n\n\treturn a + b\n"
# The head adds a line above the bug's.
HEAD = b"package calc\n// Add adds.\n\n\treturn a + b\n"
DIFF = "@@ -1,0 +2 @@\n+// Add adds.\n"
def test_the_bug_is_the_same_change_at_each_side_on_the_line_as_that_side_numbers_it(self):
found = bug_at_sides(self.MUTANT, self.DIFF, {"base": self.BASE, "head": self.HEAD})
self.assertEqual(found, {"base": self.BASE.replace(b"+", b"-"), "head": self.HEAD.replace(b"+", b"-")})
def test_a_line_the_head_changed_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "@@ -3 +3 @@\n-\treturn a + b\n+\treturn b + a\n", {"base": self.BASE, "head": self.BASE}))
def test_a_side_without_the_file_or_without_the_line_the_mutant_changes_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": None}))
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": b"package calc\n\n\treturn sum(a, b)\n"}))
def test_a_mutant_of_several_lines_holds_no_bug_where_the_head_changed_one_after_the_first(self):
mutant = Mutant("calc.py", 1, "calc.py:1 x", (b"low = min(", b"\ta,"), (b"low = max(", b"\ta,"))
base, head = b"low = min(\n\ta,\n\tb)\n", b"low = min(\n\tc,\n\tb)\n"
self.assertIsNone(bug_at_sides(mutant, "@@ -2 +2 @@\n-\ta,\n+\tc,\n", {"base": base, "head": head}))
self.assertEqual(bug_at_sides(mutant, "", {"base": base, "head": base}), {"base": base.replace(b"min", b"max"), "head": base.replace(b"min", b"max")})
if __name__ == "__main__":
unittest.main()
+225
View File
@@ -0,0 +1,225 @@
"""task-bench's Python planter: which mutants of mutmut's it keeps, as the lines each changes, and what pytest's output tells Haiku."""
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.bugs.python_bugs import killed_mutants, task_text
from task_bench.bugs.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
CALC = "def double(n):\n\treturn n * 2\n\n\ndef triple(n):\n\treturn (\n\t\tn * 3\n\t)\n"
# mutmut 3's copy of calc.py: the original of each function, then its mutants.
COPY = """def x_double__mutmut_orig(n):
return n * 2
def x_double__mutmut_1(n):
return n / 2
def x_double__mutmut_2(n):
return n * 3
def x_triple__mutmut_orig(n):
return (
n * 3
)
def x_triple__mutmut_1(n):
return (
n / 3
)
def x_triple__mutmut_2(n):
return [
n * 3
]
"""
RESULTS = " calc.x_double__mutmut_1: killed\n calc.x_double__mutmut_2: survived\n calc.x_triple__mutmut_1: no tests\n calc.x_triple__mutmut_2: caught by type check\n"
# pytest 9.2.0's report of three failed tests, the last on an error the code raised.
PYTEST_FAILURES = """============================= test session starts ==============================
collected 5 items
test_calc.py ..FFF [100%]
=================================== FAILURES ===================================
_____________________________ TotalTest.test_adds ______________________________
self = <test_calc.TotalTest testMethod=test_adds>
def test_adds(self):
> self.assertEqual(total(1, 2), 3)
E AssertionError: -1 != 3
test_calc.py:14: AssertionError
________________________________ test_total[1] _________________________________
a = 1
@pytest.mark.parametrize("a", [1, 2])
def test_total(a):
> assert total(a, 2) == a + 2
E assert -1 == (1 + 2)
E + where -1 = total(1, 2)
test_calc.py:19: AssertionError
__________________________________ test_pick ___________________________________
def test_pick():
> assert pick([1, 2, 3]) == 3
^^^^^^^^^^^^^^^
test_calc.py:23:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
rows = [1, 2, 3]
def pick(rows):
> return rows[3]
^^^^^^^
E IndexError: list index out of range
calc.py:2: IndexError
=========================== short test summary info ============================
FAILED test_calc.py::TotalTest::test_adds - AssertionError: -1 != 3
FAILED test_calc.py::test_total[1] - assert -1 == (1 + 2)
FAILED test_calc.py::test_pick - IndexError: list index out of range
========================= 3 failed, 2 passed in 0.03s ==========================
"""
def failures(*sections: str) -> str:
"""pytest's report of failed tests, each section a test's heading and what follows it, as --tb=short prints them."""
return "=================================== FAILURES ===================================\n" + "".join(sections) + "=========================== short test summary info ============================\nE no error\n"
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
for path, text in (("bin/setup.cfg", "[tool:pytest]\n"), ("bin/pkg/calc.py", CALC), ("bin/pkg/test_calc.py", "import pkg.calc\n"), ("bin/pkg/empty.py", "LIMIT = 3\n"), ("README.md", "# Calc\n")):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text(text)
self.ran: list[tuple[list[str], str, list[str]]] = []
# Where the fake mutmut writes its copy of calc.py, from the folder it runs in.
self.copy = "pkg/calc.py"
def mutmut(self, results: str = RESULTS, code: int = 0, said: str = ""):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd, sorted(str(path.relative_to(cwd)) for path in pathlib.Path(cwd).rglob("*") if path.is_file())))
if argv[:2] == ["mutmut", "results"]:
return Ran(0, results)
pathlib.Path(cwd, "mutants", self.copy).parent.mkdir(parents=True)
pathlib.Path(cwd, "mutants", self.copy).write_text(COPY)
return Ran(code, said)
return run
def test_keeps_each_mutant_the_tests_kill_as_the_lines_it_changes_named_by_its_place_and_mutmuts_name(self):
found = killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(RESULTS.replace("calc.x_", "pkg.calc.x_")), 3)
self.assertEqual(found, [
Mutant("bin/pkg/calc.py", 2, "bin/pkg/calc.py:2 x_double__mutmut_1", (b"\treturn n * 2",), (b"\treturn n / 2",)),
Mutant("bin/pkg/calc.py", 6, "bin/pkg/calc.py:6 x_triple__mutmut_2", (b"\treturn (", b"\t\tn * 3", b"\t)"), (b"\treturn [", b"\t\tn * 3", b"\t]")),
])
def test_mutmut_mutates_every_function_of_the_files_in_a_copy_of_the_folder_that_holds_their_settings(self):
killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(), 3)
argv, cwd, files = self.ran[0]
self.assertEqual(argv, ["mutmut", "run", "--max-children", "3", "pkg.calc.x_double*", "pkg.calc.x_triple*"])
self.assertEqual((pathlib.Path(cwd).parent.parent, files), (self.top, ["pkg/calc.py", "pkg/empty.py", "pkg/test_calc.py", "setup.cfg"]))
self.assertEqual(self.ran[1][0], ["mutmut", "results", "--all", "true"])
self.assertEqual(sorted(path.name for path in self.top.iterdir()), ["README.md", "bin"])
def test_mutmuts_copy_keeps_a_link_to_a_folder_as_a_link(self):
(self.top / "bin/shared").mkdir()
(self.top / "bin/pkg/fixtures").symlink_to("../shared")
links: list[str] = []
mutmut = self.mutmut()
def run(argv: list[str], cwd: str) -> Ran:
links.extend(str(path.relative_to(cwd)) for path in pathlib.Path(cwd).rglob("*") if path.is_symlink())
return mutmut(argv, cwd)
killed_mutants(str(self.top), ["bin/pkg/calc.py"], run, 3)
self.assertEqual(links[:1], ["pkg/fixtures"])
def test_a_file_without_a_function_has_no_mutant_and_mutmut_does_not_run(self):
self.assertEqual(killed_mutants(str(self.top), ["bin/pkg/empty.py"], self.mutmut(), 3), [])
self.assertEqual(self.ran, [])
def test_a_mutmut_that_fails_or_crashes_is_a_failure_that_says_how(self):
crash = 'Traceback (most recent call last):\n File "/uv/site-packages/mutmut/__main__.py", line 1050, in _run\n worker = pop(pid)\nKeyError: 12\n'
for said, reason in (("mutmut said so", "mutmut said so"), (crash, "mutmut in bin crashed with KeyError: 12, in mutmut/__main__.py line 1050")):
with self.subTest(said=said):
found = killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(code=1, said=said), 3)
self.assertIsInstance(found, Failure)
self.assertIn(reason, found.reason)
def test_a_file_that_is_gone_is_a_failure_that_names_the_tree(self):
found = killed_mutants(str(self.top), ["bin/pkg/gone.py"], self.mutmut(), 3)
self.assertIsInstance(found, Failure)
self.assertIn(f"could not read the files to mutate in {self.top}", found.reason)
def test_mutates_a_function_on_the_files_first_line_and_one_on_its_last(self):
(self.top / "bin/pkg/ends.py").write_text("def first(n): return n + 1\n\n\ndef last(n): return n * 2")
killed_mutants(str(self.top), ["bin/pkg/ends.py"], self.mutmut(), 3)
self.assertEqual(self.ran[0][0][4:], ["pkg.ends.x_first*", "pkg.ends.x_last*"])
def test_a_crlf_file_gives_the_same_mutants_without_the_cr_and_they_apply_to_it(self):
(self.top / "bin/pkg/calc.py").write_bytes(CALC.replace("\n", "\r\n").encode())
found = killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(RESULTS.replace("calc.x_", "pkg.calc.x_")), 3)
self.assertEqual([(mutant.line, mutant.was, mutant.now) for mutant in found], [(2, (b"\treturn n * 2",), (b"\treturn n / 2",)), (6, (b"\treturn (", b"\t\tn * 3", b"\t)"), (b"\treturn [", b"\t\tn * 3", b"\t]"))])
changed = mutated((self.top / "bin/pkg/calc.py").read_bytes(), found[0])
self.assertIsNotNone(changed)
self.assertIn(b"\treturn n / 2\r\n", changed or b"")
def test_keeps_the_mutants_of_every_folder_mutmut_runs_in(self):
for path, text in (("tools/setup.cfg", "[tool:pytest]\n"), ("tools/pkg/calc.py", CALC)):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text(text)
found = killed_mutants(str(self.top), ["tools/pkg/calc.py", "bin/pkg/calc.py"], self.mutmut(RESULTS.replace("calc.x_", "pkg.calc.x_")), 3)
self.assertEqual([mutant.name for mutant in found], ["bin/pkg/calc.py:2 x_double__mutmut_1", "bin/pkg/calc.py:6 x_triple__mutmut_2", "tools/pkg/calc.py:2 x_double__mutmut_1", "tools/pkg/calc.py:6 x_triple__mutmut_2"])
def test_a_file_in_the_folder_mutmut_runs_in_at_the_top_keeps_its_path(self):
(self.top / "setup.cfg").write_text("[tool:pytest]\n")
(self.top / "calc.py").write_text(CALC)
self.copy = "calc.py"
found = killed_mutants(str(self.top), ["calc.py"], self.mutmut(), 3)
self.assertEqual(found[0], Mutant("calc.py", 2, "calc.py:2 x_double__mutmut_1", (b"\treturn n * 2",), (b"\treturn n / 2",)))
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_error_without_the_code_around_it(self):
self.assertEqual(task_text(PYTEST_FAILURES), "AssertionError: -1 != 3")
def test_keeps_each_line_of_the_error(self):
self.assertEqual(task_text(failures("___ test_total[1] ___\ntest_calc.py:19: in test_total\n assert total(a, 2) == a + 2\nE assert -1 == (1 + 2)\nE + where -1 = total(1, 2)\nE\n")), "assert -1 == (1 + 2)\n+ where -1 = total(1, 2)")
def test_takes_an_error_the_code_raised_from_below_the_last_frame(self):
section = "___ test_pick ___\ntest_calc.py:23: \n_ _ _ _ _ _ _ _\n\n def pick(rows):\n> \treturn rows[3]\nE IndexError: list index out of range\n\ncalc.py:2: IndexError\n"
self.assertEqual(task_text(failures(section)), "IndexError: list index out of range")
def test_leaves_out_each_line_that_names_the_test_its_class_or_a_test_file(self):
section = "_ PickTest.test_empty[case 1] _\nE AssertionError: 3 != 4\nE test_empty: off by one\nE in PickTest\nE see test_calc.py:12\nE see calc_test.py\nE see conftest.py\nE see calc.py\n"
self.assertEqual(task_text(failures(section)), "AssertionError: 3 != 4\nsee calc.py")
def test_is_none_where_the_first_error_only_names_the_test(self):
self.assertIsNone(task_text(failures("___ test_pick ___\nE test_pick failed\n", "___ test_last ___\nE got 5\n")))
def test_takes_the_first_failed_test_that_has_an_error(self):
self.assertEqual(task_text(failures("___ test_pick ___\nno error here\n", "___ test_next ___\nE got 3\n", "___ test_last ___\nE got 5\n")), "got 3")
def test_a_line_the_failed_test_printed_is_no_error(self):
section = "___ test_pick ___\nE got 3\n----------------------------- Captured stdout call -----------------------------\nE printed, not raised\n"
self.assertEqual(task_text(failures(section, "___ test_last ___\nE got 5\n")), "got 3")
self.assertIsNone(task_text(failures("___ test_pick ___\n--- Captured stderr call ---\nE printed, not raised\n")))
def test_is_none_where_pytest_reports_no_failed_test_with_an_error(self):
for output in ("", "===== 5 passed in 0.03s =====\n", "E stray\n", "==== ERRORS ====\n___ ERROR collecting test_calc.py ___\nE SyntaxError: invalid syntax\n", failures(), failures("___ test_pick ___\n"), "E before\n" + failures("E under no test\n")):
with self.subTest(output=output):
self.assertIsNone(task_text(output))
def test_an_error_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("==== FAILURES ====\n___ test_pick ___\nE got 3"), "got 3")
if __name__ == "__main__":
unittest.main()
+269
View File
@@ -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[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()
@@ -0,0 +1,153 @@
"""The test modules of a Rust file: where they are, and a fixed file with the planted tests put back."""
import pathlib
import sys
import textwrap
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from task_bench.bugs import rust_test_modules
from task_bench.bugs.rust_test_modules import tells_apart
LIB = textwrap.dedent("""\
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds() {
assert_eq!(add(1, 2), 3);
}
}
""")
def modules(source: str) -> dict[bytes, tuple[int, int]] | None:
return rust_test_modules.modules(source.encode())
def with_tests_of(planted: str, copy: str) -> str:
return rust_test_modules.with_tests_of(planted.encode(), copy.encode()).decode()
def spelt(source: str) -> dict[str, str] | None:
found = modules(source)
return None if found is None else {name.decode(): source[start:end] for name, (start, end) in found.items()}
class ModulesTest(unittest.TestCase):
def test_holds_each_test_module_from_its_attribute_to_its_closing_brace(self):
self.assertEqual(spelt(LIB), {"tests": LIB[LIB.index("#[cfg(test)]"):LIB.rindex("}") + 1]})
def test_lists_no_module_where_the_file_has_no_test_module(self):
self.assertEqual(modules("fn main() {}\n"), {})
def test_takes_a_module_with_a_visibility_and_another_attribute(self):
source = "#[cfg(test)]\n#[allow(dead_code)]\npub(crate) mod checks {\n}\nfn after() {}\n"
self.assertEqual(spelt(source), {"checks": source[:source.index("}") + 1]})
def test_lists_no_module_where_the_attribute_is_on_anything_but_an_inline_module(self):
self.assertEqual(modules("#[cfg(test)]\nmod tests;\n#[cfg(test)]\nuse std::fmt;\n#[cfg(test)]\nfn helper() {}\n"), {})
def test_lists_no_module_inside_a_test_module(self):
source = "#[cfg(test)]\nmod outer {\n #[cfg(test)]\n mod inner {}\n}\n"
self.assertEqual(list(spelt(source)), ["outer"])
def test_reads_past_a_brace_in_a_string_a_char_a_comment_or_an_escape(self):
source = textwrap.dedent("""\
#[cfg(test)]
mod tests {
// }
/* } /* } */ } */
const A: &str = "}\\"}";
const B: &str = r#"}"}"#;
const C: char = '}';
const D: char = '\\'';
fn lifetime<'a>(x: &'a str) -> &'a str { x }
}
fn after() {}
""")
self.assertEqual(spelt(source), {"tests": source[:source.index("}\nfn after")+1]})
def test_reads_a_raw_string_that_ends_in_a_backslash(self):
source = "#[cfg(test)]\nmod tests {\n const A: &str = r\"\\\";\n}\nfn after() {}\n"
self.assertEqual(list(spelt(source)), ["tests"])
def test_ends_a_raw_string_at_its_first_closing_quote(self):
source = "#[cfg(test)]\nmod tests {\n const A: &str = r#\"x\"#;\n}\nconst B: &str = r#\"y\"#;\n"
self.assertEqual(list(spelt(source)), ["tests"])
def test_reads_a_string_that_ends_in_two_backslashes_or_in_an_escaped_quote(self):
for literal in ('"\\\\"', '"a\\""', '"\\}\\}"'):
with self.subTest(literal=literal):
source = "#[cfg(test)]\nmod tests {\n const A: &str = " + literal + ";\n}\nfn after() {}\n"
self.assertEqual(list(spelt(source)), ["tests"])
def test_lists_no_plain_module_that_follows_a_comment_or_a_char(self):
self.assertEqual(modules("// helpers\nmod util {}\nfn a() { let c = 'x'; }\nmod more {}\n"), {})
def test_lists_a_test_module_inside_a_module_that_is_no_test(self):
source = "mod outer {\n #[cfg(test)]\n mod inner {}\n fn after() {}\n}\n"
self.assertEqual(spelt(source), {"inner": "#[cfg(test)]\n mod inner {}"})
def test_cannot_tell_the_modules_apart_where_two_hold_one_name(self):
self.assertIsNone(modules("#[cfg(test)]\nmod tests {}\nfn a() { #[cfg(test)] mod tests {} }\n"))
def test_cannot_tell_the_modules_apart_where_a_brace_string_or_comment_is_never_closed(self):
for source in ("#[cfg(test)]\nmod tests {\n", "fn a() {\n", "const A: &str = \"\n", "/* open\n", "const A: &str = r#\"\n"):
with self.subTest(source=source):
self.assertIsNone(modules(source))
class TellsApartTest(unittest.TestCase):
def test_tells_the_modules_of_a_rust_file_apart_where_they_can_be(self):
self.assertEqual([tells_apart("lib.rs", b"fn a() {}"), tells_apart("lib.rs", b"fn a() {")], [True, False])
def test_takes_a_file_of_another_language_whatever_it_holds(self):
self.assertTrue(tells_apart("calc.go", b"func a() {"))
class WithTestsOfTest(unittest.TestCase):
def test_takes_the_code_as_fixed_and_the_tests_as_planted(self):
planted = LIB.replace("a + b", "a - b")
fixed = LIB.replace("assert_eq!(add(1, 2), 3);", "assert_eq!(add(1, 2), 0);")
self.assertEqual(with_tests_of(planted, fixed), LIB)
def test_takes_the_planted_tests_where_the_fix_deleted_them(self):
planted = LIB.replace("a + b", "a - b")
fixed = "pub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n"
self.assertEqual(with_tests_of(planted, fixed), planted)
def test_leaves_out_a_test_module_the_fix_added(self):
planted = "fn a() {}\n"
fixed = "fn a() {}\n#[cfg(test)]\nmod mine {}\nfn b() {}\n"
self.assertEqual(with_tests_of(planted, fixed), "fn a() {}\n\nfn b() {}\n")
def test_puts_each_planted_module_where_the_fixed_module_of_its_name_stands(self):
planted = "fn a() { 1 }\n#[cfg(test)]\nmod x { fn t() {} }\nfn b() {}\n#[cfg(test)]\nmod y { fn u() {} }\n"
fixed = "fn a() { 2 }\n#[cfg(test)]\nmod y { fn changed() {} }\n#[cfg(test)]\nmod x { fn changed() {} }\nfn c() {}\n"
self.assertEqual(with_tests_of(planted, fixed), "fn a() { 2 }\n#[cfg(test)]\nmod y { fn u() {} }\n#[cfg(test)]\nmod x { fn t() {} }\nfn c() {}\n")
def test_puts_in_planted_modules_whose_length_differs_from_the_fixed_ones(self):
planted = "#[cfg(test)]\nmod a { 1 }\n#[cfg(test)]\nmod b { 22 }\nfn code() {}\n"
fixed = "#[cfg(test)]\nmod a { 333 }\n#[cfg(test)]\nmod b { 4444444 }\nfn fixed() {}\n"
self.assertEqual(with_tests_of(planted, fixed), "#[cfg(test)]\nmod a { 1 }\n#[cfg(test)]\nmod b { 22 }\nfn fixed() {}\n")
def test_takes_the_file_as_fixed_where_the_planted_modules_cannot_be_told_apart(self):
self.assertEqual(with_tests_of("#[cfg(test)]\nmod tests {\n", "fixed {}"), "fixed {}")
def test_takes_the_planted_file_where_the_fixed_modules_cannot_be_told_apart(self):
self.assertEqual(with_tests_of(LIB, "fn broken() {"), LIB)
def test_takes_the_file_as_fixed_where_planted_has_no_module_and_the_fixed_modules_cannot_be_told_apart(self):
for planted in ("", "fn a() {}\n"):
with self.subTest(planted=planted):
self.assertEqual(with_tests_of(planted, "fn broken() {"), "fn broken() {")
if __name__ == "__main__":
unittest.main()
+49
View File
@@ -0,0 +1,49 @@
"""The copy of a tree that a mutation tool runs in."""
import os
import pathlib
import socket
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
from failure import Failure
from task_bench.bugs.scratch_copy import scratch_copy
class ScratchCopyTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
(self.top / "src").mkdir()
(self.top / "src/pick.ts").write_text("code", encoding="utf-8")
(self.top / ".hidden").write_text("kept", encoding="utf-8")
def test_copies_every_entry_of_the_tree_into_a_scratch_folder_in_it(self):
scratch, copy = scratch_copy(str(self.top))
self.assertRegex(scratch, rf"^{self.top}/\.mutate-changes-[^/]+$")
self.assertEqual(copy, f"{scratch}/copy")
self.assertEqual(sorted(str(path.relative_to(copy)) for path in pathlib.Path(copy).rglob("*")), [".hidden", "src", "src/pick.ts"])
self.assertEqual(pathlib.Path(copy, "src/pick.ts").read_text(encoding="utf-8"), "code")
def test_keeps_a_link_as_a_link(self):
(self.top / "linked").symlink_to("src/missing.ts")
_, copy = scratch_copy(str(self.top))
self.assertEqual(os.readlink(os.path.join(copy, "linked")), "src/missing.ts")
def test_fails_without_a_scratch_folder_left_where_the_tree_cannot_be_copied(self):
# A socket is an entry that no copy can read.
held = socket.socket(socket.AF_UNIX)
self.addCleanup(held.close)
held.bind(str(self.top / "held"))
found = scratch_copy(str(self.top))
self.assertIsInstance(found, Failure)
self.assertRegex(found.reason, rf"^could not copy {self.top} into {self.top}/\.mutate-changes-[^/]+: ")
self.assertEqual(sorted(path.name for path in self.top.iterdir()), [".hidden", "held", "src"])
def test_passes_on_that_no_scratch_folder_could_be_made(self):
found = scratch_copy(str(self.top / "missing"))
self.assertIsInstance(found, Failure)
self.assertIn("could not make a scratch folder in ", found.reason)
+273
View File
@@ -0,0 +1,273 @@
"""task-bench's TypeScript planter: which files Stryker mutates, how its report's mutants become lines and what `node --test`'s
output tells Haiku.
PICK's mutants and FAILING are what Stryker 10.1.1 and Node.js 24.19.0 wrote for a small project, each mutant cut down to the keys
the planter reads. The other mutants 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.typescript_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 = """export function pick(items: number[], floor: number): number {
let sum = 0;
for (const item of items) {
if (item >= floor) {
sum += item;
}
}
return sum;
}
export const tag = (n: number): string => "é😀" + (n > 1 ? "s" : "");
""".encode()
LINES = PICK.split(b"\n")
def reported(mutator: str, replacement: str, start: tuple[int, int], end: tuple[int, int], status: str = "Killed") -> dict:
return {"mutatorName": mutator, "replacement": replacement, "status": status, "location": {"start": {"line": start[0], "column": start[1]}, "end": {"line": end[0], "column": end[1]}}}
OPERATOR = reported("EqualityOperator", "item > floor", (4, 7), (4, 20))
BLOCK = reported("BlockStatement", "{}", (4, 22), (6, 4))
# Stryker counts a column in UTF-16 code units: the string before this condition holds one character of two units.
AFTER_WIDE_TEXT = reported("ConditionalExpression", "true", (11, 52), (11, 57))
# Three failed tests, the last two in a suite.
FAILING = """
> test
> node --test "src/**/*.test.ts"
✖ adds the items at or above the floor (1.654962ms)
▶ label
✖ names one (0.432991ms)
✖ names many (1.398742ms)
✖ label (2.262912ms)
ℹ tests 3
ℹ suites 1
ℹ pass 0
ℹ fail 3
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 164.424758
✖ failing tests:
test at src/pick.test.ts:5:1
✖ adds the items at or above the floor (1.654962ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
3 !== 5
at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)
at Test.runInAsyncScope (node:async_hooks:227:14)
at startSubtestAfterBootstrap (node:internal/test_runner/harness:387:17) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 3,
expected: 5,
operator: 'strictEqual',
diff: 'simple'
}
test at src/pick.test.ts:10:2
✖ names one (0.432991ms)
AssertionError [ERR_ASSERTION]: one is singular
'' !== 'one item'
at TestContext.<anonymous> (file:///w/src/pick.test.ts:11:10)
at Array.map (<anonymous>) {
generatedMessage: false,
code: 'ERR_ASSERTION',
actual: '',
expected: 'one item',
operator: 'strictEqual',
diff: 'simple'
}
test at src/pick.test.ts:13:2
✖ names many (1.398742ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
{
+ text: ''
- text: '3 items'
}
at TestContext.<anonymous> (file:///w/src/pick.test.ts:14:10) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: [Object],
expected: [Object],
operator: 'deepStrictEqual',
diff: 'simple'
}
"""
PASSING = "✔ adds the items at or above the floor (1.3494ms)\nℹ tests 1\nℹ pass 1\nℹ fail 0\n"
def failing(test: str, *lines: str) -> str:
return "\n".join([f"✖ {test} (1.2ms)", "ℹ fail 1", "", "✖ failing tests:", "", "test at src/pick.test.ts:5:1", f"✖ {test} (1.2ms)", *lines, ""])
class ChangedTest(unittest.TestCase):
def test_is_the_line_with_the_replacement_between_the_mutants_columns(self):
self.assertEqual(changed(OPERATOR["location"], "item > floor", LINES), (4, (b"\t\tif (item >= floor) {",), (b"\t\tif (item > floor) {",)))
def test_is_every_line_a_mutant_spans(self):
was = (b"\t\tif (item >= floor) {", b"\t\t\tsum += item;", b"\t\t}")
self.assertEqual(changed(BLOCK["location"], "{}", LINES), (4, was, (b"\t\tif (item >= floor) {}",)))
def test_a_replacement_of_more_lines_is_as_many_lines(self):
self.assertEqual(changed(OPERATOR["location"], "item >\n\t\t\tfloor", LINES), (4, (LINES[3],), (b"\t\tif (item >", b"\t\t\tfloor) {")))
def test_reaches_the_files_first_column_and_its_last_line(self):
self.assertEqual(changed(reported("M", "", (1, 1), (1, 8))["location"], "", LINES[:2]), (1, (LINES[0],), (LINES[0][7:],)))
self.assertEqual(changed(reported("M", "0", (2, 12), (2, 13))["location"], "0", LINES[:2]), (2, (LINES[1],), (LINES[1],)))
def test_a_mutant_that_replaces_no_code_adds_its_own(self):
self.assertEqual(changed(reported("M", "!", (4, 7), (4, 7))["location"], "!", LINES), (4, (LINES[3],), (b"\t\tif (!item >= floor) {",)))
def test_counts_a_column_in_utf_16_code_units(self):
now = 'export const tag = (n: number): string => "é😀" + (true ? "s" : "");'.encode()
self.assertEqual(changed(AFTER_WIDE_TEXT["location"], "true", LINES), (11, (LINES[10],), (now,)))
def test_is_none_where_the_file_holds_no_such_line_or_column(self):
for start, end in (((0, 1), (1, 2)), ((12, 1), (13, 1)), ((4, 7), (99, 1)), ((4, 40), (4, 41)), ((4, 0), (4, 3)), ((4, 9), (4, 7)), ((5, 1), (4, 3))):
with self.subTest(start=start, end=end):
self.assertIsNone(changed(reported("M", "x", start, end)["location"], "x", LINES))
def test_what_it_returns_plants_as_the_mutant(self):
line, was, now = changed(BLOCK["location"], "{}", LINES)
planted = mutated(PICK, Mutant("src/pick.ts", line, "a name", was, now))
self.assertEqual(planted, PICK.replace(b" {\n\t\t\tsum += item;\n\t\t}", b" {}"))
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
(self.top / "src").mkdir()
(self.top / "src/pick.ts").write_bytes(PICK)
self.ran: list[tuple[list[str], str, bytes]] = []
def stryker(self, files: dict[str, list[dict]] | None, code: int = 0, text: str | None = None):
"""A run that writes Stryker's report of these files' mutants where it runs, or none where files is None, and Stryker's
incremental file beside it."""
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd, pathlib.Path(cwd, "src/pick.ts").read_bytes()))
report = pathlib.Path(cwd, "reports/mutation/mutation.json")
report.parent.mkdir(parents=True, exist_ok=True)
pathlib.Path(cwd, "reports/stryker-incremental.json").write_text("every mutant", encoding="utf-8")
if files is not None:
report.write_text(text if text is not None else json.dumps({"files": {path: {"source": PICK.decode(), "mutants": mutants} for path, mutants in files.items()}}), encoding="utf-8")
return Ran(code, "the tool's last words\n")
return run
def test_runs_stryker_over_the_files_in_a_copy_of_the_tree_with_its_json_reporter(self):
killed_mutants(str(self.top), ["src/pick.ts", "src/last.ts"], self.stryker({}), 3)
(argv, cwd, source), = self.ran
self.assertEqual(argv, ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", "src/pick.ts,src/last.ts", "--concurrency", "3", "--reporters", "json"])
self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$")
self.assertEqual(source, PICK)
def test_names_a_file_whose_path_holds_a_globs_characters_by_a_glob_that_matches_it(self):
killed_mutants(str(self.top), ["app/[slug]/page.tsx", "src/pick.ts"], self.stryker({}), 1)
self.assertEqual(self.ran[0][0][6], "app/?slug?/page.tsx,src/pick.ts")
def test_is_each_killed_mutant_as_the_lines_it_changes(self):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR, BLOCK]}), 1)
self.assertEqual(found, [
Mutant("src/pick.ts", 4, "src/pick.ts:4:7 EqualityOperator", (LINES[3],), (b"\t\tif (item > floor) {",)),
Mutant("src/pick.ts", 4, "src/pick.ts:4:22 BlockStatement", tuple(LINES[3:6]), (b"\t\tif (item >= floor) {}",)),
])
def test_leaves_out_a_mutant_no_test_killed(self):
others = [reported("EqualityOperator", "item < floor", (4, 7), (4, 20), status) for status in ("Survived", "NoCoverage", "Timeout", "CompileError", "RuntimeError", "Ignored")]
self.assertEqual(killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": others}), 1), [])
def test_leaves_out_a_mutant_in_another_file_or_at_a_place_the_file_does_not_hold(self):
files = {"src/other.ts": [OPERATOR], "src/pick.ts": [reported("EqualityOperator", "x", (40, 1), (40, 2)), OPERATOR]}
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files), 1)
self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"])
def test_leaves_the_tree_as_it_was_whatever_stryker_wrote(self):
for files in ({"src/pick.ts": [OPERATOR]}, None):
killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, code=1), 1)
self.assertEqual(sorted(str(path.relative_to(self.top)) for path in self.top.rglob("*")), ["src", "src/pick.ts"])
def test_reads_the_report_of_a_run_that_finished_under_the_score_its_config_asks_for(self):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}, code=1), 1)
self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"])
def test_fails_where_stryker_exits_nonzero_without_a_report(self):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1)
self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words"))
def test_reads_no_report_that_the_tree_held_before_the_run(self):
(self.top / "reports/mutation").mkdir(parents=True)
(self.top / "reports/mutation/mutation.json").write_text(json.dumps({"files": {"src/pick.ts": {"source": PICK.decode(), "mutants": [OPERATOR]}}}), encoding="utf-8")
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(None, code=1), 1)
self.assertEqual(found, Failure("Stryker exited 1:\nthe tool's last words"))
def test_passes_on_a_run_that_could_not_start(self):
failure = Failure("npx could not start: No such file or directory")
self.assertIs(killed_mutants(str(self.top), ["src/pick.ts"], lambda argv, cwd: failure, 1), failure)
def test_fails_where_stryker_wrote_no_report_or_one_it_cannot_read(self):
for files, text in ((None, None), ({}, "not json"), ({}, '{"files": {"src/pick.ts": {"source": ""}}}'), ({}, '{"files": {"src/pick.ts": {"source": "", "mutants": [{"status": "Killed"}]}}}')):
with self.subTest(text=text):
found = killed_mutants(str(self.top), ["src/pick.ts"], self.stryker(files, text=text), 1)
self.assertIsInstance(found, Failure)
self.assertIn("could not read Stryker's report, reports/mutation/mutation.json in ", found.reason)
def test_fails_where_the_tree_cannot_be_copied(self):
found = killed_mutants(str(self.top / "missing"), ["src/pick.ts"], self.stryker({}), 1)
self.assertIsInstance(found, Failure)
self.assertEqual(self.ran, [])
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_error_without_the_tests_name_file_or_stack(self):
self.assertEqual(task_text(FAILING), "AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:\n3 !== 5")
def test_is_none_on_a_passing_run_or_output_that_lists_no_failing_test(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("SyntaxError: Unexpected token\n at node:internal/modules/esm/loader:1:1\n"))
self.assertIsNone(task_text(""))
def test_leaves_out_each_line_that_names_the_test_or_its_file(self):
output = failing("adds the items", " Error: adds the items failed", " got 3 in src/pick.test.ts", " want 5", " at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)")
self.assertEqual(task_text(output), "want 5")
def test_is_none_where_the_error_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(failing("adds the items", " Error: adds the items failed", " at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)")))
def test_takes_the_first_failed_test_that_has_an_error(self):
first = failing("adds", " Error: adds", " at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)")
second = "\n".join(["test at src/pick.test.ts:9:1", "✖ labels (0.4ms)", " Error: no label", " at label (file:///w/src/pick.ts:12:9)", ""])
self.assertEqual(task_text(first + "\n" + second), "Error: no label")
def test_an_error_without_a_stack_ends_at_its_test(self):
output = failing("adds", " 'a string was thrown'") + "\ntest at src/pick.test.ts:9:1\n✖ labels (0.4ms)\n Error: no label\n"
self.assertEqual(task_text(output), "'a string was thrown'")
def test_an_error_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("✖ failing tests:\n\ntest at a.test.ts:1:1\n✖ adds (1ms)\n Error: got 3\n want 5"), "Error: got 3\nwant 5")
def test_a_line_before_the_list_of_failing_tests_is_no_error(self):
self.assertIsNone(task_text("✖ adds (1ms)\n Error: printed by the test itself\nℹ fail 1\n\n✖ failing tests:\n\ntest at a.test.ts:1:1\n✖ adds (1ms)\n"))
if __name__ == "__main__":
unittest.main()
+113
View File
@@ -0,0 +1,113 @@
"""The bugs task-bench plants in TypeScript and JavaScript: Stryker's killed mutants, re-applied from its JSON report, and the error
`node --test` prints when a test fails on one."""
import json
import pathlib
import re
from mutate_changes.tool_process import failed, remove, Run
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.bugs.planted_mutant import Mutant
from task_bench.bugs.scratch_copy import scratch_copy
# Where Stryker 10.1.1's json reporter writes, from the folder it runs in. Only the project's own Stryker config can set another
# path, so the planter reads this one.
REPORT = "reports/mutation/mutation.json"
# The heading of the list of failed tests that `node --test`'s spec reporter prints. Each test in it has its error.
FAILING_TESTS = "✖ failing tests:"
# Where a listed test stands, the line before its name: `test at src/pick.test.ts:5:1`.
TEST_PLACE = re.compile(r"^test at \S+:\d+:\d+$")
# A listed test's name and how long it ran: `✖ adds the items (1.654962ms)`.
TEST = re.compile(r"^✖ (.+) \(\d+(?:\.\d+)?ms\)$")
# A line of the error's stack, which follows its message: ` at TestContext.<anonymous> (file:///w/src/pick.test.ts:6:9)`.
STACK = re.compile(r"^\s+at ")
TEST_FILE = re.compile(r"\.(?:spec|test)\.[cm]?[jt]sx?\b")
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 Stryker finds them in a copy of that tree. One at a place
its file doesn't hold is left out.
Stryker runs at the copy's top, with the Stryker config and the package.json there."""
copied = scratch_copy(top)
if isinstance(copied, Failure):
return copied
scratch, copy = copied
try:
mutate = ",".join(in_diff_tools.glob_escaped(path) for path in files)
report = pathlib.Path(copy, REPORT)
# A report the project tracks would otherwise stand for this run's.
report.unlink(missing_ok=True)
ran = run([*in_diff_tools.STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "json"], copy)
# Stryker exits 1 too where it finished under the score the project's config sets as `thresholds.break`, which the files'
# score may be. Only a run that finished writes the report.
if isinstance(ran, Failure) or ran.code and not report.is_file():
return ran if isinstance(ran, Failure) else failed("Stryker", ran)
reported = json.loads(report.read_bytes())["files"]
return [mutant for path in files if path in reported for mutant in file_mutants(path, reported[path])]
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"could not read Stryker's report, {REPORT} in {copy}: {failure}")
finally:
remove(scratch)
def file_mutants(path: str, reported: dict) -> list[Mutant]:
"""The killed mutants of the file at path, from what Stryker's report holds of it: the source Stryker read, and each mutant."""
lines = reported["source"].encode().split(b"\n")
killed = [mutant for mutant in reported["mutants"] if mutant["status"] == "Killed"]
found = [(mutant, changed(mutant["location"], mutant["replacement"], lines)) for mutant in killed]
return [Mutant(path, lines_changed[0], f"{path}:{mutant['location']['start']['line']}:{mutant['location']['start']['column']} {mutant['mutatorName']}", lines_changed[1], lines_changed[2]) for mutant, lines_changed in found if lines_changed]
def changed(location: dict, replacement: str, lines: list[bytes]) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
"""The lines a mutant changes; `lines` are its file's. Stryker's report gives the code the mutant puts in, and where the code it
replaces starts and ends: each a line and a column, both from 1, the end's column the first one after that code. Returned are
the number of the first line, those lines as the file has them, and what the mutant has in their place. None where the file
holds no such lines or columns."""
start, end = location["start"], location["end"]
if not 1 <= start["line"] <= end["line"] <= len(lines) or (start["line"], start["column"]) > (end["line"], end["column"]):
return None
before, after = cut(lines[start["line"] - 1], start["column"]), cut(lines[end["line"] - 1], end["column"])
if before is None or after is None:
return None
now = before[0] + replacement.encode() + after[1]
return start["line"], tuple(lines[start["line"] - 1:end["line"]]), tuple(now.split(b"\n"))
def cut(line: bytes, column: int) -> tuple[bytes, bytes] | None:
"""A line's bytes before a column and from it on. Stryker counts a column in UTF-16 code units, as JavaScript counts a string's
length, so a character outside the Basic Multilingual Plane is two columns. None where the line holds no such column, or is not
UTF-8."""
try:
units = line.decode().encode("utf-16-le")
at = 2 * (column - 1)
if not 0 <= at <= len(units):
return None
return units[:at].decode("utf-16-le").encode(), units[at:].decode("utf-16-le").encode()
except UnicodeError:
return None
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the error of the first test that has an error in `node --test`'s list of failing
tests, without the test's name or file and without the stack, so it says what goes wrong and not which test shows it.
None where the output lists no failing test with an error, as on a passing run, a file that fails to load or a reporter other
than spec, or where each error only names its test."""
listed = f"\n{output}".partition(f"\n{FAILING_TESTS}\n")[2]
errors: list[tuple[str, list[str]]] = []
within = False
for line in listed.splitlines():
if test := TEST.match(line):
errors.append((test[1], []))
within = True
elif TEST_PLACE.match(line) or STACK.match(line):
within = False
elif within:
errors[-1][1].append(line.strip())
kept = (kept_lines(test, error) for test, error in errors)
return next(("\n".join(lines) for lines in kept if lines), None)
def kept_lines(test: str, error: list[str]) -> list[str]:
return [text for text in error if text and test not in text and not TEST_FILE.search(text)]