106 lines
5.7 KiB
Python
106 lines
5.7 KiB
Python
"""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."""
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
|
|
from failure import Failure
|
|
from mutate_changes import in_diff_tools
|
|
from task_bench.planted_mutant import Mutant
|
|
from mutate_changes.tool_process import failed, remove, Run, scratch_folder
|
|
|
|
# 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?:$")
|
|
# 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 there. One whose diff doesn't fit the
|
|
source Infection logged with it is left out.
|
|
|
|
Infection runs at top, with the Infection config and the vendor folder there."""
|
|
scratch = scratch_folder(top)
|
|
if isinstance(scratch, Failure):
|
|
return scratch
|
|
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)
|
|
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}")
|
|
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.
|
|
|
|
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."""
|
|
logged = mutator["originalFilePath"]
|
|
path = max((path for path in files if logged == path or logged.endswith(f"/{path}")), key=len, default=None)
|
|
start = mutator["originalStartLine"]
|
|
found = changed(diff, mutator["originalSourceCode"].split("\n"), start) if path else None
|
|
return Mutant(path, found[0], f"{path}:{start} {mutator['mutatorName']}", found[1], found[2]) if path and 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."""
|
|
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:
|
|
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
|
|
|
|
|
|
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.
|
|
|
|
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 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)]
|