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:
@@ -2,6 +2,7 @@
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from mutate_changes.changed_lines import by_folder, label, runs
|
||||
@@ -14,7 +15,7 @@ CARGO_FINISHED = frozenset({0, 2, 3})
|
||||
CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable")
|
||||
INFECTION = "vendor/bin/infection" # the project's own, as Composer installs it
|
||||
# npx runs the project's own @stryker-mutator/core, else one an earlier npx run cached, and installs none.
|
||||
STRYKER = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run"]
|
||||
STRYKER_RUN = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run"]
|
||||
GREMLINS_UNKILLED = frozenset({"LIVED", "NOT COVERED"})
|
||||
# What Gremlins v0.6.0 needs of the diff it reads from git: one run of lines per hunk is all it mutates, so a hunk holds the changed
|
||||
# lines and none around them, nor a neighbouring change; it takes each file's path after a b/; and it reads no colour codes. A user's git
|
||||
@@ -117,6 +118,13 @@ def outcome_lines(path: pathlib.Path) -> list[str]:
|
||||
|
||||
# Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't
|
||||
# tell from a run that broke, so either fails the run.
|
||||
def glob_escaped(path: str) -> str:
|
||||
"""A path as a glob that matches it. Stryker 10.1.1 reads each entry of --mutate as a glob, in which `app/[slug]/page.tsx`
|
||||
matches `app/s/page.tsx` and not the file of that name. It reads a backslash as a slash, so no character can be escaped: a `?`
|
||||
stands for each one a glob gives a meaning, and matches it."""
|
||||
return re.sub(r"[][!()*+@{}]", "?", path)
|
||||
|
||||
|
||||
def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure:
|
||||
"""For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line
|
||||
naming the files with no package.json above them, if any.
|
||||
@@ -129,8 +137,8 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in
|
||||
if not os.path.isfile(os.path.join(top, folder, "package.json")):
|
||||
unplaced = sorted(files)
|
||||
continue
|
||||
mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines))
|
||||
ran = run([*STRYKER, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder))
|
||||
mutate = ",".join(f"{glob_escaped(path)}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines))
|
||||
ran = run([*STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder))
|
||||
if isinstance(ran, Failure) or ran.code:
|
||||
return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran)
|
||||
report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()])
|
||||
|
||||
@@ -17,12 +17,12 @@ from mutate_changes.changed_lines import added_lines, by_folder, not_mutated, ru
|
||||
from mutate_changes.mutmut_tool import copy_files, Ended, Folder, mutate_folder, NO_MUTANT, reported
|
||||
from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, mutant_globs, mutated_lines, named, statuses
|
||||
from failure import Failure
|
||||
from mutate_changes.in_diff_tools import glob_escaped, run_stryker, with_plain_git_diff
|
||||
from mutate_changes.bare_imports import imported_by_file_name
|
||||
from test_env import isolated_env
|
||||
from mutate_changes.mutmut_setup import left_out, mutmut_config
|
||||
from mutate_changes import main
|
||||
from mutate_changes.tool_process import Ran, run_tool, scratch_folder
|
||||
from mutate_changes.in_diff_tools import with_plain_git_diff
|
||||
|
||||
SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n"
|
||||
# The shape of the file mutmut 3 writes under mutants/: the original of each function and its mutants, with the original's lines.
|
||||
@@ -163,6 +163,18 @@ class InDiffTools(unittest.TestCase):
|
||||
self.assertEqual((env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"], env["GIT_CONFIG_KEY_6"], "GIT_CONFIG_KEY_7" in env), ("7", "diff.context", "diff.interHunkContext", False))
|
||||
|
||||
|
||||
def test_a_path_goes_to_stryker_with_a_question_mark_for_each_character_a_glob_gives_a_meaning(self):
|
||||
self.assertEqual(glob_escaped("app/[slug]/(shop)/{a}/b!c*d+e@f.tsx"), "app/?slug?/?shop?/?a?/b?c?d?e?f.tsx")
|
||||
self.assertEqual(glob_escaped("src/pick-one_two.test.ts"), "src/pick-one_two.test.ts")
|
||||
|
||||
def test_stryker_is_handed_a_changed_file_whose_path_holds_a_globs_characters_as_a_glob_that_matches_it(self):
|
||||
with tempfile.TemporaryDirectory() as top:
|
||||
pathlib.Path(top, "package.json").write_text("{}")
|
||||
ran: list[list[str]] = []
|
||||
run_stryker(top, {"app/[slug]/page.tsx": frozenset({3, 4})}, lambda argv, cwd: ran.append(argv) or Ran(0, ""), 1)
|
||||
self.assertEqual(ran[0][5:7], ["--mutate", "app/?slug?/page.tsx:3-4"])
|
||||
|
||||
|
||||
class MutmutSetup(unittest.TestCase):
|
||||
def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self):
|
||||
for existing in ("", "[mutmut]\nsource_paths = old.py\nalso_copy = old\n"):
|
||||
|
||||
+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
|
||||
|
||||
@@ -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=lambda folder, names: [os.path.basename(scratch)] if folder == top else [])
|
||||
except OSError as failure:
|
||||
remove(scratch)
|
||||
return Failure(f"could not copy {top} into {scratch}: {failure}")
|
||||
return scratch, copy
|
||||
@@ -1,7 +1,7 @@
|
||||
"""task-bench's PHP planter: which files Infection mutates, how its log's diffs become mutants and what PHPUnit's output tells Haiku.
|
||||
"""task-bench's PHP planter: which files Infection mutates, how its log's mutants become lines and what PHPUnit's output tells Haiku.
|
||||
|
||||
PICK's diffs and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13, and each logged
|
||||
mutant holds the keys the planter reads. The other diffs and outputs are made up in the same form."""
|
||||
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
|
||||
@@ -42,29 +42,25 @@ final class Pick
|
||||
}
|
||||
"""
|
||||
LINES = PICK.split("\n")
|
||||
OPERATOR_DIFF = "@@ @@\n \t{\n \t\t$sum = 0;\n \t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n+\t\t\tif ($item > $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n \t\t}"
|
||||
|
||||
|
||||
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_DIFF = (
|
||||
"@@ @@\n \tpublic static function sum(array $items, int $floor): int\n \t{\n \t\t$sum = 0;\n-\t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n"
|
||||
"+\t\tforeach ([] as $item) {\n+ if ($item >= $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n-\t\t}\n+ }\n \t\treturn $sum;\n \t}"
|
||||
)
|
||||
TERNARY_DIFF = (
|
||||
"@@ @@\n\n \tpublic static function label(int $count): string\n \t{\n-\t\treturn $count === 1\n-\t\t\t? 'one item'\n-\t\t\t: $count . ' items';\n"
|
||||
"+\t\treturn $count === 1 ? $count . ' items' : 'one item';\n \t}\n }"
|
||||
)
|
||||
# An empty line of the file stands in the diff without the space that opens an unchanged line.
|
||||
VISIBILITY_DIFF = (
|
||||
"@@ @@\n \t\treturn $sum;\n \t}\n\n-\tpublic static function label(int $count): string\n+\tprotected static function label(int $count): string\n"
|
||||
" \t{\n \t\treturn $count === 1\n \t\t\t? 'one item'"
|
||||
)
|
||||
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, diff: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict:
|
||||
return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "originalFilePath": path, "originalStartLine": line}, "diff": diff}
|
||||
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}}
|
||||
|
||||
|
||||
# Three failed tests.
|
||||
FAILING = """PHPUnit 12.5.45 by Sebastian Bergmann and contributors.
|
||||
|
||||
Runtime: PHP 8.5.13
|
||||
@@ -116,45 +112,36 @@ def failing(test: str, *lines: str) -> str:
|
||||
|
||||
class ChangedTest(unittest.TestCase):
|
||||
def test_is_the_line_an_operator_mutant_changes(self):
|
||||
self.assertEqual(changed(OPERATOR_DIFF, LINES, 12), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW))
|
||||
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(FOREACH_DIFF, LINES, 11), (11, was, now))
|
||||
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(TERNARY_DIFF, LINES, 21), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)))
|
||||
self.assertEqual(changed(PICK, TERNARY), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)))
|
||||
|
||||
def test_reads_an_empty_line_of_the_diff_as_an_unchanged_empty_line(self):
|
||||
self.assertEqual(changed(VISIBILITY_DIFF, LINES, 19), (19, (b"\tpublic static function label(int $count): string",), (b"\tprotected static function label(int $count): string",)))
|
||||
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_finds_the_lines_around_the_mutants_start_line_where_the_file_holds_them_twice(self):
|
||||
twice = ["\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}", "", "\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}"]
|
||||
diff = "@@ @@\n \t\t$a = 1;\n-\t\treturn $a >= 2;\n+\t\treturn $a > 2;\n \t}"
|
||||
self.assertEqual(changed(diff, twice, 2), (2, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",)))
|
||||
self.assertEqual(changed(diff, twice, 6), (6, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",)))
|
||||
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_is_none_where_the_diffs_lines_do_not_stand_around_the_start_line(self):
|
||||
self.assertIsNone(changed(OPERATOR_DIFF, LINES, 20))
|
||||
self.assertIsNone(changed(OPERATOR_DIFF.replace("$sum = 0", "$sum = 1"), LINES, 12))
|
||||
self.assertIsNone(changed(OPERATOR_DIFF, LINES, 0))
|
||||
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_diff_holds_no_change_or_no_hunk(self):
|
||||
self.assertIsNone(changed("@@ @@\n \t{\n \t\t$sum = 0;", LINES, 10))
|
||||
self.assertIsNone(changed("", LINES, 10))
|
||||
|
||||
def test_is_none_where_the_diff_holds_a_second_hunk(self):
|
||||
self.assertIsNone(changed(OPERATOR_DIFF + "\n@@ @@\n \t\t\t}\n-\t\t}\n+\t\t};\n \t\treturn $sum;", LINES, 15))
|
||||
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 diff, start in ((OPERATOR_DIFF, 12), (FOREACH_DIFF, 11), (TERNARY_DIFF, 21), (VISIBILITY_DIFF, 19)):
|
||||
with self.subTest(start=start):
|
||||
line, was, now = changed(diff, LINES, start)
|
||||
planted = mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now))
|
||||
self.assertEqual(planted.split(b"\n")[line - 1], now[0])
|
||||
self.assertEqual(len(planted.split(b"\n")), len(LINES) - len(was) + len(now))
|
||||
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):
|
||||
@@ -162,28 +149,30 @@ class KilledMutantsTest(unittest.TestCase):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.top = pathlib.Path(folder.name)
|
||||
self.ran: list[tuple[list[str], str]] = []
|
||||
(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."""
|
||||
"""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))
|
||||
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_at_the_top_with_a_json_log_in_a_scratch_folder(self):
|
||||
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), = self.ran
|
||||
self.assertEqual(cwd, str(self.top))
|
||||
self.assertEqual(argv[:4], ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress"])
|
||||
self.assertRegex(argv[4], r"^--logger-json=\.mutate-changes-[^/]+/log\.json$")
|
||||
self.assertEqual(len(argv), 5)
|
||||
(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_DIFF), logged("Ternary", 21, TERNARY_DIFF)], "escaped": [logged("PublicVisibility", 19, VISIBILITY_DIFF)]}
|
||||
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, [
|
||||
@@ -191,19 +180,23 @@ class KilledMutantsTest(unittest.TestCase):
|
||||
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_DIFF, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]}
|
||||
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_whose_diff_does_not_fit_its_source(self):
|
||||
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, source="<?php\n")]}
|
||||
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_removes_the_scratch_folder(self):
|
||||
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(list(self.top.iterdir()), [])
|
||||
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)
|
||||
@@ -214,11 +207,17 @@ class KilledMutantsTest(unittest.TestCase):
|
||||
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):
|
||||
for log in (None, "not json", "{}", '{"killed": [{"diff": ""}]}', '{"killed": [7]}'):
|
||||
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 in ", found.reason)
|
||||
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):
|
||||
@@ -251,6 +250,17 @@ class TaskTextTest(unittest.TestCase):
|
||||
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")
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
"""The copy of a tree that a mutation tool runs in."""
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from task_bench.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_copies_a_folder_below_the_top_that_has_the_scratch_folders_name(self):
|
||||
first, _ = scratch_copy(str(self.top))
|
||||
(self.top / "src" / os.path.basename(first)).mkdir()
|
||||
_, copy = scratch_copy(str(self.top))
|
||||
self.assertTrue(os.path.isdir(os.path.join(copy, "src", os.path.basename(first))))
|
||||
|
||||
def test_fails_without_a_scratch_folder_left_where_the_tree_cannot_be_copied(self):
|
||||
with unittest.mock.patch("shutil.copytree", side_effect=OSError("No space left on device")):
|
||||
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-[^/]+: No space left on device$")
|
||||
self.assertEqual(sorted(path.name for path in self.top.iterdir()), [".hidden", "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)
|
||||
@@ -1,10 +1,8 @@
|
||||
"""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, the mutants with the keys the
|
||||
planter reads. The other mutants and outputs are made up in the same form."""
|
||||
import contextlib
|
||||
import io
|
||||
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
|
||||
@@ -159,23 +157,33 @@ class KilledMutantsTest(unittest.TestCase):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.top = pathlib.Path(folder.name)
|
||||
self.ran: list[tuple[list[str], str]] = []
|
||||
(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, or none where files is 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))
|
||||
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)
|
||||
pathlib.Path(cwd, "reports/stryker-incremental.json").write_text("every mutant", encoding="utf-8")
|
||||
if files is not None:
|
||||
report = self.top / "reports/mutation/mutation.json"
|
||||
report.parent.mkdir(parents=True)
|
||||
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_at_the_top_with_its_json_reporter(self):
|
||||
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)
|
||||
expected = ["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", "src/pick.ts,src/last.ts", "--concurrency", "3", "--reporters", "json"]
|
||||
self.assertEqual(self.ran, [(expected, str(self.top))])
|
||||
(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)
|
||||
@@ -193,29 +201,18 @@ class KilledMutantsTest(unittest.TestCase):
|
||||
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_removes_the_report_and_the_folders_stryker_made_for_it(self):
|
||||
killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}), 1)
|
||||
self.assertEqual(list(self.top.iterdir()), [])
|
||||
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_keeps_a_reports_folder_that_holds_something_else(self):
|
||||
(self.top / "reports").mkdir()
|
||||
(self.top / "reports/coverage.txt").write_text("kept", encoding="utf-8")
|
||||
killed_mutants(str(self.top), ["src/pick.ts"], self.stryker({"src/pick.ts": [OPERATOR]}), 1)
|
||||
self.assertEqual(sorted(str(path.relative_to(self.top)) for path in (self.top / "reports").rglob("*")), ["reports/coverage.txt"])
|
||||
|
||||
def test_fails_where_stryker_exits_nonzero_and_still_removes_the_report(self):
|
||||
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(found, Failure("Stryker exited 1:\nthe tool's last words"))
|
||||
self.assertFalse((self.top / "reports").exists())
|
||||
self.assertEqual([mutant.name for mutant in found], ["src/pick.ts:4:7 EqualityOperator"])
|
||||
|
||||
def test_says_on_stderr_only_that_it_could_not_remove_a_report(self):
|
||||
def blocked(argv: list[str], cwd: str) -> Ran:
|
||||
(self.top / "reports/mutation/mutation.json/held").mkdir(parents=True)
|
||||
return Ran(0, "")
|
||||
for run, said in ((self.stryker(None), ""), (blocked, f"could not remove {self.top}/reports/mutation/mutation.json: ")):
|
||||
with self.subTest(said=said), contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsInstance(killed_mutants(str(self.top), ["src/pick.ts"], run, 1), Failure)
|
||||
self.assertEqual(stderr.getvalue()[:len(said) or None], said)
|
||||
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_passes_on_a_run_that_could_not_start(self):
|
||||
failure = Failure("npx could not start: No such file or directory")
|
||||
@@ -226,7 +223,12 @@ class KilledMutantsTest(unittest.TestCase):
|
||||
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 at reports/mutation/mutation.json", found.reason)
|
||||
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):
|
||||
|
||||
@@ -1,20 +1,19 @@
|
||||
"""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 contextlib
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
from mutate_changes.tool_process import failed, Run
|
||||
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 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 `node --test`'s list of the failed tests, as its spec reporter prints it, each with its error.
|
||||
# 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+$")
|
||||
@@ -26,33 +25,28 @@ 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 there. One at a place its file doesn't
|
||||
hold is left out.
|
||||
"""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 top, with the Stryker config and the package.json there."""
|
||||
report = pathlib.Path(top, REPORT)
|
||||
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:
|
||||
ran = run([*in_diff_tools.STRYKER, "--mutate", ",".join(files), "--concurrency", str(jobs), "--reporters", "json"], top)
|
||||
if isinstance(ran, Failure) or ran.code:
|
||||
mutate = ",".join(in_diff_tools.glob_escaped(path) for path in files)
|
||||
ran = run([*in_diff_tools.STRYKER_RUN, "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "json"], copy)
|
||||
report = pathlib.Path(copy, REPORT)
|
||||
# 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 at {REPORT}: {failure}")
|
||||
return Failure(f"could not read Stryker's report, {REPORT} in {copy}: {failure}")
|
||||
finally:
|
||||
remove_report(report)
|
||||
|
||||
|
||||
def remove_report(report: pathlib.Path) -> None:
|
||||
"""Remove Stryker's report, and the two folders Stryker made for it where they hold nothing else. Where the report can't be
|
||||
removed, say so on stderr: it tells where each mutant is, and a bug's tree is a copy of this one."""
|
||||
try:
|
||||
report.unlink(missing_ok=True)
|
||||
except OSError as failure:
|
||||
print(f"could not remove {report}: {failure}", file=sys.stderr)
|
||||
with contextlib.suppress(OSError):
|
||||
report.parent.rmdir()
|
||||
report.parent.parent.rmdir()
|
||||
remove(scratch)
|
||||
|
||||
|
||||
def file_mutants(path: str, reported: dict) -> list[Mutant]:
|
||||
@@ -93,7 +87,7 @@ def cut(line: bytes, column: int) -> tuple[bytes, bytes] | None:
|
||||
|
||||
|
||||
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 `node --test`'s list of failing
|
||||
"""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
|
||||
|
||||
Reference in New Issue
Block a user