"""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)]