"""Tests for ``blackcat dockerize`` (stdlib, offline, no daemon).
Every subprocess is injected: the tests assert the exact argv that podman
or docker would receive, the scaffold contents, the fingerprint rules and
the user/ownership decisions, without touching a container runtime.
"""
# retoor <retoor@molodetz.nl>
import argparse
import contextlib
import io
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from blackcat.cli import build_parser
from blackcat.dockerize import (
BACKENDS,
DEFAULT_CONTAINER,
DEFAULT_IMAGE,
FALLBACKS,
FINGERPRINT_LABEL,
SCAFFOLD_FILES,
ContainerRuntime,
DockerizeCommand,
DockerizeError,
DockerizeOptions,
FallbackRuntime,
build_command,
build_context,
build_files,
bwrap_command,
detect_backend,
detect_runtime,
ensure_scaffold,
fallback_command,
fallback_inner,
fingerprint,
hash_tree,
image_is_current,
local_command,
proot_command,
read_image_labels,
resolve_options,
rmi_command,
run_command,
stop_command,
template_bytes,
unshare_command,
uses_host_user,
validate_project,
)
REPO = Path(__file__).resolve().parents[1]
PODMAN = ContainerRuntime(name="podman", path="/usr/bin/podman",
version="5.7.0", rootless=True)
DOCKER = ContainerRuntime(name="docker", path="/usr/bin/docker",
version="29.1.3")
BWRAP = FallbackRuntime(name="bwrap", path="/usr/bin/bwrap",
version="0.9.0")
UNSHARE = FallbackRuntime(name="unshare", path="/usr/bin/unshare")
PROOT = FallbackRuntime(name="proot", path="/usr/bin/proot")
LOCAL = FallbackRuntime(name="local", path=sys.executable)
def which_only(table):
def which(name):
return table.get(name)
return which
def which_every(name):
return {"podman": "/usr/bin/podman", "docker": "/usr/bin/docker",
"bwrap": "/usr/bin/bwrap", "unshare": "/usr/bin/unshare",
"proot": "/usr/bin/proot"}.get(name)
def make_args(**overrides):
base = {
"path": None, "runtime": "auto", "image": None, "name": None,
"browser": False, "context": "minimal", "rebuild": False,
"pull": False, "build_only": False, "no_scaffold": False,
"force": False, "shell": False, "entrypoint": None, "user": "auto",
"keep": False, "stop": False, "rm_image": False, "dry_run": False,
"args": [], "verbose": 0, "quiet": 0, "log_level": None,
"log_file": None,
}
base.update(overrides)
return argparse.Namespace(**base)
def make_opts(root, **overrides):
base = {
"root": root, "dockerized": root / "dockerized",
"image": DEFAULT_IMAGE, "name": DEFAULT_CONTAINER,
"runtime_requested": "auto", "context": "minimal", "browser": False,
"rebuild": False, "pull": False, "build_only": False,
"scaffold": True, "force": False, "shell": False,
"entrypoint": None, "user_mode": "auto", "keep": False,
"stop": False, "rmi": False, "dry_run": False, "args": (),
"uid": 1000, "gid": 1000, "platform": "linux", "selinux": False,
"tty": True, "term": "xterm-256color", "colorterm": None,
"quiet": False,
}
base.update(overrides)
return DockerizeOptions(**base)
def make_project(base: Path) -> Path:
root = base / "proj"
(root / "blackcat").mkdir(parents=True)
(root / "blackcat" / "__init__.py").write_text("")
(root / "pyproject.toml").write_text(
(REPO / "pyproject.toml").read_text())
(root / "README.md").write_text("# proj\n")
return root
def which_all(name):
return {"podman": "/usr/bin/podman", "docker": "/usr/bin/docker"}.get(
name)
class Recorder:
"""Records argv, returning canned capture results and stream codes."""
def __init__(self, results=None, stream_codes=None, default_stream=0):
self.calls = []
self.results = results or {}
self.stream_codes = stream_codes or {}
self.default_stream = default_stream
self.stream_calls = []
def capture(self, command):
cmd = list(command)
self.calls.append(cmd)
for needle, result in self.results.items():
if needle in cmd:
return result
return subprocess.CompletedProcess(cmd, 0, "", "")
def stream(self, command):
cmd = list(command)
self.stream_calls.append(cmd)
for needle, code in self.stream_codes.items():
if needle in cmd:
return code
return self.default_stream
def labels_result(payload, rc=0):
stdout = payload if isinstance(payload, str) else json.dumps(payload)
return subprocess.CompletedProcess([], rc, stdout, "")
class TestParser(unittest.TestCase):
def test_defaults(self):
args = build_parser().parse_args(["dockerize"])
self.assertEqual(args.command, "dockerize")
self.assertEqual(args.runtime, "auto")
self.assertEqual(args.context, "minimal")
self.assertEqual(args.user, "auto")
self.assertEqual(args.args, [])
self.assertFalse(args.dry_run)
def test_every_flag_parses(self):
args = build_parser().parse_args([
"dockerize", "--path", "/tmp/x", "--runtime", "docker",
"--image", "img:1", "--name", "box", "--browser",
"--context", "project", "--rebuild", "--pull", "--build-only",
"--no-scaffold", "--force", "--shell", "--entrypoint", "/bin/sh",
"--user", "root", "--keep", "--stop", "--rm-image", "--dry-run"])
self.assertEqual((args.image, args.name), ("img:1", "box"))
self.assertTrue(args.browser and args.rebuild and args.pull)
self.assertTrue(args.build_only and args.no_scaffold and args.force)
self.assertTrue(args.shell and args.keep and args.stop)
self.assertTrue(args.rm_image and args.dry_run)
self.assertEqual(args.entrypoint, "/bin/sh")
def test_passthrough_needs_double_dash(self):
args = build_parser().parse_args(
["dockerize", "--", "--provider", "echo", "tui"])
self.assertEqual(args.args, ["--", "--provider", "echo", "tui"])
def test_every_backend_parses(self):
for backend in ("auto", "podman", "docker", "bwrap", "unshare",
"proot", "local"):
with self.subTest(backend=backend):
args = build_parser().parse_args(
["dockerize", "--runtime", backend])
self.assertEqual(args.runtime, backend)
self.assertEqual(
BACKENDS, ("podman", "docker", "bwrap", "unshare", "proot",
"local"))
def test_typo_is_rejected(self):
with self.assertRaises(SystemExit) as caught:
with contextlib.redirect_stderr(io.StringIO()):
build_parser().parse_args(["dockerize", "--rebuild-x"])
self.assertEqual(caught.exception.code, 2)
class TestTemplates(unittest.TestCase):
def test_every_asset_readable(self):
for name in SCAFFOLD_FILES:
data = template_bytes(name)
self.assertTrue(data, name)
self.assertIn(b"\n", data, name)
def test_generated_scaffold_matches_templates(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
ensure_scaffold(make_opts(root))
for name in SCAFFOLD_FILES:
with self.subTest(name=name):
target = root / "dockerized" / name
self.assertTrue(target.is_file(), target)
self.assertEqual(target.read_bytes(), template_bytes(name))
def test_gitignore_covers_the_generated_folder_only(self):
lines = [line.strip()
for line in (REPO / ".gitignore").read_text().splitlines()]
self.assertIn("/dockerized/", lines)
self.assertNotIn("dockerized/", lines)
self.assertNotIn("dockerized", lines)
def test_package_data_declared(self):
text = (REPO / "pyproject.toml").read_text()
self.assertIn('blackcat = ["templates/dockerized/*"]', text)
def test_missing_asset_names_itself(self):
with self.assertRaises(DockerizeError) as caught:
template_bytes("nope.txt")
self.assertIn("nope.txt", str(caught.exception))
class TestResolveOptions(unittest.TestCase):
def test_relative_path_is_resolved(self):
with tempfile.TemporaryDirectory() as tmp:
opts = resolve_options(
make_args(path="sub"), environ={}, cwd=Path(tmp),
platform="linux", tty=False, selinux=False, ids=(1, 2))
self.assertTrue(opts.root.is_absolute())
self.assertEqual(opts.root, (Path(tmp) / "sub").resolve())
self.assertEqual(opts.dockerized, opts.root / "dockerized")
self.assertEqual((opts.uid, opts.gid), (1, 2))
def test_env_fallbacks(self):
environ = {
"BLACKCAT_CONTAINER_RUNTIME": "docker",
"BLACKCAT_CONTAINER_IMAGE": "env:1",
"BLACKCAT_CONTAINER_NAME": "env-box",
"TERM": "screen-256color",
"COLORTERM": "truecolor",
}
with tempfile.TemporaryDirectory() as tmp:
opts = resolve_options(make_args(), environ=environ,
cwd=Path(tmp), platform="linux",
tty=False, selinux=False, ids=(0, 0))
self.assertEqual(opts.runtime_requested, "docker")
self.assertEqual(opts.image, "env:1")
self.assertEqual(opts.name, "env-box")
self.assertEqual(opts.term, "screen-256color")
self.assertEqual(opts.colorterm, "truecolor")
def test_flags_beat_env(self):
environ = {"BLACKCAT_CONTAINER_RUNTIME": "docker",
"BLACKCAT_CONTAINER_IMAGE": "env:1"}
with tempfile.TemporaryDirectory() as tmp:
opts = resolve_options(
make_args(runtime="podman", image="flag:1"), environ=environ,
cwd=Path(tmp), platform="linux", tty=False, selinux=False,
ids=(0, 0))
self.assertEqual(opts.runtime_requested, "podman")
self.assertEqual(opts.image, "flag:1")
def test_empty_env_falls_back_to_defaults(self):
with tempfile.TemporaryDirectory() as tmp:
opts = resolve_options(
make_args(), environ={"BLACKCAT_CONTAINER_IMAGE": ""},
cwd=Path(tmp), platform="linux", tty=False, selinux=False,
ids=(0, 0))
self.assertEqual(opts.image, DEFAULT_IMAGE)
self.assertEqual(opts.name, DEFAULT_CONTAINER)
self.assertEqual(opts.term, "xterm-256color")
self.assertIsNone(opts.colorterm)
def test_windows_is_refused(self):
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(DockerizeError) as caught:
resolve_options(make_args(), environ={}, cwd=Path(tmp),
platform="win32", tty=False, selinux=False,
ids=(0, 0))
self.assertIn("WSL", str(caught.exception))
def test_leading_double_dash_stripped(self):
with tempfile.TemporaryDirectory() as tmp:
opts = resolve_options(
make_args(args=["--", "--provider", "echo"]), environ={},
cwd=Path(tmp), platform="linux", tty=False, selinux=False,
ids=(0, 0))
self.assertEqual(opts.args, ("--provider", "echo"))
def test_negated_flags(self):
with tempfile.TemporaryDirectory() as tmp:
opts = resolve_options(
make_args(no_scaffold=True, quiet=2, user="root"),
environ={}, cwd=Path(tmp), platform="linux", tty=False,
selinux=False, ids=(0, 0))
self.assertFalse(opts.scaffold)
self.assertTrue(opts.quiet)
self.assertEqual(opts.user_mode, "root")
class TestScaffold(unittest.TestCase):
def test_creates_everything(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
written, kept = ensure_scaffold(make_opts(root))
self.assertEqual(sorted(written), sorted(SCAFFOLD_FILES))
self.assertEqual(kept, [])
for name in SCAFFOLD_FILES:
self.assertTrue((root / "dockerized" / name).is_file())
entry = root / "dockerized" / "entrypoint.sh"
self.assertEqual(entry.stat().st_mode & 0o777, 0o755)
def test_second_call_keeps_all(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
written, kept = ensure_scaffold(opts)
self.assertEqual(written, [])
self.assertEqual(sorted(kept), sorted(SCAFFOLD_FILES))
def test_edited_file_is_kept_without_force(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
target = root / "dockerized" / "Dockerfile"
target.write_text("FROM scratch\n")
written, kept = ensure_scaffold(opts)
self.assertNotIn("Dockerfile", written)
self.assertIn("Dockerfile", kept)
self.assertEqual(target.read_text(), "FROM scratch\n")
def test_force_rewrites(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
ensure_scaffold(make_opts(root))
target = root / "dockerized" / "Dockerfile"
target.write_text("FROM scratch\n")
written, _ = ensure_scaffold(make_opts(root, force=True))
self.assertIn("Dockerfile", written)
self.assertEqual(target.read_bytes(), template_bytes("Dockerfile"))
def test_no_scaffold_writes_nothing(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
written, kept = ensure_scaffold(make_opts(root, scaffold=False))
self.assertEqual((written, kept), ([], []))
self.assertFalse((root / "dockerized").exists())
def test_dry_run_touches_nothing(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
written, _ = ensure_scaffold(make_opts(root), dry_run=True)
self.assertEqual(sorted(written), sorted(SCAFFOLD_FILES))
self.assertFalse((root / "dockerized").exists())
def test_dockerized_as_file_raises(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
(root / "dockerized").write_text("not a dir")
with self.assertRaises(DockerizeError):
ensure_scaffold(make_opts(root))
class TestFingerprint(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = make_project(Path(self.tmp.name))
self.opts = make_opts(self.root)
ensure_scaffold(self.opts)
def test_stable(self):
self.assertEqual(fingerprint(self.opts), fingerprint(self.opts))
def test_dockerfile_change(self):
before = fingerprint(self.opts)
dockerfile = self.root / "dockerized" / "Dockerfile"
dockerfile.write_bytes(dockerfile.read_bytes() + b"# edit\n")
self.assertNotEqual(before, fingerprint(self.opts))
def test_pyproject_change(self):
before = fingerprint(self.opts)
pyproject = self.root / "pyproject.toml"
pyproject.write_text(pyproject.read_text() + "\n")
self.assertNotEqual(before, fingerprint(self.opts))
def test_browser_toggle(self):
before = fingerprint(self.opts)
after = fingerprint(make_opts(self.root, browser=True))
self.assertNotEqual(before, after)
def test_context_toggle(self):
before = fingerprint(self.opts)
after = fingerprint(make_opts(self.root, context="project"))
self.assertNotEqual(before, after)
def test_minimal_context_ignores_source(self):
before = fingerprint(self.opts)
(self.root / "notes.md").write_text("research\n")
self.assertEqual(before, fingerprint(self.opts))
def test_project_context_tracks_source(self):
opts = make_opts(self.root, context="project")
before = fingerprint(opts)
(self.root / "notes.md").write_text("research\n")
self.assertNotEqual(before, fingerprint(opts))
def test_hash_tree_skips_host_artifacts(self):
before = hash_tree(self.root)
for name in (".git/objects/x", ".venv/lib/y", "__pycache__/z.pyc"):
path = self.root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("junk")
self.assertEqual(before, hash_tree(self.root))
(self.root / "real.py").write_text("x = 1\n")
self.assertNotEqual(before, hash_tree(self.root))
class TestRuntimeDetection(unittest.TestCase):
def test_prefers_podman(self):
runtime = detect_runtime("auto", environ={}, which=which_all,
probe=lambda n, p: ContainerRuntime(n, p))
self.assertEqual(runtime.name, "podman")
def test_falls_back_to_docker(self):
calls = []
def probe(name, path):
calls.append(name)
return ContainerRuntime(name, path) if name == "docker" else None
runtime = detect_runtime("auto", environ={}, which=which_all,
probe=probe)
self.assertEqual(runtime.name, "docker")
self.assertEqual(calls, ["podman", "docker"])
def test_env_selects_runtime(self):
runtime = detect_runtime(
"auto", environ={"BLACKCAT_CONTAINER_RUNTIME": "docker"},
which=which_all, probe=lambda n, p: ContainerRuntime(n, p))
self.assertEqual(runtime.name, "docker")
def test_flag_beats_env(self):
runtime = detect_runtime(
"podman", environ={"BLACKCAT_CONTAINER_RUNTIME": "docker"},
which=which_all, probe=lambda n, p: ContainerRuntime(n, p))
self.assertEqual(runtime.name, "podman")
def test_no_runtime_raises_with_hint(self):
with self.assertRaises(DockerizeError) as caught:
detect_runtime("auto", environ={}, which=lambda name: None)
message = str(caught.exception)
self.assertIn("podman", message)
self.assertIn("docker", message)
self.assertIn("BLACKCAT_CONTAINER_RUNTIME", message)
def test_unknown_runtime_raises(self):
with self.assertRaises(DockerizeError):
detect_runtime("lxc", environ={}, which=which_all)
def fallback_ok(name, path):
return FallbackRuntime(name=name, path=path)
class TestDetectBackend(unittest.TestCase):
def test_chain_order(self):
self.assertEqual(FALLBACKS, ("bwrap", "unshare", "proot", "local"))
self.assertEqual(BACKENDS, ("podman", "docker") + FALLBACKS)
def test_auto_prefers_podman(self):
backend = detect_backend(
"auto", environ={}, which=which_all,
probe=lambda n, p: ContainerRuntime(n, p),
fallback_probe=fallback_ok)
self.assertIsInstance(backend, ContainerRuntime)
self.assertEqual(backend.name, "podman")
def test_auto_skips_dead_engines_for_bwrap(self):
backend = detect_backend(
"auto", environ={}, which=which_every,
probe=lambda n, p: None, fallback_probe=fallback_ok)
self.assertIsInstance(backend, FallbackRuntime)
self.assertEqual(backend.name, "bwrap")
def test_auto_skips_missing_binaries(self):
backend = detect_backend(
"auto", environ={}, which=which_only({"unshare": "/u/unshare"}),
probe=lambda n, p: None, fallback_probe=fallback_ok)
self.assertEqual(backend.name, "unshare")
def test_auto_skips_broken_userns(self):
def probe(name, path):
return None if name == "unshare" else fallback_ok(name, path)
backend = detect_backend(
"auto", environ={},
which=which_only({"unshare": "/u/unshare",
"proot": "/u/proot"}),
probe=lambda n, p: None, fallback_probe=probe)
self.assertEqual(backend.name, "proot")
def test_auto_ends_at_local(self):
backend = detect_backend(
"auto", environ={}, which=lambda name: None,
probe=lambda n, p: None, fallback_probe=lambda n, p: None)
self.assertIsInstance(backend, FallbackRuntime)
self.assertEqual(backend.name, "local")
self.assertTrue(backend.is_local)
def test_local_needs_no_binary(self):
backend = detect_backend("local", environ={},
which=lambda name: None)
self.assertEqual(backend.name, "local")
self.assertTrue(backend.is_local)
def test_explicit_bwrap_resolves(self):
backend = detect_backend(
"bwrap", environ={}, which=which_every,
fallback_probe=fallback_ok)
self.assertEqual((backend.name, backend.path),
("bwrap", "/usr/bin/bwrap"))
def test_explicit_container_missing_errors(self):
with self.assertRaises(DockerizeError) as caught:
detect_backend("podman", environ={},
which=lambda name: None)
self.assertIn("podman", str(caught.exception))
self.assertIn("auto", str(caught.exception))
def test_explicit_fallback_missing_errors(self):
with self.assertRaises(DockerizeError) as caught:
detect_backend("bwrap", environ={},
which=lambda name: None,
fallback_probe=fallback_ok)
self.assertIn("bwrap", str(caught.exception))
def test_explicit_fallback_broken_errors(self):
with self.assertRaises(DockerizeError):
detect_backend("bwrap", environ={}, which=which_all,
fallback_probe=lambda n, p: None)
def test_unknown_backend_raises(self):
with self.assertRaises(DockerizeError):
detect_backend("lxc", environ={}, which=which_all)
def test_env_selects_backend(self):
backend = detect_backend(
"auto", environ={"BLACKCAT_CONTAINER_RUNTIME": "proot"},
which=which_every, fallback_probe=fallback_ok)
self.assertEqual(backend.name, "proot")
def test_flag_beats_env(self):
backend = detect_backend(
"unshare", environ={"BLACKCAT_CONTAINER_RUNTIME": "docker"},
which=which_every, fallback_probe=fallback_ok)
self.assertEqual(backend.name, "unshare")
class TestFallbackCommands(unittest.TestCase):
def opts(self, root, **overrides):
return make_opts(root, **overrides)
def test_local_runs_host_python(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
command = local_command(self.opts(root))
self.assertEqual(command[:2], ["env", f"PYTHONPATH={root}"])
self.assertEqual(command[2:], [sys.executable, "-m", "blackcat",
"--yolo", "tui"])
def test_local_passthrough(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
opts = self.opts(root, args=("--provider", "echo", "tui"))
command = local_command(opts)
self.assertEqual(command[-3:], ["--provider", "echo", "tui"])
def test_local_shell_and_entrypoint(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
shell = local_command(self.opts(root, shell=True))
self.assertIn("/bin/bash", shell)
custom = local_command(self.opts(root, shell=True,
entrypoint="/bin/sh"))
self.assertIn("/bin/sh", custom)
self.assertNotIn("/bin/bash", custom)
def test_bwrap_binds_and_isolates(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
command = bwrap_command(BWRAP, self.opts(root))
self.assertEqual(command[0], "/usr/bin/bwrap")
self.assertIn("--unshare-pid", command)
self.assertNotIn("--unshare-net", command)
self.assertIn("--bind", command)
self.assertIn(str(root), command)
self.assertIn("--chdir", command)
self.assertEqual(command[command.index("--chdir") + 1], str(root))
self.assertIn("--setenv", command)
self.assertIn("PYTHONPATH", command)
self.assertIn(str(root), command)
self.assertEqual(command[-5:], [sys.executable, "-m", "blackcat",
"--yolo", "tui"])
def test_bwrap_binds_outside_venv(self):
home = Path(sys.prefix)
root = home / "proj"
command = bwrap_command(BWRAP, self.opts(root))
self.assertIn(str(home), command)
self.assertIn("--bind", command)
def test_bwrap_skips_venv_inside_project(self):
root = Path(sys.prefix).parent
command = bwrap_command(BWRAP, self.opts(root))
self.assertEqual(command.count("--bind"), 1)
def test_unshare_maps_root_user(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
command = unshare_command(UNSHARE, self.opts(root))
self.assertEqual(command[:3], ["/usr/bin/unshare",
"--map-root-user", "--mount"])
for flag in ("--uts", "--ipc", "--pid", "--fork", "--mount-proc"):
self.assertIn(flag, command)
self.assertNotIn("--net", command)
self.assertEqual(command[command.index("--wd") + 1], str(root))
self.assertIn(f"PYTHONPATH={root}", command)
self.assertEqual(command[-2:], ["--yolo", "tui"])
self.assertIn(sys.executable, command)
def test_proot_mounts_app(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
command = proot_command(PROOT, self.opts(root))
self.assertEqual(command[:2], ["/usr/bin/proot", "-b"])
self.assertIn(f"{root}:/app", command)
self.assertEqual(command[command.index("-w") + 1], "/app")
self.assertIn("PYTHONPATH=/app", command)
self.assertEqual(command[-2:], ["--yolo", "tui"])
def test_dispatcher_matches_builders(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
opts = self.opts(root)
self.assertEqual(fallback_command(BWRAP, opts),
bwrap_command(BWRAP, opts))
self.assertEqual(fallback_command(UNSHARE, opts),
unshare_command(UNSHARE, opts))
self.assertEqual(fallback_command(PROOT, opts),
proot_command(PROOT, opts))
self.assertEqual(fallback_command(LOCAL, opts),
local_command(opts))
def test_fallback_inner_defaults(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
inner = fallback_inner(self.opts(root))
self.assertEqual(inner, [sys.executable, "-m", "blackcat",
"--yolo", "tui"])
class TestImageInspection(unittest.TestCase):
def test_labels_parsed(self):
runtime = PODMAN
labels = read_image_labels(
runtime, "img", capture=lambda cmd: labels_result(
{"org.blackcat.fingerprint": "abc"}))
self.assertEqual(labels, {"org.blackcat.fingerprint": "abc"})
def test_null_labels(self):
labels = read_image_labels(
PODMAN, "img",
capture=lambda cmd: labels_result("null"))
self.assertEqual(labels, {})
def test_missing_image(self):
labels = read_image_labels(
PODMAN, "img",
capture=lambda cmd: subprocess.CompletedProcess([], 1, "", "no"))
self.assertIsNone(labels)
def test_malformed_json(self):
labels = read_image_labels(
PODMAN, "img", capture=lambda cmd: labels_result("{not json"))
self.assertIsNone(labels)
def test_non_dict_labels(self):
labels = read_image_labels(
PODMAN, "img", capture=lambda cmd: labels_result("[]"))
self.assertIsNone(labels)
def test_current_matching(self):
digest = "a" * 64
self.assertTrue(image_is_current({FINGERPRINT_LABEL: digest}, digest))
self.assertFalse(image_is_current({FINGERPRINT_LABEL: digest}, "b"))
self.assertFalse(image_is_current(None, digest))
def test_argv_is_inspect_never_exists(self):
seen = []
def capture(command):
seen.append(list(command))
return labels_result("{}")
read_image_labels(DOCKER, "img:1", capture=capture)
self.assertEqual(seen[0][:4],
["/usr/bin/docker", "image", "inspect", "--format"])
self.assertNotIn("exists", seen[0])
class TestBuild(unittest.TestCase):
def test_minimal_context_contents_and_cleanup(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
with build_context(opts) as context:
names = sorted(path.name for path in context.iterdir())
self.assertEqual(names, ["Dockerfile", "README.md",
"entrypoint.sh", "pyproject.toml"])
entry = context / "entrypoint.sh"
self.assertEqual(entry.stat().st_mode & 0o777, 0o755)
captured = context
self.assertFalse(captured.exists())
def test_user_dockerfile_wins(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
(root / "dockerized" / "Dockerfile").write_text("FROM scratch\n")
with build_context(opts) as context:
self.assertEqual((context / "Dockerfile").read_text(),
"FROM scratch\n")
def test_context_cleaned_up_on_error(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
with self.assertRaises(RuntimeError):
with build_context(opts) as context:
captured = context
raise RuntimeError("boom")
self.assertFalse(captured.exists())
def test_minimal_argv(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
ensure_scaffold(opts, dry_run=False)
with build_context(opts) as context:
command = build_command(PODMAN, opts, context, "d" * 64)
self.assertEqual(command[:2], ["/usr/bin/podman", "build"])
self.assertEqual(command[command.index("-t") + 1], DEFAULT_IMAGE)
self.assertEqual(command[command.index("--label") + 1],
f"{FINGERPRINT_LABEL}={'d' * 64}")
self.assertEqual(command[command.index("--build-arg") + 1],
"WITH_BROWSER=0")
self.assertEqual(command[-1], str(context))
def test_argv_upgrades(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root, rebuild=True, pull=True, browser=True)
ensure_scaffold(opts)
with build_context(opts) as context:
command = build_command(PODMAN, opts, context, "d")
self.assertIn("--no-cache", command)
self.assertIn("--pull", command)
self.assertIn("WITH_BROWSER=1", command)
def test_no_ignorefile_or_layers(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
with build_context(opts) as context:
command = build_command(DOCKER, opts, context, "d")
joined = " ".join(command)
self.assertNotIn("ignorefile", joined)
self.assertNotIn("--layers", joined)
def test_project_context_argv(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root, context="project")
ensure_scaffold(opts)
command = build_command(DOCKER, opts, root, "d")
self.assertEqual(command[command.index("-f") + 1],
str(root / "dockerized" / "Dockerfile"))
self.assertEqual(command[-1], str(root))
def test_build_files_shape(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
opts = make_opts(root)
ensure_scaffold(opts)
files = build_files(opts)
self.assertEqual(sorted(files), ["Dockerfile", "README.md",
"entrypoint.sh", "pyproject.toml"])
class TestRun(unittest.TestCase):
def command(self, runtime=PODMAN, **overrides):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
opts = make_opts(root, **overrides)
return run_command(runtime, opts), opts
def test_podman_mapping(self):
command, opts = self.command()
self.assertIn("--userns=keep-id", command)
self.assertNotIn("--user", command)
self.assertIn("HOME=/tmp", command)
self.assertIn(f"{opts.root}:/app", command)
def test_docker_mapping(self):
command, _ = self.command(runtime=DOCKER)
self.assertIn("--user", command)
self.assertIn("1000:1000", command)
self.assertNotIn("--userns=keep-id", command)
self.assertIn("HOME=/tmp", command)
def test_root_needs_no_mapping(self):
command, _ = self.command(uid=0, gid=0)
self.assertNotIn("--userns=keep-id", command)
self.assertNotIn("--user", command)
self.assertNotIn("HOME=/tmp", command)
def test_user_root_disables_mapping(self):
command, _ = self.command(user_mode="root")
self.assertNotIn("--userns=keep-id", command)
self.assertNotIn("HOME=/tmp", command)
def test_darwin_has_no_mapping(self):
command, _ = self.command(platform="darwin", uid=501, gid=20)
self.assertNotIn("--userns=keep-id", command)
self.assertNotIn("--user", command)
def test_user_host_forces_mapping(self):
command, _ = self.command(platform="darwin", uid=501, gid=20,
user_mode="host")
self.assertIn("--userns=keep-id", command)
def test_selinux_suffix(self):
command, opts = self.command(selinux=True)
self.assertIn(f"{opts.root}:/app:z", command)
def test_tty_variants(self):
command, _ = self.command(tty=True)
self.assertIn("-i", command)
self.assertIn("-t", command)
command, _ = self.command(tty=False)
self.assertIn("-i", command)
self.assertNotIn("-t", command)
def test_keep_drops_rm(self):
command, _ = self.command(keep=True)
self.assertNotIn("--rm", command)
command, _ = self.command()
self.assertIn("--rm", command)
def test_shell_and_entrypoint(self):
command, _ = self.command(shell=True)
self.assertEqual(command[command.index("--entrypoint") + 1],
"/bin/bash")
command, _ = self.command(shell=True, entrypoint="/bin/sh")
self.assertEqual(command[command.index("--entrypoint") + 1],
"/bin/sh")
def test_default_command_and_passthrough(self):
command, _ = self.command()
self.assertEqual(command[-2:], ["--yolo", "tui"])
command, _ = self.command(args=("--provider", "echo", "tui"))
self.assertEqual(command[-3:], ["--provider", "echo", "tui"])
def test_always_init_pull_name_workdir(self):
command, _ = self.command()
for flag in ("--init", "--pull=never"):
self.assertIn(flag, command)
self.assertEqual(command[command.index("--name") + 1], DEFAULT_CONTAINER)
self.assertEqual(command[command.index("--workdir") + 1], "/app")
def test_stop_and_rmi_commands(self):
self.assertEqual(stop_command(PODMAN, "box"),
["/usr/bin/podman", "rm", "-f", "box"])
self.assertEqual(rmi_command(DOCKER, "img:1"),
["/usr/bin/docker", "rmi", "-f", "img:1"])
def test_uses_host_user_rules(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp))
self.assertTrue(uses_host_user(make_opts(root)))
self.assertFalse(uses_host_user(make_opts(root, uid=0)))
self.assertFalse(uses_host_user(make_opts(root,
user_mode="root")))
self.assertFalse(uses_host_user(make_opts(root,
platform="darwin")))
self.assertTrue(uses_host_user(make_opts(root, platform="darwin",
user_mode="host")))
class TestValidate(unittest.TestCase):
def test_accepts_checkout(self):
with tempfile.TemporaryDirectory() as tmp:
validate_project(make_opts(make_project(Path(tmp))))
def test_missing_markers(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "empty"
root.mkdir()
with self.assertRaises(DockerizeError) as caught:
validate_project(make_opts(root))
self.assertIn("pyproject.toml", str(caught.exception))
(root / "pyproject.toml").write_text("")
with self.assertRaises(DockerizeError) as caught:
validate_project(make_opts(root))
self.assertIn("blackcat/__init__.py", str(caught.exception))
class TestCommand(unittest.TestCase):
def build(self, tmp, recorder, **arg_overrides):
root = make_project(Path(tmp)).resolve()
args = make_args(path=str(root), **arg_overrides)
command = DockerizeCommand(
args, capture=recorder.capture, stream=recorder.stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=which_all,
probe=lambda name, path: ContainerRuntime(name, path, "9.9"))
return command, root
def current_labels(self, root):
opts = make_opts(root)
ensure_scaffold(opts)
return {FINGERPRINT_LABEL: fingerprint(opts)}
def test_full_flow_builds_then_runs(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={"inspect": labels_result("", 1)})
command, root = self.build(tmp, recorder)
with contextlib.redirect_stderr(io.StringIO()):
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(len(recorder.stream_calls), 2)
self.assertIn("build", recorder.stream_calls[0])
self.assertIn("run", recorder.stream_calls[1])
self.assertTrue((root / "dockerized" / "Dockerfile").is_file())
self.assertEqual(
recorder.stream_calls[0][recorder.stream_calls[0].index(
"--label") + 1].split("=")[0], FINGERPRINT_LABEL)
def test_current_image_skips_build(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
labels = self.current_labels(root)
recorder = Recorder(results={"inspect": labels_result(labels)})
args = make_args(path=str(root))
command = DockerizeCommand(
args, capture=recorder.capture, stream=recorder.stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=which_all,
probe=lambda name, path: ContainerRuntime(name, path))
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(len(recorder.stream_calls), 1)
self.assertIn("is current", err.getvalue())
def test_stale_image_rebuilds(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={
"inspect": labels_result({FINGERPRINT_LABEL: "old"})})
command, _ = self.build(tmp, recorder)
with contextlib.redirect_stderr(io.StringIO()) as err:
command.run()
self.assertEqual(len(recorder.stream_calls), 2)
self.assertIn("stale", err.getvalue())
def test_rebuild_forces_build_even_when_current(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
labels = self.current_labels(root)
recorder = Recorder(results={"inspect": labels_result(labels)})
args = make_args(path=str(root), rebuild=True)
command = DockerizeCommand(
args, capture=recorder.capture, stream=recorder.stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=which_all,
probe=lambda name, path: ContainerRuntime(name, path))
with contextlib.redirect_stderr(io.StringIO()):
command.run()
self.assertIn("--no-cache", recorder.stream_calls[0])
def test_build_only_does_not_run(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={"inspect": labels_result("", 1)})
command, _ = self.build(tmp, recorder, build_only=True)
with contextlib.redirect_stderr(io.StringIO()):
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(len(recorder.stream_calls), 1)
self.assertIn("build", recorder.stream_calls[0])
def test_build_failure_is_exit_two(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={"inspect": labels_result("", 1)},
stream_codes={"build": 3})
command, _ = self.build(tmp, recorder)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 2)
self.assertIn("build failed", err.getvalue())
def test_stop_action(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={
"rm": subprocess.CompletedProcess([], 0, "", "")})
command, _ = self.build(tmp, recorder, stop=True)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(recorder.stream_calls, [])
self.assertIn("removed container", err.getvalue())
def test_stop_missing_container_is_fine(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={
"rm": subprocess.CompletedProcess([], 1, "", "no such")})
command, _ = self.build(tmp, recorder, stop=True)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertIn("nothing to remove", err.getvalue())
def test_rm_image_failure_is_exit_two(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={
"rmi": subprocess.CompletedProcess([], 1, "", "in use")})
command, _ = self.build(tmp, recorder, rm_image=True)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 2)
self.assertIn("rmi failed", err.getvalue())
def test_dry_run_executes_nothing(self):
with tempfile.TemporaryDirectory() as tmp:
def boom(*args, **kwargs):
raise AssertionError("dry run executed a command")
recorder = Recorder()
recorder.capture = boom
recorder.stream = boom
command, root = self.build(tmp, recorder, dry_run=True)
with contextlib.redirect_stderr(io.StringIO()):
with contextlib.redirect_stdout(io.StringIO()) as out:
code = command.run()
self.assertEqual(code, 0)
self.assertFalse((root / "dockerized").exists())
self.assertIn("build", out.getvalue())
self.assertIn("run", out.getvalue())
def test_no_runtime_falls_back_to_local(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
args = make_args(path=str(root))
recorder = Recorder()
command = DockerizeCommand(
args, capture=recorder.capture, stream=recorder.stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=lambda name: None)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(len(recorder.stream_calls), 1)
argv = recorder.stream_calls[0]
self.assertIn("-m", argv)
self.assertIn("blackcat", argv)
self.assertNotIn("build", argv)
self.assertIn("backend local", err.getvalue())
def test_explicit_podman_missing_is_exit_two(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
args = make_args(path=str(root), runtime="podman")
command = DockerizeCommand(
args, capture=Recorder().capture, stream=Recorder().stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=lambda name: None)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 2)
self.assertIn("no podman runtime", err.getvalue())
def test_explicit_bwrap_missing_is_exit_two(self):
with tempfile.TemporaryDirectory() as tmp:
root = make_project(Path(tmp)).resolve()
args = make_args(path=str(root), runtime="bwrap")
command = DockerizeCommand(
args, capture=Recorder().capture, stream=Recorder().stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=lambda name: None)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 2)
self.assertIn("no bwrap backend", err.getvalue())
def test_not_a_checkout_is_exit_two(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp) / "empty"
root.mkdir()
recorder = Recorder()
command = DockerizeCommand(
make_args(path=str(root)), capture=recorder.capture,
stream=recorder.stream, environ={}, cwd=root,
platform="linux", tty=True, selinux=False, ids=(0, 0),
which=which_all,
probe=lambda name, path: ContainerRuntime(name, path))
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 2)
self.assertIn("not a blackcat checkout", err.getvalue())
self.assertEqual(recorder.calls, [])
def test_container_exit_code_propagates(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={"inspect": labels_result("", 1)},
stream_codes={"run": 7})
command, _ = self.build(tmp, recorder)
with contextlib.redirect_stderr(io.StringIO()):
code = command.run()
self.assertEqual(code, 7)
def test_quiet_suppresses_progress(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={"inspect": labels_result("", 1)})
command, _ = self.build(tmp, recorder, quiet=2)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(err.getvalue(), "")
def test_passthrough_reaches_run_command(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(results={"inspect": labels_result("", 1)})
command, _ = self.build(
tmp, recorder, args=["--", "--provider", "echo", "tui"])
with contextlib.redirect_stderr(io.StringIO()):
command.run()
run_argv = recorder.stream_calls[1]
self.assertEqual(run_argv[-3:],
["--provider", "echo", "tui"])
def test_dry_run_stop_prints_only(self):
with tempfile.TemporaryDirectory() as tmp:
def boom(*args, **kwargs):
raise AssertionError("dry run executed a command")
recorder = Recorder()
recorder.capture = boom
command, _ = self.build(tmp, recorder, dry_run=True, stop=True)
with contextlib.redirect_stderr(io.StringIO()):
with contextlib.redirect_stdout(io.StringIO()) as out:
code = command.run()
self.assertEqual(code, 0)
self.assertIn("rm -f", out.getvalue())
class TestFallbackRun(unittest.TestCase):
def build(self, tmp, recorder, **overrides):
root = make_project(Path(tmp)).resolve()
which = overrides.pop("which", lambda name: None)
probe = overrides.pop("probe", lambda n, p: None)
fallback_probe = overrides.pop("fallback_probe", None)
args = make_args(path=str(root), **overrides)
command = DockerizeCommand(
args, capture=recorder.capture, stream=recorder.stream,
environ={}, cwd=root, platform="linux", tty=True,
selinux=False, ids=(1000, 1000), which=which, probe=probe,
fallback_probe=fallback_probe)
return command, root
def test_unshare_skips_build(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder()
command, _ = self.build(
tmp, recorder,
which=which_only({"unshare": "/usr/bin/unshare"}),
fallback_probe=fallback_ok)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(len(recorder.stream_calls), 1)
self.assertEqual(recorder.stream_calls[0][0],
"/usr/bin/unshare")
self.assertEqual(recorder.calls, [])
self.assertIn("backend unshare", err.getvalue())
def test_passthrough_reaches_fallback(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder()
command, _ = self.build(
tmp, recorder, args=["--", "--provider", "echo", "tui"])
with contextlib.redirect_stderr(io.StringIO()):
command.run()
argv = recorder.stream_calls[0]
self.assertEqual(argv[-3:], ["--provider", "echo", "tui"])
self.assertIn(sys.executable, argv)
def test_build_only_does_nothing(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder()
command, _ = self.build(tmp, recorder, build_only=True)
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
self.assertEqual(code, 0)
self.assertEqual(recorder.stream_calls, [])
self.assertIn("builds no image", err.getvalue())
def test_stop_and_rmi_are_noops(self):
for flag in ("stop", "rm_image"):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder()
command, _ = self.build(tmp, recorder, **{flag: True})
with contextlib.redirect_stderr(io.StringIO()) as err:
code = command.run()
with self.subTest(flag=flag):
self.assertEqual(code, 0)
self.assertEqual(recorder.stream_calls, [])
self.assertIn("nothing to remove", err.getvalue())
def test_fallback_exit_code_propagates(self):
with tempfile.TemporaryDirectory() as tmp:
recorder = Recorder(stream_codes={"blackcat": 7})
command, _ = self.build(tmp, recorder)
with contextlib.redirect_stderr(io.StringIO()):
code = command.run()
self.assertEqual(code, 7)
def test_fallback_dry_run_prints_only(self):
with tempfile.TemporaryDirectory() as tmp:
def boom(*args, **kwargs):
raise AssertionError("dry run executed a command")
recorder = Recorder()
recorder.capture = boom
recorder.stream = boom
command, _ = self.build(tmp, recorder, dry_run=True)
with contextlib.redirect_stderr(io.StringIO()):
with contextlib.redirect_stdout(io.StringIO()) as out:
code = command.run()
self.assertEqual(code, 0)
self.assertIn("blackcat", out.getvalue())
if __name__ == "__main__":
unittest.main()