Compare commits

...

3 Commits

Author SHA1 Message Date
lilleman 632023ed21 Sort the two planters' imports
CI / tests (pull_request) Successful in 5m35s
2026-11-26 10:42:42 +01:00
lilleman ffe2048b73 Plant task-bench's bugs in TypeScript and PHP, from Stryker's and Infection's killed mutants
CI / tests (pull_request) Has been cancelled
2026-11-26 10:39:36 +01:00
lilleman 48270c0439 Record the reading cost 2026-11-26 10:39:36 +01:00
12 changed files with 773 additions and 24 deletions
+2 -2
View File
@@ -236,7 +236,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, Python and Rust files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go, PHP, Python, Rust, TypeScript and JavaScript files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--tasks shipped-features` it has Haiku rebuild features the project shipped: it takes each one's change out of the code, tells Haiku the tagline of the plan item, and checks the build with the tests that change holds. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
@@ -286,7 +286,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, Python and Rust files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go, PHP, Python, Rust, TypeScript and JavaScript files, or takes the project's bench features, its data sources or the features its history shipped, and has Haiku fix, build or add them in containers.
- `test_env.py` serves the tests.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
+6 -4
View File
@@ -12,6 +12,9 @@ from git_cli.git_repo import Git
# cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out.
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"]
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
@@ -118,8 +121,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in
"""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.
Stryker runs in the nearest folder above each file that holds a package.json. npx runs the project's own @stryker-mutator/core, else
one an earlier npx run cached, and installs none."""
Stryker runs in the nearest folder above each file that holds a package.json."""
report: list[str] = []
unplaced: list[str] = []
for folder, files in sorted(by_folder(top, changed, ("package.json",)).items()):
@@ -128,7 +130,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in
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(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder))
ran = run([*STRYKER, "--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()])
@@ -137,7 +139,7 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: in
def run_infection(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure:
"""A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base."""
ran = run(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top)
ran = run([INFECTION, "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output("Infection", ran)
return ["Infection in the checkout's top:", *ran.output.splitlines()]
+17 -12
View File
@@ -15,13 +15,16 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
- Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places`
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, mutmut 3 over
the Python files, as `mutmut run`, and cargo-mutants over the Rust files, as `cargo mutants`. No other language is planted
in so far. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
the Python files, as `mutmut run`, cargo-mutants over the Rust files, as `cargo mutants`, Infection over the PHP files, as
`vendor/bin/infection`, and Stryker over the TypeScript and JavaScript files, as `npx stryker run`. No other language is
planted in so far. Infection and Stryker run at the copy's top, with the project's config for the tool there. Stryker's json
reporter must write where it does by default, `reports/mutation/mutation.json`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where,
planted at each side, a test fails and prints a message that says more than the test's name. The bench reads that message
from `go test`'s output for a Go file, from pytest's for a Python file and from `cargo test`'s for a Rust file, so --test must
run the tests of each language the places name, with that runner: pytest as it prints by default, or with --tb=short, and
`cargo test` without --nocapture. Any other mutant is passed over, so a change to the very lines of a bug is not benched.
from `go test`'s output for a Go file, from pytest's for a Python file, from `cargo test`'s for a Rust file, from PHPUnit's
for a PHP file and from `node --test`'s for a TypeScript or JavaScript file, so --test must run the tests of each language the
places name, with that runner: pytest as it prints by default, or with --tb=short, `cargo test` without --nocapture, PHPUnit
as it prints by default, and `node --test` with its spec reporter. Any other mutant is passed over, so a change to the very lines of a bug is not benched.
- Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's
tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p
--strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every
@@ -40,9 +43,10 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at
the copy's top, with no network, so the image must hold what the tests would otherwise download.
--prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs `<prefix> "$@"` with
the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins and
cargo-mutants run in the copy of the base, and mutmut in a copy of the folder there that holds its settings; $PWD is the folder
the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut` or the `cargo` on the host's PATH. For example,
the tool's command as "$@", such as `gremlins unleash ...`, `mutmut run ...` or `cargo mutants ...`. Gremlins,
cargo-mutants, Infection and Stryker run in the copy of the base, and mutmut in a copy of the folder there that holds its settings;
$PWD is the folder the tool runs in. Without --prefix, the bench runs the `gremlins`, the `mutmut`, the `cargo` or the `npx` on
the host's PATH, or the copy's own `vendor/bin/infection`. For example,
for Go, for Python and then for Rust:
docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
@@ -54,7 +58,8 @@ for Go, for Python and then for Rust:
rust:1.100.0 sh -c 'cargo install --quiet --locked cargo-mutants@27.1.0 && exec "$@"' sh
Where the places name files in more than one language, the one prefix gets each tool's command, Gremlins' first and
cargo-mutants' last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`, `mutmut` or `cargo`, as here for Go
Stryker's last, and a tool it cannot run fails the bench. Such a prefix picks the tool by "$1", which is `gremlins`,
`vendor/bin/infection`, `mutmut`, `cargo` or `npx`, as here for Go
and Python:
sh -c 'case "$1" in
@@ -152,7 +157,7 @@ not, unless a bench or a gather is using it. So gather a bench before the next o
Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole
number from 1, a --tasks that is none of bugs, features, data-sources and shipped-features, or no token; and where git, docker or a mutation tool
fails, the seats' places don't name any Go, Python or Rust file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
fails, the seats' places don't name any file in a language the bench plants bugs in, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no
`bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable
file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts.
@@ -359,11 +364,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
"""What plans a bench of bugs: of the mutants the tests kill in the Go, Python and Rust files of the tree at base that hold a place
"""What plans a bench of bugs: of the mutants the tests kill in the files of the tree at base that are in a language of plant's LANGUAGES and hold a place
in places, those --seed draws first become bugs, until --bugs of them have."""
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
if not files:
return Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.")
return Failure("The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(base, files, run, CPUS_PER_SLOT)
return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"]))
+105
View File
@@ -0,0 +1,105 @@
"""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 mutate_changes.tool_process import failed, remove, Run, scratch_folder
from failure import Failure
from mutate_changes import in_diff_tools
from task_bench.planted_mutant import Mutant
# 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)]
+5 -2
View File
@@ -6,8 +6,8 @@ import re
import typing
from failure import Failure
from task_bench import go_bugs, python_bugs, rust_bugs
from mutate_changes.changed_lines import is_test
from task_bench import go_bugs, php_bugs, python_bugs, rust_bugs, typescript_bugs
from mutate_changes.changed_lines import is_test, STRYKER
from task_bench.planted_mutant import Mutant
from mutate_changes.tool_process import Run
@@ -28,8 +28,11 @@ class Language(typing.NamedTuple):
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),
)
+2 -1
View File
@@ -11,7 +11,8 @@ 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' column and mutator, or mutmut's name. cargo-mutants' own name for a mutant holds all of it."""
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
+259
View File
@@ -0,0 +1,259 @@
"""task-bench's PHP planter: which files Infection mutates, how its log's diffs become mutants 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."""
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.php_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.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")
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}"
# 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'"
)
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}
# Three failed tests.
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(OPERATOR_DIFF, LINES, 12), (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))
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';",)))
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_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_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_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_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))
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
self.ran: list[tuple[list[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."""
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
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):
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)
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)]}
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_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")]}
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")]}
self.assertEqual(killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1), [])
def test_removes_the_scratch_folder(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()), [])
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):
for log in (None, "not json", "{}", '{"killed": [{"diff": ""}]}', '{"killed": [7]}'):
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)
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_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_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()
+3 -1
View File
@@ -85,9 +85,11 @@ class LanguagesTest(unittest.TestCase):
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",)), ("Python", (".py",)), ("Rust", (".rs",))])
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")
+2 -2
View File
@@ -236,7 +236,7 @@ class BenchTest(unittest.TestCase):
def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug.\n")):
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug.\n")):
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors:
self.assertEqual(main.main(argv, self.env, lambda home: places), 1)
self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said))
@@ -309,7 +309,7 @@ class BenchTest(unittest.TestCase):
def test_fails_where_the_places_name_no_file_of_the_base_in_a_language_the_bench_plants_in(self):
with contextlib.redirect_stderr(io.StringIO()):
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
self.assertEqual(found, Failure("The places the seats found hard don't name any Go, Python or Rust file that the base holds, so there is nowhere to plant a bug."))
self.assertEqual(found, Failure("The places the seats found hard don't name any file that the base holds in a language the bench plants bugs in, so there is nowhere to plant a bug."))
self.assertFalse(self.log.exists())
def test_fails_where_the_tests_fail_without_a_bug(self):
+247
View File
@@ -0,0 +1,247 @@
"""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 json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.typescript_bugs import changed, killed_mutants, task_text
from failure import Failure
from task_bench.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_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.ran: list[tuple[list[str], str]] = []
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."""
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
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):
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))])
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_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_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):
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())
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 at reports/mutation/mutation.json", found.reason)
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()
+117
View File
@@ -0,0 +1,117 @@
"""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 failure import Failure
from mutate_changes import in_diff_tools
from task_bench.planted_mutant import Mutant
# 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.
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 there. 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)
try:
ran = run([*in_diff_tools.STRYKER, "--mutate", ",".join(files), "--concurrency", str(jobs), "--reporters", "json"], top)
if isinstance(ran, Failure) or ran.code:
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}")
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()
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 failed test that has one 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)]
+8
View File
@@ -3661,3 +3661,11 @@ Read most (opens and searches):
- `bin/task_bench/bench_folder.py` 2
- `bin/task_bench/feature_tasks.py` 2
- `docs/decisions.md` 2
## Reading cost, chunk a2b51a47f8f9, finished 2026-11-26T09:29:04Z
51817 new input tokens before the first commit.
Read most (opens and searches):
- `principles/technical-principles.md` 2