Files
FabledSteward/tests/plugins/docker/test_mcp_tools.py
T
bvandeusenandClaude Opus 5.5 2ebfdc8cdf
CI / lint (push) Successful in 2s
CI / integration (push) Successful in 43s
CI / unit (push) Successful in 1m0s
CI / publish (push) Successful in 58s
test(docker): the plugin registers prune_docker as an admin write tool
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:09:57 -04:00

106 lines
4.9 KiB
Python

"""The docker plugin's MCP tools: what counts as a problem, and how it is reported."""
import inspect
from datetime import datetime, timedelta, timezone
from types import SimpleNamespace as NS
from unittest.mock import MagicMock
import pytest
import plugins.docker as docker_plugin
from plugins.docker import mcp_tools as t
from steward.models.users import UserRole
NOW = datetime(2026, 10, 6, 12, 0, tzinfo=timezone.utc)
def _c(**kw):
base = dict(name="web", host_id="h1", image="nginx", status="running", health=None,
exit_code=None, oom_killed=False, restart_count=0, cpu_pct=1.0, mem_pct=2.0,
mem_usage_bytes=1, mem_limit_bytes=2, started_at=NOW - timedelta(hours=1),
compose_project=None, service_name=None, scraped_at=NOW - timedelta(seconds=30))
base.update(kw)
return NS(**base)
def test_container_problems_most_severe_first():
assert t.container_problems(_c(), 0, False) == []
assert t.container_problems(_c(status="restarting"), 4, True) == ["restarting", "crash_looping"]
# The crash-loop count comes from Settings → Thresholds.
assert t.container_problems(_c(), 2, True) == []
assert t.container_problems(_c(), 2, True, crash_loop_deaths=2) == ["crash_looping"]
assert t.container_problems(_c(health="unhealthy", oom_killed=True), 0, False) == ["unhealthy", "oom_killed"]
# An unhealthy flag on a stopped container is stale; it isn't failing a healthcheck now.
assert t.container_problems(_c(status="exited", health="unhealthy", exit_code=0), 0, False) == []
def test_exited_nonzero_needs_a_recent_death():
crashed = _c(status="exited", exit_code=137)
assert t.container_problems(crashed, 1, True) == ["exited_nonzero"]
# A container that died weeks ago and was left stopped is not news.
assert t.container_problems(crashed, 0, False) == []
def test_cut_middle_keeps_both_ends_and_sizes_the_gap():
assert t.cut_middle("short") == "short"
line = "A" * 10 + "B" * 100 + "C" * 10
cut = t.cut_middle(line, limit=20)
assert cut.startswith("A" * 10) and cut.endswith("C" * 10)
assert "[… 100 characters omitted …]" in cut
def test_container_row_uptime_only_while_running():
row = t.container_row(_c(), {"h1": "nas"}, [], NOW)
assert row["host_name"] == "nas" and row["uptime_s"] == 3600 and row["reported_age_s"] == 30
assert t.container_row(_c(status="exited"), {}, [], NOW)["uptime_s"] is None
def test_container_findings_one_per_container_with_every_problem_named():
rows = [t.container_row(_c(name="db", status="restarting", exit_code=1), {"h1": "nas"},
["restarting", "crash_looping"], NOW),
t.container_row(_c(name="ok"), {}, [], NOW)]
(f,) = t.container_findings(rows)
assert f["severity"] == "critical" and f["kind"] == "container_restarting"
assert "is restarting and keeps dying" in f["summary"] and "on nas" in f["summary"]
assert "(exit 1)" in f["summary"]
assert f["next"] == 'get_container(container="db", host="h1")'
def test_service_findings_by_state():
svcs = [{"name": "a", "state": "healthy", "running": 2, "desired": 2},
{"name": "b", "state": "degraded", "running": 1, "desired": 3},
{"name": "c", "state": "down", "running": 0, "desired": 1}]
got = {f["subject"]: f["severity"] for f in t.service_findings(svcs)}
assert got == {"b": "warning", "c": "critical"}
def test_plugin_exposes_the_mcp_hooks():
reg = MagicMock()
docker_plugin.register_mcp_tools(reg)
regs = {call.args[0].__name__: call.kwargs for call in reg.call_args_list}
assert set(regs) == {"list_containers", "get_container", "list_swarm_services",
"search_container_logs", "get_docker_disk_usage", "prune_docker"}
for name, kw in regs.items():
if name == "prune_docker":
assert (kw["role"], kw["read_only"]) == (UserRole.admin, False)
else:
assert (kw["role"], kw["read_only"]) == (UserRole.viewer, True), name
assert callable(docker_plugin.mcp_overview)
def test_prune_preview_sizes_what_each_target_removes():
usage = NS(images_reclaimable=3000, build_cache_size=70)
assert t.prune_preview("containers", usage, 4) == {"stopped_containers": 4}
assert t.prune_preview("images", usage, 4) == {"unused_images_bytes": 3000}
system = t.prune_preview("system", usage, 4)
assert system["stopped_containers"] == 4 and system["build_cache_bytes"] == 70
assert t.prune_preview("images", None, 0) == {"unused_images_bytes": None}
async def test_prune_docker_refuses_an_unknown_target_before_reading_anything(monkeypatch):
def _no_db():
raise AssertionError("touched the database")
monkeypatch.setattr(t, "db_session", _no_db)
with pytest.raises(ValueError, match="'volumes' is not one of containers, images, system"):
await t.prune_docker("nas", "volumes")
assert inspect.signature(t.prune_docker).parameters["check"].default is True