Test task-bench's docker calls, command line and planter where mutants survived
CI / tests (pull_request) Successful in 4m38s
CI / tests (pull_request) Successful in 4m38s
This commit is contained in:
@@ -14,10 +14,12 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from task_bench import api_proxy, main, runs
|
||||
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests
|
||||
from failure import Failure
|
||||
from task_bench import api_proxy, main
|
||||
from task_bench.runs import checked_tree
|
||||
from test_env import isolated_env
|
||||
from mutate_changes.tool_process import Ran
|
||||
from task_bench.figures import Result
|
||||
|
||||
BASE_CODE = "package calc\n\nfunc Add(a, b int) int {\n\treturn a + b\n}\n\nfunc Twice(a int) int {\n\treturn a * 2\n}\n"
|
||||
# The head moves Add down a line and rewrites Twice's line.
|
||||
@@ -30,11 +32,13 @@ TESTS = textwrap.dedent("""\
|
||||
""")
|
||||
# Reports `+` in Add, which the head keeps, and the `*` in Twice, which the head rewrites, as killed; and a mutant no test caught.
|
||||
GREMLINS = textwrap.dedent("""\
|
||||
import json, sys
|
||||
import json, os, sys
|
||||
lines = open("calc.go").read().split("\\n")
|
||||
found = [{"line": at, "column": 11, "status": "KILLED", "type": "ARITHMETIC_BASE"} for at, line in enumerate(lines, 1) if " + " in line or " * " in line]
|
||||
report = {"files": [{"file_name": "calc.go", "mutations": [*found, {**found[0], "status": "LIVED", "type": "INVERT_NEGATIVES"}]}]}
|
||||
json.dump(report, open(sys.argv[sys.argv.index("--output") + 1], "w"))
|
||||
if os.environ.get("FAKE_GREMLINS_LOG"):
|
||||
json.dump([os.getcwd(), *sys.argv[1:]], open(os.environ["FAKE_GREMLINS_LOG"], "w"))
|
||||
""")
|
||||
# Logs each call. A `run` of the bench's image runs its command in the mounted tree: sh as it is, and claude as the fake below.
|
||||
DOCKER = textwrap.dedent("""\
|
||||
@@ -44,7 +48,9 @@ DOCKER = textwrap.dedent("""\
|
||||
with open(os.environ["FAKE_LOG"], "a") as log:
|
||||
log.write(json.dumps(args) + "\\n")
|
||||
if args[0] == "build":
|
||||
sys.stdin.read()
|
||||
held = sys.stdin.read()
|
||||
if os.environ.get("FAKE_STDIN"):
|
||||
open(os.environ["FAKE_STDIN"], "w").write(held)
|
||||
if args[0] != "run" or "--detach" in args:
|
||||
sys.exit(int(os.environ.get("FAKE_FAILS") == args[0]))
|
||||
tree = args[args.index("--volume") + 1].rpartition(":")[0]
|
||||
@@ -94,11 +100,15 @@ class BenchTest(unittest.TestCase):
|
||||
self.git("init", "--quiet", "--initial-branch", "main")
|
||||
for name, text in (("calc.go", BASE_CODE), ("calc_test.go", TESTS), ("README.md", "# Calc\n")):
|
||||
(self.repo / name).write_text(text)
|
||||
# A link to nothing, which a copy that followed links would fail on.
|
||||
os.symlink("missing", self.repo / "dangling")
|
||||
self.base = self.commit("Base")
|
||||
self.git("checkout", "--quiet", "-b", "item-1")
|
||||
(self.repo / "calc.go").write_text(HEAD_CODE)
|
||||
self.head = self.commit("Head")
|
||||
self.enterContext(contextlib.chdir(self.repo))
|
||||
# The bench runs from a folder below the checkout's top.
|
||||
(self.repo / "below").mkdir()
|
||||
self.enterContext(contextlib.chdir(self.repo / "below"))
|
||||
|
||||
def git(self, *args: str) -> str:
|
||||
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@localhost", "-c", "commit.gpgsign=false", *args], cwd=self.repo, env=self.env, check=True, capture_output=True, text=True).stdout.strip()
|
||||
@@ -137,7 +147,58 @@ class BenchTest(unittest.TestCase):
|
||||
self.assertEqual((results["sides"], results["bugs"], len(results["runs"])), ({"base": self.base, "head": self.head}, {"1": "calc.go:4:11 ARITHMETIC_BASE"}, 4))
|
||||
self.assertEqual(results["runs"][0], {"bug": 1, "side": "base", "run": 1, "passed": False, "finished": True, "claude_code": "2.1.330", "model": "claude-haiku-5-5", "tokens": {"input": 40, "write_5m": 9000, "write_1h": 0, "read": 52000, "output": 800}, "turns": 3, "seconds": 61.5, "reads": 1})
|
||||
self.assertEqual(sorted(path.name for path in (folder / "runs").iterdir() if path.suffix == ".jsonl"), ["bug-1-base-1.jsonl", "bug-1-base-2.jsonl", "bug-1-head-1.jsonl", "bug-1-head-2.jsonl"])
|
||||
self.assertIn("run 4 of 4, bug 1 at the head: passed.", self.progress.getvalue())
|
||||
self.assertEqual(results["seed"], 1)
|
||||
self.assertEqual(self.progress.getvalue().splitlines(), [
|
||||
f"task-bench: base {self.base[:12]}, head {self.head[:12]}.",
|
||||
"task-bench: run 1 of 4, bug 1 at the base: not passed.",
|
||||
"task-bench: run 2 of 4, bug 1 at the head: passed.",
|
||||
"task-bench: run 3 of 4, bug 1 at the base: not passed.",
|
||||
"task-bench: run 4 of 4, bug 1 at the head: passed.",
|
||||
])
|
||||
self.assertEqual(sorted(path.name for path in folder.iterdir()), ["bugs", "results.json", "runs", "trees"])
|
||||
self.assertEqual((folder / "runs/bug-1-base-1.stderr").read_bytes(), b"")
|
||||
self.assertEqual(os.readlink(folder / "bugs/1/head/dangling"), "missing")
|
||||
|
||||
def test_the_command_line_runs_the_bench_on_the_seats_places_and_prints_its_report(self):
|
||||
argv = [part for name, value in self.given.items() for part in (name, value)]
|
||||
homes = []
|
||||
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(main.main(argv, self.env, lambda home: homes.append(home) or PLACES), 0)
|
||||
self.assertEqual(homes, [self.home])
|
||||
# Without --base, the base is the merge base with the default branch.
|
||||
self.assertEqual(out.getvalue().splitlines()[0], f"task-bench: base {self.base[:12]}, head {self.head[:12]}. 1 bug, fixed 2 times at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
|
||||
self.assertEqual(out.getvalue().splitlines()[3], "| Task | Side | Passed | Input | Cache write | Cache read | Output | Turns | Wall, s | Reads |")
|
||||
self.assertTrue(out.getvalue().endswith("task-bench\n"), out.getvalue()[-80:])
|
||||
|
||||
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 name no Go file that the base holds, 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))
|
||||
|
||||
def test_the_head_is_the_commit_asked_for(self):
|
||||
report = self.bench(**{"--head": "main", "--runs": "1"})
|
||||
self.assertEqual(report[0], f"task-bench: base {self.base[:12]}, head {self.base[:12]}. 1 bug, fixed 1 time at each side by claude-haiku-5-5 in Claude Code 2.1.330.")
|
||||
|
||||
def test_fails_on_a_head_or_a_base_git_does_not_know(self):
|
||||
for name in ("--head", "--base"):
|
||||
found = self.bench(**{name: "no-such-ref"})
|
||||
self.assertIsInstance(found, Failure)
|
||||
self.assertIn("no-such-ref", found.reason)
|
||||
|
||||
def test_the_image_is_built_from_the_one_asked_for_with_the_caps_memory(self):
|
||||
self.env["FAKE_STDIN"] = str(self.root / "dockerfile")
|
||||
self.env.pop("RUN_HEAVY_MEMORY")
|
||||
self.bench(**{"--runs": "1"})
|
||||
self.assertEqual((self.root / "dockerfile").read_text().splitlines()[0], "FROM golang:1.27.4")
|
||||
self.assertEqual(self.calls()[0][1:6], ["--quiet", "--memory", "4096m", "--memory-swap", "4096m"])
|
||||
|
||||
def test_gremlins_runs_through_the_prefix_in_the_copy_of_the_base_with_a_slots_workers(self):
|
||||
self.env["FAKE_GREMLINS_LOG"] = str(self.root / "gremlins.log")
|
||||
folder = pathlib.Path(self.bench(**{"--runs": "1"})[-1].removeprefix("Each run's result and stream: "))
|
||||
cwd, *argv = json.loads((self.root / "gremlins.log").read_text())
|
||||
self.assertEqual((cwd, argv[:2], argv[-2:]), (str(folder / "trees/base"), ["gremlins", "unleash"], ["--workers", str(main.CPUS_PER_SLOT)]))
|
||||
|
||||
def test_each_side_gets_its_own_tree_with_the_bug_committed_once_and_no_trace_of_the_checkout(self):
|
||||
folder = pathlib.Path(self.bench()[-1].removeprefix("Each run's result and stream: "))
|
||||
@@ -235,6 +296,127 @@ class MainTest(unittest.TestCase):
|
||||
self.assertIn("usage: task-bench --image <image> --test <shell text>", out.getvalue())
|
||||
|
||||
|
||||
def test_records_a_run_that_did_not_finish_without_figures(self):
|
||||
self.assertEqual(main.recorded(Result(1, "base", 2, False, None)), {"bug": 1, "side": "base", "run": 2, "passed": False, "finished": False})
|
||||
|
||||
|
||||
class Recorded:
|
||||
"""A docker that records each call and answers by the call's first word, else that it ran."""
|
||||
|
||||
def __init__(self, **answers: Ran | Failure):
|
||||
self.calls: list[tuple[list[str], float, str | None]] = []
|
||||
self.answers = answers
|
||||
|
||||
def __call__(self, args, *, seconds, stdin=None, stdout=None, stderr=None):
|
||||
self.calls.append((args, seconds, stdin))
|
||||
if stdout:
|
||||
stdout.write(b"stream")
|
||||
stderr.write(b"errors")
|
||||
return self.answers.get(args[0], Ran(0, "ran"))
|
||||
|
||||
|
||||
class ContainersTest(unittest.TestCase):
|
||||
IN_TREE = ["--memory", "512m", "--memory-swap", "512m", "--user", "1000:1000", "--env", "HOME=/tmp", "--volume", "/tree:/work", "--workdir", "/work"]
|
||||
REMOVED = (["rm", "--force", "bench-run"], 120, None)
|
||||
|
||||
def setUp(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.stream = pathlib.Path(folder.name, "run.jsonl")
|
||||
|
||||
def containers(self, **answers: Ran | Failure) -> Containers:
|
||||
self.docker = Recorded(**answers)
|
||||
return Containers(self.docker, "bench", "go test ./...", 512, "1000:1000")
|
||||
|
||||
def test_opens_the_image_the_network_without_a_route_out_and_the_proxy_on_both_networks(self):
|
||||
self.assertIsNone(opened(self.containers(), "golang:1.27.4"))
|
||||
proxy = str(pathlib.Path(runs.__file__).with_name("api_proxy.py"))
|
||||
self.assertEqual(self.docker.calls, [
|
||||
(["build", "--quiet", "--memory", "512m", "--memory-swap", "512m", "--tag", "bench:throwaway", "-"], 1200, "FROM golang:1.27.4\nUSER root\nRUN curl -fsSL https://claude.ai/install.sh | bash && cp -L /root/.local/bin/claude /usr/local/bin/claude\n"),
|
||||
(["network", "create", "--internal", "bench"], 60, None),
|
||||
(["run", "--detach", "--rm", "--name", "bench-proxy", "--memory", "256m", "--memory-swap", "256m", "--volume", f"{proxy}:/api_proxy.py:ro", "python:3.15.2-slim", "python", "/api_proxy.py", "api.anthropic.com:443"], 300, None),
|
||||
(["network", "connect", "bench", "bench-proxy"], 60, None),
|
||||
])
|
||||
|
||||
def test_opening_stops_at_the_first_step_that_fails_and_says_which(self):
|
||||
found = opened(self.containers(network=Ran(1, "pool overlaps")), "golang:1.27.4")
|
||||
self.assertEqual((found.reason.startswith("docker network"), "pool overlaps" in found.reason, len(self.docker.calls)), (True, True, 2))
|
||||
self.assertEqual(opened(self.containers(build=Failure("docker could not start")), "golang:1.27.4"), Failure("docker could not start"))
|
||||
|
||||
def test_closing_removes_the_running_container_the_proxy_the_network_and_the_image(self):
|
||||
closed(self.containers())
|
||||
self.assertEqual(self.docker.calls, [self.REMOVED, (["rm", "--force", "bench-proxy"], 120, None), (["network", "rm", "bench"], 120, None), (["image", "rm", "bench:throwaway"], 120, None)])
|
||||
|
||||
def test_the_tests_run_in_the_tree_without_a_network_for_at_most_half_an_hour(self):
|
||||
self.assertEqual(ran_tests(self.containers(), "/tree"), Ran(0, "ran"))
|
||||
self.assertEqual(self.docker.calls, [(["run", "--rm", "--name", "bench-run", "--network", "none", *self.IN_TREE, "bench:throwaway", "sh", "-c", "go test ./..."], 1800, None)])
|
||||
|
||||
def test_tests_that_run_out_of_time_are_a_failure_and_their_container_goes(self):
|
||||
late = Failure("docker run still ran after 30 min")
|
||||
self.assertEqual(ran_tests(self.containers(run=late), "/tree"), late)
|
||||
self.assertEqual(self.docker.calls[1:], [self.REMOVED])
|
||||
|
||||
def test_a_fix_writes_claudes_stream_and_its_errors_beside_it(self):
|
||||
self.assertIsNone(fix_attempted(self.containers(), "/tree", "got 3, want 4", self.stream))
|
||||
self.assertEqual((self.stream.read_bytes(), self.stream.with_suffix(".stderr").read_bytes()), (b"stream", b"errors"))
|
||||
(args, seconds, stdin), = self.docker.calls
|
||||
self.assertEqual((args[:6], seconds, stdin), (["run", "--rm", "--name", "bench-run", "--network", "bench"], 1800, None))
|
||||
self.assertEqual(args[6:18], self.IN_TREE)
|
||||
self.assertEqual(args[18:25], ["--env", "CLAUDE_CODE_OAUTH_TOKEN", "--env", "HTTPS_PROXY=http://bench-proxy:8080", "--env", "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1", "bench:throwaway"])
|
||||
|
||||
def test_a_fix_that_runs_out_of_time_is_no_failure_and_its_container_goes(self):
|
||||
self.assertIsNone(fix_attempted(self.containers(run=Failure("docker run still ran after 30 min")), "/tree", "got 3", self.stream))
|
||||
self.assertEqual(self.docker.calls[1:], [self.REMOVED])
|
||||
|
||||
def test_a_fix_docker_could_not_start_is_a_failure(self):
|
||||
broke = Failure("docker could not start: No such file or directory")
|
||||
self.assertEqual(fix_attempted(self.containers(run=broke), "/tree", "got 3", self.stream), broke)
|
||||
self.assertEqual(self.docker.calls[1:], [self.REMOVED])
|
||||
|
||||
def test_a_stream_that_cannot_be_written_is_a_failure(self):
|
||||
found = fix_attempted(self.containers(), "/tree", "got 3", self.stream / "below" / "run.jsonl")
|
||||
self.assertTrue(found.reason.startswith(f"could not write {self.stream}/below/run.jsonl: "), found.reason)
|
||||
self.assertEqual(self.docker.calls, [])
|
||||
|
||||
|
||||
class DockerCliTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(folder.cleanup)
|
||||
self.root = pathlib.Path(folder.name)
|
||||
(self.root / "docker").write_text('#!/bin/sh\necho "$@ $SAID"\ncat\necho broke >&2\nexit 3\n')
|
||||
(self.root / "docker").chmod(0o755)
|
||||
self.docker = docker_cli({"PATH": f"{self.root}{os.pathsep}{os.environ['PATH']}", "SAID": "caf\xe9"})
|
||||
|
||||
def test_runs_docker_in_the_environment_with_the_text_on_its_input_and_returns_its_code_and_all_it_printed(self):
|
||||
self.assertEqual(self.docker(["build", "-"], seconds=30, stdin="FROM x\n"), Ran(3, "build - caf\xe9\nFROM x\nbroke\n"))
|
||||
|
||||
def test_gives_docker_no_input_where_the_call_has_none(self):
|
||||
self.assertEqual(self.docker(["ps"], seconds=30), Ran(3, "ps caf\xe9\nbroke\n"))
|
||||
|
||||
def test_writes_the_output_and_the_errors_to_the_files_the_call_gives(self):
|
||||
with (self.root / "out").open("wb") as out, (self.root / "errors").open("wb") as errors:
|
||||
self.assertEqual(self.docker(["ps"], seconds=30, stdout=out, stderr=errors), Ran(3, ""))
|
||||
self.assertEqual(((self.root / "out").read_text(), (self.root / "errors").read_text()), ("ps caf\xe9\n", "broke\n"))
|
||||
|
||||
def test_output_that_is_no_utf_8_still_reads(self):
|
||||
(self.root / "docker").write_text("#!/bin/sh\nprintf 'a\\377b'\n")
|
||||
self.assertEqual(self.docker(["ps"], seconds=30), Ran(0, "a\ufffdb"))
|
||||
|
||||
def test_a_docker_that_is_not_there_is_a_failure(self):
|
||||
self.assertEqual(docker_cli({"PATH": str(self.root / "none")})(["ps"], seconds=30), Failure("docker could not start: No such file or directory"))
|
||||
|
||||
def test_a_docker_that_runs_too_long_is_a_failure_that_names_the_command_and_the_minutes(self):
|
||||
waited = []
|
||||
|
||||
def late(argv, timeout, **given):
|
||||
waited.append(timeout)
|
||||
raise subprocess.TimeoutExpired(argv, timeout)
|
||||
|
||||
self.assertEqual(docker_cli({}, late)(["run", "--rm"], seconds=90), Failure("docker run still ran after 2 min"))
|
||||
self.assertEqual(waited, [90])
|
||||
|
||||
|
||||
class CheckedTreeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
folder = tempfile.TemporaryDirectory()
|
||||
@@ -264,6 +446,16 @@ class CheckedTreeTest(unittest.TestCase):
|
||||
checked_tree(planted, copy, str(self.root / "check"))
|
||||
self.assertEqual(os.readlink(self.root / "check/host.go"), "/etc/hostname")
|
||||
|
||||
def test_a_link_never_stands_in_for_a_folder_of_the_planted_tree_and_a_linked_folder_is_copied_as_a_link(self):
|
||||
planted = self.tree("planted", {"calc.go": "bug", "sub/old.go": "old", "gone/a.go": "a"})
|
||||
copy = self.tree("copy", {"calc.go": "fixed"})
|
||||
os.symlink("/etc", os.path.join(copy, "sub"))
|
||||
os.symlink("/etc", os.path.join(copy, "etc"))
|
||||
checked_tree(planted, copy, str(self.root / "check"))
|
||||
check = self.root / "check"
|
||||
self.assertEqual((check.joinpath("sub").is_symlink(), os.readlink(check / "etc")), (False, "/etc"))
|
||||
self.assertEqual(self.held("check"), {"calc.go": "fixed"})
|
||||
|
||||
|
||||
class ApiProxyTest(unittest.IsolatedAsyncioTestCase):
|
||||
async def asyncSetUp(self):
|
||||
|
||||
Reference in New Issue
Block a user