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: