Answer stability round 1: 0 🔴, 5 🟡 (0 misread); run both tools in a scratch copy, read Infection's two sources, end PHPUnit's list, spell glob characters
This commit is contained in:
+41
-44
@@ -1,17 +1,21 @@
|
||||
"""The bugs task-bench plants in PHP: Infection's killed mutants, each read from the diff in its JSON log, and the message PHPUnit
|
||||
prints when a test fails on one."""
|
||||
"""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 os
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from mutate_changes.tool_process import failed, remove, Run, scratch_folder
|
||||
from mutate_changes.tool_process import failed, remove, Run
|
||||
from failure import Failure
|
||||
from mutate_changes import in_diff_tools
|
||||
from task_bench.planted_mutant import Mutant
|
||||
from task_bench.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
|
||||
@@ -21,65 +25,56 @@ 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 there. One whose diff doesn't fit the
|
||||
source Infection logged with it is left out.
|
||||
"""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 top, with the Infection config and the vendor folder there."""
|
||||
scratch = scratch_folder(top)
|
||||
if isinstance(scratch, Failure):
|
||||
return scratch
|
||||
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:
|
||||
log = pathlib.Path(scratch, "log.json")
|
||||
ran = run([in_diff_tools.INFECTION, f"--filter={','.join(files)}", f"--threads={jobs}", "--no-progress", f"--logger-json={os.path.relpath(log, top)}"], top)
|
||||
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"], logged["diff"]) for logged in json.loads(log.read_bytes())["killed"]]
|
||||
return [mutant for mutator, diff in killed if (mutant := planted(mutator, diff, files))]
|
||||
except (OSError, ValueError, KeyError, TypeError) as failure:
|
||||
return Failure(f"could not read Infection's log in {scratch}: {failure}")
|
||||
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, diff: str, 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 `changed` finds no lines.
|
||||
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, which is another than top's where a container ran it. So the file is
|
||||
the longest of `files` that ends that path."""
|
||||
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
|
||||
start = mutator["originalStartLine"]
|
||||
found = changed(diff, mutator["originalSourceCode"].split("\n"), start)
|
||||
return Mutant(path, found[0], f"{path}:{start} {mutator['mutatorName']}", found[1], found[2]) if found else 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(diff: str, lines: list[str], start: int) -> tuple[int, tuple[bytes, ...], tuple[bytes, ...]] | None:
|
||||
"""The lines a mutant changes, from the diff Infection 0.35.12 logs for it: the number of the first, from 1, those lines as the
|
||||
file has them, and what the mutant has in their place. An unchanged line between two changed ones is in both.
|
||||
|
||||
The diff's one hunk gives no line numbers. So the hunk's lines are found among `lines`, the file's, around `start`, the line
|
||||
Infection logs as the one the mutated code starts on. None where the diff holds no change, or where its lines stand around
|
||||
`start` nowhere or more than once, as do those of a diff with a second hunk."""
|
||||
hunk = diff.partition("@@ @@\n")[2].split("\n")
|
||||
# An empty line of the file is an empty line of the hunk; any other line opens with a space, a minus or a plus.
|
||||
body = [(line[:1] if line[:1] in ("-", "+") else " ", line[1:]) for line in hunk]
|
||||
at = [index for index, (kind, _) in enumerate(body) if kind != " "]
|
||||
old = [text for kind, text in body if kind != "+"]
|
||||
held = [first for first in range(max(start - len(old), 0), start) if lines[first:first + len(old)] == old]
|
||||
if not at or len(held) != 1:
|
||||
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
|
||||
span = body[at[0]:at[-1] + 1]
|
||||
was = tuple(text.encode() for kind, text in span if kind != "+")
|
||||
now = tuple(text.encode() for kind, text in span if kind != "-")
|
||||
# Each line of the hunk before the first changed one is a line of the file.
|
||||
return held[0] + at[0] + 1, was, now
|
||||
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 with one 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.
|
||||
"""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."""
|
||||
@@ -88,6 +83,8 @@ def task_text(output: str) -> str | None:
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user