merge: testing → main (reconcile 2-week divergence)

This commit is contained in:
2026-04-28 18:36:00 -04:00
parent 499836c9e4
commit 862e4dbb31
1235 changed files with 160255 additions and 7996 deletions

View File

View File

@@ -0,0 +1,224 @@
"""Phase 3 Step 4 — child CRUD: LAN / decky / edge."""
from __future__ import annotations
import pytest
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import persist, transition_status
from decnet.topology.status import TopologyStatus
from decnet.web.dependencies import repo as _repo
_V1 = "/api/v1/topologies"
def _cfg(name: str = "draft") -> TopologyConfig:
return TopologyConfig(
name=name,
depth=1,
branching_factor=1,
deckies_per_lan_min=1,
deckies_per_lan_max=1,
services_explicit=["ssh"],
randomize_services=False,
seed=0,
)
async def _seed(name: str = "draft") -> str:
return await persist(_repo, generate(_cfg(name)))
def _hdr(token: str) -> dict:
return {"Authorization": f"Bearer {token}"}
# ── LAN CRUD ──────────────────────────────────────────────────────
@pytest.mark.anyio
async def test_lan_create_ok(client, auth_token):
topology_id = await _seed("lan-create")
r = await client.post(
f"{_V1}/{topology_id}/lans",
json={"name": "extra-lan"},
headers=_hdr(auth_token),
)
assert r.status_code == 201, r.text
body = r.json()
assert body["name"] == "extra-lan"
assert body["topology_id"] == topology_id
assert body["subnet"] # allocator minted one
@pytest.mark.anyio
async def test_lan_create_blocked_when_active(client, auth_token):
topology_id = await _seed("lan-active")
await transition_status(_repo, topology_id, TopologyStatus.DEPLOYING)
await transition_status(_repo, topology_id, TopologyStatus.ACTIVE)
r = await client.post(
f"{_V1}/{topology_id}/lans",
json={"name": "extra-lan"},
headers=_hdr(auth_token),
)
assert r.status_code == 409
@pytest.mark.anyio
async def test_lan_patch_ok(client, auth_token):
topology_id = await _seed("lan-patch")
lans = await _repo.list_lans_for_topology(topology_id)
lan_id = lans[0]["id"]
r = await client.patch(
f"{_V1}/{topology_id}/lans/{lan_id}",
json={"x": 123.0, "y": 456.0},
headers=_hdr(auth_token),
)
assert r.status_code == 200, r.text
body = r.json()
assert body["x"] == 123.0
assert body["y"] == 456.0
@pytest.mark.anyio
async def test_lan_delete_ok(client, auth_token):
topology_id = await _seed("lan-delete")
# Add a throw-away LAN first (deleting the primary LAN would orphan its decky).
created = await client.post(
f"{_V1}/{topology_id}/lans",
json={"name": "disposable"},
headers=_hdr(auth_token),
)
lan_id = created.json()["id"]
r = await client.delete(
f"{_V1}/{topology_id}/lans/{lan_id}",
headers=_hdr(auth_token),
)
assert r.status_code == 204
@pytest.mark.anyio
async def test_lan_requires_admin(client, viewer_token):
topology_id = await _seed("lan-viewer")
r = await client.post(
f"{_V1}/{topology_id}/lans",
json={"name": "nope"},
headers=_hdr(viewer_token),
)
assert r.status_code == 403
# ── Decky CRUD ────────────────────────────────────────────────────
@pytest.mark.anyio
async def test_decky_create_ok(client, auth_token):
topology_id = await _seed("decky-create")
r = await client.post(
f"{_V1}/{topology_id}/deckies",
json={"name": "test-decky", "services": ["ssh"]},
headers=_hdr(auth_token),
)
assert r.status_code == 201, r.text
body = r.json()
assert body["name"] == "test-decky"
assert body["services"] == ["ssh"]
@pytest.mark.anyio
async def test_decky_patch_ok(client, auth_token):
topology_id = await _seed("decky-patch")
deckies = await _repo.list_topology_deckies(topology_id)
decky_uuid = deckies[0]["uuid"]
r = await client.patch(
f"{_V1}/{topology_id}/deckies/{decky_uuid}",
json={"x": 50.0, "y": 60.0},
headers=_hdr(auth_token),
)
assert r.status_code == 200
assert r.json()["x"] == 50.0
@pytest.mark.anyio
async def test_decky_delete_ok(client, auth_token):
topology_id = await _seed("decky-delete")
created = await client.post(
f"{_V1}/{topology_id}/deckies",
json={"name": "transient", "services": []},
headers=_hdr(auth_token),
)
decky_uuid = created.json()["uuid"]
r = await client.delete(
f"{_V1}/{topology_id}/deckies/{decky_uuid}",
headers=_hdr(auth_token),
)
assert r.status_code == 204
@pytest.mark.anyio
async def test_decky_delete_missing_404(client, auth_token):
topology_id = await _seed("decky-missing")
r = await client.delete(
f"{_V1}/{topology_id}/deckies/not-a-uuid",
headers=_hdr(auth_token),
)
assert r.status_code == 404
# ── Edge CRUD ─────────────────────────────────────────────────────
@pytest.mark.anyio
async def test_edge_create_and_delete(client, auth_token):
topology_id = await _seed("edge-crud")
# Add a second LAN so we can wire an extra edge (bridge) into it.
new_lan = await client.post(
f"{_V1}/{topology_id}/lans",
json={"name": "bridge-target"},
headers=_hdr(auth_token),
)
lan_id = new_lan.json()["id"]
deckies = await _repo.list_topology_deckies(topology_id)
decky_uuid = deckies[0]["uuid"]
r = await client.post(
f"{_V1}/{topology_id}/edges",
json={"decky_uuid": decky_uuid, "lan_id": lan_id, "is_bridge": True},
headers=_hdr(auth_token),
)
assert r.status_code == 201, r.text
edge_id = r.json()["id"]
r2 = await client.delete(
f"{_V1}/{topology_id}/edges/{edge_id}",
headers=_hdr(auth_token),
)
assert r2.status_code == 204
@pytest.mark.anyio
async def test_edge_create_bad_refs_400(client, auth_token):
topology_id = await _seed("edge-bad")
r = await client.post(
f"{_V1}/{topology_id}/edges",
json={"decky_uuid": "ghost", "lan_id": "also-ghost"},
headers=_hdr(auth_token),
)
assert r.status_code == 400
@pytest.mark.anyio
async def test_edge_requires_admin(client, viewer_token):
topology_id = await _seed("edge-viewer")
r = await client.post(
f"{_V1}/{topology_id}/edges",
json={"decky_uuid": "x", "lan_id": "y"},
headers=_hdr(viewer_token),
)
assert r.status_code == 403

View File

@@ -0,0 +1,140 @@
"""SSE events stream — GET /topologies/{id}/events (DEBT-030)."""
from __future__ import annotations
import asyncio
import httpx
import pytest
from decnet.bus import app as _bus_app
from decnet.bus import topics as _topics
from decnet.bus.fake import FakeBus
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import persist, transition_status
from decnet.topology.status import TopologyStatus
from decnet.web.api import app
from decnet.web.dependencies import repo as _repo
_V1 = "/api/v1/topologies"
def _cfg(name: str) -> TopologyConfig:
return TopologyConfig(
name=name, depth=1, branching_factor=1,
deckies_per_lan_min=1, deckies_per_lan_max=1,
services_explicit=["ssh"], randomize_services=False, seed=0,
)
async def _seed_active(name: str) -> str:
tid = await persist(_repo, generate(_cfg(name)))
await transition_status(_repo, tid, TopologyStatus.DEPLOYING)
await transition_status(_repo, tid, TopologyStatus.ACTIVE)
return tid
@pytest.fixture
def _fake_app_bus(monkeypatch):
bus = FakeBus()
async def _get() -> FakeBus:
if not bus._connected:
await bus.connect()
return bus
monkeypatch.setattr(_bus_app, "get_app_bus", _get)
from decnet.web.router.topology import api_events as _ev
from decnet.web.router.topology import api_mutations as _mu
monkeypatch.setattr(_ev, "get_app_bus", _get)
monkeypatch.setattr(_mu, "get_app_bus", _get)
return bus
@pytest.mark.anyio
async def test_events_unauthenticated_401():
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://test",
) as ac:
r = await ac.get(f"{_V1}/any/events")
assert r.status_code == 401
@pytest.mark.anyio
async def test_events_missing_topology_404(auth_token, _fake_app_bus):
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=app), base_url="http://test",
) as ac:
r = await ac.get(
f"{_V1}/nope/events",
params={"token": auth_token},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_events_emits_snapshot_and_live_event(auth_token, _fake_app_bus):
"""Drive the generator directly — avoids the full httpx streaming
roundtrip, which is painful under ASGITransport + an infinite SSE loop.
The route is thin glue: if the generator yields snapshot + mapped
bus events, the handler works. Auth/404 paths are covered above.
"""
from decnet.web.router.topology import api_events as _ev
tid = await _seed_active("evt-live")
class _FakeRequest:
async def is_disconnected(self) -> bool:
return False
# Patch out the role gate so we can call the async endpoint directly.
response = await _ev.api_topology_events(
topology_id=tid,
request=_FakeRequest(), # type: ignore[arg-type]
user={"role": "admin", "uuid": "00000000-0000-0000-0000-000000000000"},
)
gen = response.body_iterator
def _as_text(frame) -> str:
return frame if isinstance(frame, str) else frame.decode()
async def _publish_after_snapshot() -> None:
# Wait for the generator to reach its blocking subscribe state.
# We don't have a synchronization primitive, so a short sleep is
# good enough — the test-level timeout catches any real hang.
await asyncio.sleep(0.1)
await _fake_app_bus.publish(
_topics.topology_mutation(tid, _topics.MUTATION_APPLIED),
{"mutation_id": "m1", "op": "add_lan"},
event_type=_topics.MUTATION_APPLIED,
)
pub_task = asyncio.create_task(_publish_after_snapshot())
async def _drive() -> tuple[bool, bool]:
saw_snapshot = False
saw_live = False
# Bounded — real loop produces keepalive, snapshot, (waits), then
# forwarded event. Max 5 iterations covers pathological orderings.
for _ in range(5):
frame = _as_text(await gen.__anext__())
if "event: snapshot" in frame:
saw_snapshot = True
if "event: mutation.applied" in frame:
saw_live = True
break
return saw_snapshot, saw_live
try:
saw_snapshot, saw_live = await asyncio.wait_for(_drive(), timeout=5.0)
finally:
pub_task.cancel()
try:
await pub_task
except (asyncio.CancelledError, Exception):
pass
await gen.aclose()
assert saw_snapshot
assert saw_live

View File

@@ -0,0 +1,148 @@
"""Phase 3 Step 1 — parity between repo dict output and Pydantic DTOs.
These tests pin the contract that repo-hydrated dicts deserialize
cleanly into the REST DTOs. If a repo-row shape drifts, the DTO test
fails before any endpoint rides on the stale contract.
"""
from __future__ import annotations
import pytest
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import hydrate, persist, transition_status
from decnet.topology.status import TopologyStatus
from decnet.web.db.factory import get_repository
from decnet.web.db.models import (
DeckyRow,
EdgeRow,
LANRow,
MutationEnqueueRequest,
MutationRow,
TopologyDetail,
TopologyGenerateRequest,
TopologyListResponse,
TopologyStatusEventRow,
TopologySummary,
)
from decnet.web.router.topology import topology_router
def _cfg() -> TopologyConfig:
return TopologyConfig(
name="dto-parity",
depth=1,
branching_factor=1,
deckies_per_lan_min=1,
deckies_per_lan_max=1,
services_explicit=["ssh"],
randomize_services=False,
seed=0,
)
@pytest.fixture
async def repo(tmp_path):
r = get_repository(db_path=str(tmp_path / "dto.db"))
await r.initialize()
return r
def test_router_skeleton_mounted():
"""topology_router lives under /topologies and is import-safe."""
assert topology_router.prefix == "/topologies"
assert "topologies" in (topology_router.tags or [])
def test_generate_request_accepts_cli_shape():
"""TopologyGenerateRequest mirrors the CLI flags."""
req = TopologyGenerateRequest(
name="n",
depth=2,
branching_factor=2,
deckies_per_lan_min=1,
deckies_per_lan_max=3,
services_explicit=["ssh", "ftp"],
randomize_services=False,
seed=7,
)
assert req.depth == 2
assert req.services_explicit == ["ssh", "ftp"]
def test_mutation_request_rejects_unknown_op():
"""Literal guard is what gives the frontend a free 422 contract."""
with pytest.raises(ValueError):
MutationEnqueueRequest(op="teleport_lan", payload={})
@pytest.mark.anyio
async def test_summary_accepts_repo_topology_row(repo):
plan = generate(_cfg())
tid = await persist(repo, plan)
row = await repo.get_topology(tid)
summary = TopologySummary(**row)
assert summary.id == tid
assert summary.version == 1
# Defaults surface cleanly on a fresh topology.
assert summary.needs_resync is False
assert summary.target_host_uuid is None
@pytest.mark.anyio
async def test_summary_surfaces_needs_resync_flag(repo):
"""When the heartbeat handler flags a topology for resync, the API
list/detail views must expose it so operators can debug without
shelling into the DB."""
plan = generate(_cfg())
tid = await persist(repo, plan)
await repo.set_topology_resync(tid, True)
row = await repo.get_topology(tid)
summary = TopologySummary(**row)
assert summary.needs_resync is True
@pytest.mark.anyio
async def test_detail_accepts_hydrated_shape(repo):
plan = generate(_cfg())
tid = await persist(repo, plan)
hydrated = await hydrate(repo, tid)
detail = TopologyDetail(
topology=TopologySummary(**hydrated["topology"]),
lans=[LANRow(**l) for l in hydrated["lans"]],
deckies=[DeckyRow(**d) for d in hydrated["deckies"]],
edges=[EdgeRow(**e) for e in hydrated["edges"]],
)
assert detail.topology.id == tid
assert len(detail.lans) == len(hydrated["lans"])
assert len(detail.deckies) == len(hydrated["deckies"])
@pytest.mark.anyio
async def test_mutation_row_accepts_repo_row(repo):
plan = generate(_cfg())
tid = await persist(repo, plan)
mid = await repo.enqueue_topology_mutation(
tid, "add_lan", {"name": "LAN-X"}
)
rows = await repo.list_topology_mutations(tid)
assert rows and rows[0]["id"] == mid
m = MutationRow(**rows[0])
assert m.op == "add_lan"
assert m.payload == {"name": "LAN-X"}
@pytest.mark.anyio
async def test_status_event_row_accepts_repo_row(repo):
plan = generate(_cfg())
tid = await persist(repo, plan)
await transition_status(repo, tid, TopologyStatus.DEPLOYING)
events = await repo.list_topology_status_events(tid)
assert events
TopologyStatusEventRow(**events[0])
def test_list_response_envelope_shape():
resp = TopologyListResponse(total=0, limit=50, offset=0, data=[])
assert resp.total == 0
assert resp.data == []

View File

@@ -0,0 +1,203 @@
"""Phase 3 Step 5 — live mutation queue endpoints."""
from __future__ import annotations
import pytest
from decnet.bus import app as _bus_app
from decnet.bus import topics as _topics
from decnet.bus.fake import FakeBus
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import persist, transition_status
from decnet.topology.status import TopologyStatus
from decnet.web.dependencies import repo as _repo
_V1 = "/api/v1/topologies"
def _cfg(name: str = "draft") -> TopologyConfig:
return TopologyConfig(
name=name,
depth=1,
branching_factor=1,
deckies_per_lan_min=1,
deckies_per_lan_max=1,
services_explicit=["ssh"],
randomize_services=False,
seed=0,
)
async def _seed_active(name: str = "mutation-target") -> str:
topology_id = await persist(_repo, generate(_cfg(name)))
await transition_status(_repo, topology_id, TopologyStatus.DEPLOYING)
await transition_status(_repo, topology_id, TopologyStatus.ACTIVE)
return topology_id
def _hdr(token: str) -> dict:
return {"Authorization": f"Bearer {token}"}
# ── POST /mutations ───────────────────────────────────────────────
@pytest.mark.anyio
async def test_enqueue_ok(client, auth_token):
topology_id = await _seed_active("enq-ok")
r = await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "add_lan", "payload": {"name": "new-lan"}},
headers=_hdr(auth_token),
)
assert r.status_code == 202, r.text
body = r.json()
assert body["state"] == "pending"
assert body["mutation_id"]
@pytest.mark.anyio
async def test_enqueue_blocked_when_pending(client, auth_token):
topology_id = await persist(_repo, generate(_cfg("enq-pending")))
# stays in 'pending'
r = await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "add_lan", "payload": {"name": "x"}},
headers=_hdr(auth_token),
)
assert r.status_code == 409
@pytest.mark.anyio
async def test_enqueue_unknown_op_rejected(client, auth_token):
topology_id = await _seed_active("enq-bad-op")
r = await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "frobnicate", "payload": {}},
headers=_hdr(auth_token),
)
# Literal-mismatch on MutationEnqueueRequest.op — the project's
# validation handler leaves these as 422.
assert r.status_code in (400, 422)
@pytest.mark.anyio
async def test_enqueue_missing_topology_404(client, auth_token):
r = await client.post(
f"{_V1}/nope/mutations",
json={"op": "add_lan", "payload": {}},
headers=_hdr(auth_token),
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_enqueue_requires_admin(client, viewer_token):
topology_id = await _seed_active("enq-viewer")
r = await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "add_lan", "payload": {"name": "x"}},
headers=_hdr(viewer_token),
)
assert r.status_code == 403
# ── GET /mutations ────────────────────────────────────────────────
@pytest.mark.anyio
async def test_list_empty(client, auth_token):
topology_id = await _seed_active("list-empty")
r = await client.get(
f"{_V1}/{topology_id}/mutations",
headers=_hdr(auth_token),
)
assert r.status_code == 200
assert r.json() == []
@pytest.mark.anyio
async def test_list_after_enqueue(client, auth_token):
topology_id = await _seed_active("list-after")
await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "update_lan", "payload": {"id": "lan-1", "patch": {"x": 10}}},
headers=_hdr(auth_token),
)
r = await client.get(
f"{_V1}/{topology_id}/mutations",
headers=_hdr(auth_token),
)
assert r.status_code == 200
rows = r.json()
assert len(rows) == 1
assert rows[0]["op"] == "update_lan"
assert rows[0]["state"] == "pending"
@pytest.mark.anyio
async def test_list_state_filter(client, auth_token):
topology_id = await _seed_active("list-filter")
await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "add_lan", "payload": {"name": "a"}},
headers=_hdr(auth_token),
)
r = await client.get(
f"{_V1}/{topology_id}/mutations?state=applied",
headers=_hdr(auth_token),
)
assert r.status_code == 200
assert r.json() == [] # nothing has been marked applied yet
@pytest.mark.anyio
async def test_list_viewer_ok(client, viewer_token):
topology_id = await _seed_active("list-viewer")
r = await client.get(
f"{_V1}/{topology_id}/mutations",
headers=_hdr(viewer_token),
)
assert r.status_code == 200
# ── Bus publish on enqueue (DEBT-030) ─────────────────────────────
@pytest.fixture
def _fake_app_bus(monkeypatch):
"""Replace the process-wide app bus with an in-process FakeBus."""
bus = FakeBus()
async def _get() -> FakeBus:
if not bus._connected:
await bus.connect()
return bus
monkeypatch.setattr(_bus_app, "get_app_bus", _get)
# Also patch the re-export in the route module.
from decnet.web.router.topology import api_mutations as _mod
monkeypatch.setattr(_mod, "get_app_bus", _get)
return bus
@pytest.mark.anyio
async def test_enqueue_publishes_on_bus(client, auth_token, _fake_app_bus):
topology_id = await _seed_active("enq-pub")
sub = _fake_app_bus.subscribe(
_topics.topology_mutation(topology_id, _topics.MUTATION_ENQUEUED),
)
async with sub:
r = await client.post(
f"{_V1}/{topology_id}/mutations",
json={"op": "add_lan", "payload": {"name": "pub-lan"}},
headers=_hdr(auth_token),
)
assert r.status_code == 202
mutation_id = r.json()["mutation_id"]
import asyncio
event = await asyncio.wait_for(sub.__aiter__().__anext__(), timeout=1.0)
assert event.type == _topics.MUTATION_ENQUEUED
assert event.payload["mutation_id"] == mutation_id
assert event.payload["op"] == "add_lan"

View File

@@ -0,0 +1,180 @@
"""Per-topology persona endpoints — GET/PUT /topologies/{id}/personas."""
from __future__ import annotations
import json
import pytest
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import persist
from decnet.web.dependencies import repo as _repo
_V1 = "/api/v1/topologies"
def _cfg(name: str = "personas") -> TopologyConfig:
return TopologyConfig(
name=name,
depth=1,
branching_factor=1,
deckies_per_lan_min=1,
deckies_per_lan_max=1,
services_explicit=["ssh"],
randomize_services=False,
seed=0,
)
async def _seed(name: str = "personas") -> str:
return await persist(_repo, generate(_cfg(name)))
def _persona(email: str, name: str = "Jane Doe") -> dict:
return {
"name": name,
"email": email,
"role": "Admin",
"tone": "formal",
"mannerisms": ["uses bullet points"],
}
@pytest.mark.anyio
async def test_get_default_empty(client, auth_token):
tid = await _seed("get-empty")
r = await client.get(
f"{_V1}/{tid}/personas",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200, r.text
body = r.json()
assert body["topology_id"] == tid
assert body["personas"] == []
assert body["language_default"] == "en"
@pytest.mark.anyio
async def test_get_404(client, auth_token):
r = await client.get(
f"{_V1}/does-not-exist/personas",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_put_then_get(client, auth_token):
tid = await _seed("put-roundtrip")
payload = {"personas": [
_persona("a@example.com", "Alice"),
_persona("b@example.com", "Bob"),
]}
r = await client.put(
f"{_V1}/{tid}/personas",
json=payload,
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200, r.text
assert len(r.json()["personas"]) == 2
r2 = await client.get(
f"{_V1}/{tid}/personas",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r2.status_code == 200
emails = [p["email"] for p in r2.json()["personas"]]
assert emails == ["a@example.com", "b@example.com"]
# Persisted as JSON string in the topology row.
topo = await _repo.get_topology(tid)
assert isinstance(topo["email_personas"], str)
stored = json.loads(topo["email_personas"])
assert {p["email"] for p in stored} == {"a@example.com", "b@example.com"}
@pytest.mark.anyio
async def test_put_empty_clears(client, auth_token):
tid = await _seed("put-empty")
await client.put(
f"{_V1}/{tid}/personas",
json={"personas": [_persona("x@example.com")]},
headers={"Authorization": f"Bearer {auth_token}"},
)
r = await client.put(
f"{_V1}/{tid}/personas",
json={"personas": []},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200
assert r.json()["personas"] == []
@pytest.mark.anyio
async def test_put_non_list_400(client, auth_token):
tid = await _seed("put-non-list")
r = await client.put(
f"{_V1}/{tid}/personas",
json={"personas": "not a list"},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 400
@pytest.mark.anyio
async def test_put_all_invalid_400(client, auth_token):
tid = await _seed("put-all-bad")
r = await client.put(
f"{_V1}/{tid}/personas",
json={"personas": [{"email": "no-at-sign"}, {"name": "no-email"}]},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 400
@pytest.mark.anyio
async def test_put_partial_invalid_keeps_valid(client, auth_token):
"""Mirror the global-pool drop-invalid semantics.
The endpoint silently drops bad entries; operators discover what
landed by reading back the GET.
"""
tid = await _seed("put-partial")
r = await client.put(
f"{_V1}/{tid}/personas",
json={"personas": [
_persona("good@example.com"),
{"name": "missing email"},
]},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200
body = r.json()
assert [p["email"] for p in body["personas"]] == ["good@example.com"]
@pytest.mark.anyio
async def test_put_404_on_missing_topology(client, auth_token):
r = await client.put(
f"{_V1}/does-not-exist/personas",
json={"personas": [_persona("x@example.com")]},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_get_does_not_shadow_existing_topology_id(client, auth_token):
"""Ensure the personas subroute is registered before the bare /{id}.
If the literal `/personas` segment got shadowed by the parameterized
`/{id}` route, GET would return the topology body instead of 404 for
a missing personas resource. Sanity-check the order.
"""
tid = await _seed("shadow-check")
r = await client.get(
f"{_V1}/{tid}/personas",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200
assert "personas" in r.json()

View File

@@ -0,0 +1,169 @@
"""Phase 3 Step 2 — read endpoints: list / get / status-events / catalog."""
from __future__ import annotations
import pytest
from sqlmodel import select as _ss_select
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import persist, transition_status
from decnet.topology.status import TopologyStatus
from decnet.web.db.models import Topology as _TopologyTable
from decnet.web.dependencies import repo as _repo
_V1 = "/api/v1/topologies"
_LIST = f"{_V1}/"
def _cfg(name: str = "draft") -> TopologyConfig:
return TopologyConfig(
name=name,
depth=1,
branching_factor=1,
deckies_per_lan_min=1,
deckies_per_lan_max=1,
services_explicit=["ssh"],
randomize_services=False,
seed=0,
)
async def _seed(name: str = "draft") -> str:
return await persist(_repo, generate(_cfg(name)))
@pytest.mark.anyio
async def test_list_empty_ok(client, auth_token):
r = await client.get(_LIST, headers={"Authorization": f"Bearer {auth_token}"})
assert r.status_code == 200
body = r.json()
assert body["total"] == 0
assert body["data"] == []
@pytest.mark.anyio
async def test_list_requires_auth(client):
r = await client.get(_LIST)
assert r.status_code == 401
@pytest.mark.anyio
async def test_list_viewer_allowed(client, viewer_token):
r = await client.get(_LIST, headers={"Authorization": f"Bearer {viewer_token}"})
assert r.status_code == 200
@pytest.mark.anyio
async def test_list_with_topology_and_pagination(client, auth_token):
tid1 = await _seed("alpha")
await _seed("beta")
r = await client.get(
f"{_LIST}?limit=1&offset=0",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200
body = r.json()
assert body["total"] == 2
assert len(body["data"]) == 1
assert body["data"][0]["id"] in {tid1, body["data"][0]["id"]}
@pytest.mark.anyio
async def test_get_topology_hydrated(client, auth_token):
tid = await _seed("detail")
r = await client.get(
f"{_V1}/{tid}", headers={"Authorization": f"Bearer {auth_token}"}
)
assert r.status_code == 200
body = r.json()
assert body["topology"]["id"] == tid
assert body["topology"]["version"] == 1
assert body["lans"], "seeded topology has at least one LAN"
assert body["deckies"]
@pytest.mark.anyio
async def test_get_topology_404(client, auth_token):
r = await client.get(
f"{_V1}/does-not-exist",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_status_events_after_transition(client, auth_token):
tid = await _seed("events")
await transition_status(_repo, tid, TopologyStatus.DEPLOYING)
r = await client.get(
f"{_V1}/{tid}/status-events",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200
rows = r.json()
assert rows and rows[0]["to_status"] == "deploying"
@pytest.mark.anyio
async def test_status_events_404_on_missing(client, auth_token):
r = await client.get(
f"{_V1}/nope/status-events",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_services_catalog(client, viewer_token):
r = await client.get(
f"{_V1}/services",
headers={"Authorization": f"Bearer {viewer_token}"},
)
assert r.status_code == 200
body = r.json()
assert isinstance(body["services"], list)
assert "ssh" in body["services"]
@pytest.mark.anyio
async def test_next_subnet_starts_at_base(client, auth_token):
r = await client.get(
f"{_V1}/next-subnet?base=172.20",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 200
assert r.json()["subnet"].startswith("172.20.")
@pytest.mark.anyio
async def test_next_ip_skips_gateway_and_existing(client, auth_token):
tid = await _seed("ipalloc")
# Find a LAN and existing decky IPs from the seeded topology.
r = await client.get(
f"{_V1}/{tid}", headers={"Authorization": f"Bearer {auth_token}"}
)
body = r.json()
lan = body["lans"][0]
taken = {
(d.get("decky_config") or {}).get("ips_by_lan", {}).get(lan["name"])
for d in body["deckies"]
}
taken.discard(None)
r2 = await client.get(
f"{_V1}/{tid}/lans/{lan['id']}/next-ip",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r2.status_code == 200
ip = r2.json()["ip"]
assert ip not in taken
assert not ip.endswith(".1") # gateway skipped
@pytest.mark.anyio
async def test_next_ip_404_lan(client, auth_token):
tid = await _seed("nopelan")
r = await client.get(
f"{_V1}/{tid}/lans/bogus/next-ip",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404

View File

@@ -0,0 +1,319 @@
"""Phase 3 Step 3 — write endpoints: create / delete / deploy."""
from __future__ import annotations
from unittest.mock import AsyncMock, patch
import pytest
from decnet.topology.config import TopologyConfig
from decnet.topology.generator import generate
from decnet.topology.persistence import persist, transition_status
from decnet.topology.status import TopologyStatus
from decnet.web.dependencies import repo as _repo
_V1 = "/api/v1/topologies"
def _generate_payload(name: str = "from-api") -> dict:
return {
"name": name,
"depth": 1,
"branching_factor": 1,
"deckies_per_lan_min": 1,
"deckies_per_lan_max": 1,
"services_explicit": ["ssh"],
"randomize_services": False,
"seed": 1,
}
def _cfg(name: str = "draft") -> TopologyConfig:
return TopologyConfig(
name=name,
depth=1,
branching_factor=1,
deckies_per_lan_min=1,
deckies_per_lan_max=1,
services_explicit=["ssh"],
randomize_services=False,
seed=0,
)
async def _seed(name: str = "draft") -> str:
return await persist(_repo, generate(_cfg(name)))
# ── POST /topologies ──────────────────────────────────────────────
@pytest.mark.anyio
async def test_create_ok(client, auth_token):
r = await client.post(
f"{_V1}/",
json=_generate_payload(),
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 201, r.text
body = r.json()
assert body["status"] == TopologyStatus.PENDING
assert body["name"] == "from-api"
# Children were persisted.
lans = await _repo.list_lans_for_topology(body["id"])
assert len(lans) >= 1
@pytest.mark.anyio
async def test_create_requires_admin(client, viewer_token):
r = await client.post(
f"{_V1}/",
json=_generate_payload(),
headers={"Authorization": f"Bearer {viewer_token}"},
)
assert r.status_code == 403
@pytest.mark.anyio
async def test_create_requires_auth(client):
r = await client.post(f"{_V1}/", json=_generate_payload())
assert r.status_code == 401
@pytest.mark.anyio
async def test_create_duplicate_name_is_409(client, auth_token):
"""Re-using an existing topology name must return a clean 409, not
bubble the raw MySQL IntegrityError up to a 500."""
payload = _generate_payload()
first = await client.post(
f"{_V1}/",
json=payload,
headers={"Authorization": f"Bearer {auth_token}"},
)
assert first.status_code == 201, first.text
second = await client.post(
f"{_V1}/",
json=payload,
headers={"Authorization": f"Bearer {auth_token}"},
)
assert second.status_code == 409, second.text
assert payload["name"] in second.json()["detail"]
@pytest.mark.anyio
async def test_create_bad_body(client, auth_token):
r = await client.post(
f"{_V1}/",
json={"name": "x"}, # missing required fields
headers={"Authorization": f"Bearer {auth_token}"},
)
# Project-wide validation handler: missing fields → 400 (not 422).
assert r.status_code == 400
# ── DELETE /topologies/{id} ───────────────────────────────────────
@pytest.mark.anyio
async def test_delete_pending_ok(client, auth_token):
topology_id = await _seed("for-delete")
r = await client.delete(
f"{_V1}/{topology_id}",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 204
assert await _repo.get_topology(topology_id) is None
@pytest.mark.anyio
async def test_delete_active_blocked(client, auth_token):
topology_id = await _seed("for-delete-active")
await transition_status(_repo, topology_id, TopologyStatus.DEPLOYING)
await transition_status(_repo, topology_id, TopologyStatus.ACTIVE)
r = await client.delete(
f"{_V1}/{topology_id}",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 409
assert await _repo.get_topology(topology_id) is not None
@pytest.mark.anyio
async def test_delete_missing_404(client, auth_token):
r = await client.delete(
f"{_V1}/does-not-exist",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_delete_requires_admin(client, viewer_token):
topology_id = await _seed("viewer-delete")
r = await client.delete(
f"{_V1}/{topology_id}",
headers={"Authorization": f"Bearer {viewer_token}"},
)
assert r.status_code == 403
# ── POST /topologies/{id}/deploy ──────────────────────────────────
@pytest.mark.anyio
async def test_deploy_accepts_pending(client, auth_token):
topology_id = await _seed("for-deploy")
with patch(
"decnet.web.router.topology.api_deploy_topology.deploy_topology",
new=AsyncMock(return_value=None),
) as mock_deploy:
r = await client.post(
f"{_V1}/{topology_id}/deploy",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 202, r.text
body = r.json()
assert body["id"] == topology_id
# BackgroundTasks run after the response, so the mock must have been invoked
# by the time the client context exits.
mock_deploy.assert_called_once()
@pytest.mark.anyio
async def test_deploy_non_pending_blocked(client, auth_token):
topology_id = await _seed("for-deploy-blocked")
await transition_status(_repo, topology_id, TopologyStatus.DEPLOYING)
r = await client.post(
f"{_V1}/{topology_id}/deploy",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 409
@pytest.mark.anyio
async def test_deploy_missing_404(client, auth_token):
r = await client.post(
f"{_V1}/missing/deploy",
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 404
@pytest.mark.anyio
async def test_deploy_requires_admin(client, viewer_token):
topology_id = await _seed("viewer-deploy")
r = await client.post(
f"{_V1}/{topology_id}/deploy",
headers={"Authorization": f"Bearer {viewer_token}"},
)
assert r.status_code == 403
# ── mode / target_host_uuid pairing (Step 1) ──────────────────────
async def _seed_swarm_host(uuid_: str = "host-uuid-1", status: str = "enrolled") -> None:
await _repo.add_swarm_host(
{
"uuid": uuid_,
"name": f"host-{uuid_}",
"address": "10.9.9.9",
"agent_port": 8765,
"status": status,
"client_cert_fingerprint": "a" * 64,
"cert_bundle_path": "/tmp/ignored",
}
)
@pytest.mark.anyio
async def test_create_blank_agent_mode_ok(client, auth_token):
await _seed_swarm_host("host-ok", status="active")
r = await client.post(
f"{_V1}/blank",
json={"name": "blank-agent", "mode": "agent", "target_host_uuid": "host-ok"},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 201, r.text
body = r.json()
assert body["mode"] == "agent"
assert body["target_host_uuid"] == "host-ok"
@pytest.mark.anyio
async def test_create_blank_agent_without_host_is_400(client, auth_token):
r = await client.post(
f"{_V1}/blank",
json={"name": "blank-agent-no-host", "mode": "agent"},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 400
assert "target_host_uuid" in r.json()["detail"]
@pytest.mark.anyio
async def test_create_blank_agent_unknown_host_is_400(client, auth_token):
r = await client.post(
f"{_V1}/blank",
json={
"name": "blank-agent-unknown",
"mode": "agent",
"target_host_uuid": "does-not-exist",
},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 400
assert "unknown" in r.json()["detail"].lower()
@pytest.mark.anyio
async def test_create_blank_unihost_with_host_is_400(client, auth_token):
await _seed_swarm_host("host-unused")
r = await client.post(
f"{_V1}/blank",
json={
"name": "blank-unihost-with-host",
"mode": "unihost",
"target_host_uuid": "host-unused",
},
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 400
@pytest.mark.anyio
async def test_create_agent_mode_ok(client, auth_token):
await _seed_swarm_host("host-gen")
payload = {
**_generate_payload("gen-agent"),
"mode": "agent",
"target_host_uuid": "host-gen",
}
r = await client.post(
f"{_V1}/",
json=payload,
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 201, r.text
body = r.json()
assert body["mode"] == "agent"
assert body["target_host_uuid"] == "host-gen"
@pytest.mark.anyio
async def test_create_agent_unreachable_host_is_400(client, auth_token):
await _seed_swarm_host("host-dead", status="unreachable")
payload = {
**_generate_payload("gen-agent-dead"),
"mode": "agent",
"target_host_uuid": "host-dead",
}
r = await client.post(
f"{_V1}/",
json=payload,
headers={"Authorization": f"Bearer {auth_token}"},
)
assert r.status_code == 400