Inject the docker runner into the adf_codec tool and test its image and container calls

This commit is contained in:
2026-11-14 16:40:46 +01:00
parent 18dbf7b3d8
commit 8a50a676a4
2 changed files with 111 additions and 8 deletions
+10 -8
View File
@@ -31,6 +31,8 @@ class Ran:
# Runs the shim in the given mode (`to-adf` or `to-markdown`) on a text, or fails to start it.
Run = typing.Callable[[str, str], Ran | Failure]
# Runs a docker command line on a text, in at most the given seconds, or fails to start it.
Docker = typing.Callable[[list[str], str, int], Ran | Failure]
def image_tag(shim: pathlib.Path) -> str:
@@ -45,9 +47,9 @@ def docker_args(image: str, mode: str) -> list[str]:
return ["docker", "run", "--rm", "-i", "--memory", MEMORY, "--memory-swap", MEMORY, "--network", "none", "--read-only", image, mode]
def docker(args: list[str], text: str, seconds: int) -> Ran | Failure:
def docker(args: list[str], text: str, seconds: int, call: typing.Callable[..., typing.Any] = subprocess.run) -> Ran | Failure:
try:
done = subprocess.run(args, input=text, capture_output=True, text=True, encoding="utf-8", timeout=seconds)
done = call(args, input=text, capture_output=True, text=True, encoding="utf-8", timeout=seconds)
except FileNotFoundError:
return Failure("docker is not installed, and the adf-codec shim runs in a container")
except subprocess.TimeoutExpired:
@@ -55,13 +57,13 @@ def docker(args: list[str], text: str, seconds: int) -> Ran | Failure:
return Ran(done.returncode, done.stdout, done.stderr)
def ensure_image(shim: pathlib.Path) -> str | Failure:
def ensure_image(shim: pathlib.Path, run_docker: Docker = docker) -> str | Failure:
"""The tag of the shim's image, built from node_shim/ first where this machine has no image under that tag."""
tag = image_tag(shim)
found = docker(["docker", "image", "inspect", tag], "", RUN_SECONDS)
found = run_docker(["docker", "image", "inspect", tag], "", RUN_SECONDS)
if isinstance(found, Failure) or found.status == 0:
return found if isinstance(found, Failure) else tag
built = docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
built = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
if isinstance(built, Failure):
return built
if built.status != 0:
@@ -69,11 +71,11 @@ def ensure_image(shim: pathlib.Path) -> str | Failure:
return tag
def container_run(mode: str, text: str) -> Ran | Failure:
image = ensure_image(SHIM)
def container_run(mode: str, text: str, run_docker: Docker = docker) -> Ran | Failure:
image = ensure_image(SHIM, run_docker)
if isinstance(image, Failure):
return image
return docker(docker_args(image, mode), text, RUN_SECONDS)
return run_docker(docker_args(image, mode), text, RUN_SECONDS)
def answer(mode: str, text: str, run: Run) -> str | Failure:
+101
View File
@@ -1,4 +1,5 @@
import json
import re
import shutil
import subprocess
@@ -88,6 +89,106 @@ def test_the_image_tag_changes_with_the_shim_files(tmp_path):
assert convert.image_tag(tmp_path) != before
def test_the_container_command_line_is_exactly_this():
assert convert.docker_args("image:1", "to-adf") == [
"docker", "run", "--rm", "-i", "--memory", "256m", "--memory-swap", "256m", "--network", "none", "--read-only", "image:1", "to-adf",
]
def test_a_refusal_at_the_root_says_the_document():
refusal = {"error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal)))
assert failure == Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)")
def test_the_image_tag_is_a_12_digit_hash_of_the_shim_files(tmp_path):
for name in convert.SHIM_FILES:
(tmp_path / name).write_text("a")
assert re.fullmatch(r"claude-config-adf-codec:[0-9a-f]{12}", convert.image_tag(tmp_path))
def test_docker_passes_the_text_on_stdin_and_returns_the_output():
seen = {}
def call(args, **kwargs):
seen.update(kwargs, args=args)
return subprocess.CompletedProcess(args, 3, "out", "err")
assert convert.docker(["docker", "x"], "text", 7, call) == convert.Ran(3, "out", "err")
assert seen == {"args": ["docker", "x"], "input": "text", "capture_output": True, "text": True, "encoding": "utf-8", "timeout": 7}
def test_docker_missing_becomes_a_failure():
def call(args, **kwargs):
raise FileNotFoundError
failure = convert.docker(["docker", "x"], "", 7, call)
assert failure == Failure("docker is not installed, and the adf-codec shim runs in a container")
def test_docker_that_takes_too_long_becomes_a_failure():
def call(args, **kwargs):
raise subprocess.TimeoutExpired(args, 7)
assert convert.docker(["docker", "build", "x"], "", 7, call) == Failure("`docker build` took more than 7 seconds")
def shim_dir(tmp_path):
for name in convert.SHIM_FILES:
(tmp_path / name).write_text("a")
return tmp_path
def scripted(*answers):
lines: list[tuple[list[str], str, int]] = []
queue = list(answers)
def run_docker(args, text, seconds):
lines.append((args, text, seconds))
return queue.pop(0)
run_docker.lines = lines # type: ignore[attr-defined]
return run_docker
def test_an_image_that_exists_is_not_built(tmp_path):
run_docker = scripted(convert.Ran(0, "", ""))
tag = convert.image_tag(shim_dir(tmp_path))
assert convert.ensure_image(tmp_path, run_docker) == tag
assert run_docker.lines == [(["docker", "image", "inspect", tag], "", convert.RUN_SECONDS)]
def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit(tmp_path):
run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(0, "", ""))
tag = convert.image_tag(shim_dir(tmp_path))
assert convert.ensure_image(tmp_path, run_docker) == tag
assert run_docker.lines[1] == (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS)
def test_a_failed_build_becomes_a_failure_with_its_stderr(tmp_path):
run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n"))
shim_dir(tmp_path)
assert convert.ensure_image(tmp_path, run_docker) == Failure("building the adf-codec shim's image failed with exit 5: no network")
def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path):
shim_dir(tmp_path)
down = Failure("docker is not installed")
assert convert.ensure_image(tmp_path, scripted(down)) == down
assert convert.ensure_image(tmp_path, scripted(convert.Ran(1, "", ""), down)) == down
def test_container_run_runs_the_image_on_the_text():
run_docker = scripted(convert.Ran(0, "", ""), convert.Ran(0, "answer", ""))
assert convert.container_run("to-adf", "text", run_docker) == convert.Ran(0, "answer", "")
assert run_docker.lines[1] == (convert.docker_args(convert.image_tag(convert.SHIM), "to-adf"), "text", convert.RUN_SECONDS)
def test_container_run_passes_an_image_failure_through():
down = Failure("docker is not installed")
assert convert.container_run("to-adf", "text", scripted(down)) == down
@pytest.mark.skipif(shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True).returncode != 0, reason="needs a docker daemon")
def test_round_trip_through_the_real_container():
doc = convert.markdown_to_adf("# Title\n\nSome **bold** text.\n")