594 lines
28 KiB
Python
594 lines
28 KiB
Python
# backend/tests/api/test_agent_runs_coverage.py
|
|
# #region Test.Api.AgentRuns.Coverage [C:3] [TYPE Module] [SEMANTICS test,api,agent-run,coverage,error-paths]
|
|
# @BRIEF Route-level coverage for every agent-run endpoint — success, 4xx error mapping,
|
|
# 403 RBAC, 404 ownership, and external-failure (500) paths with rollback assertions.
|
|
# @RELATION BINDS_TO -> [Api.AgentRuns]
|
|
# @TEST_CONTRACT: [HttpRequest] -> [2xx/4xx/5xx + payload]
|
|
# @TEST_SCENARIO: endpoint_success -> 200/201 with service return serialized through response model
|
|
# @TEST_SCENARIO: service_value_error -> 4xx mapping (422 create/draft, 409 events/gates/save/decide/consume, 404 events)
|
|
# @TEST_SCENARIO: service_external_fail -> 500 with db.rollback and re-raise
|
|
# @TEST_EDGE: missing_permission -> 403 for EXECUTE/READ/WRITE-guarded endpoints (limited user)
|
|
# @TEST_EDGE: invalid_payload -> 422 from Pydantic (sequence=0, bad payload_hash, empty target_paths, bad decision, empty scenario_id)
|
|
# @TEST_EDGE: draft_bytes_missing -> 404 "Draft content not found" when storage returns None
|
|
# @TEST_EDGE: consume_materialize_only_confirmed_save -> worktree materialization runs only for confirmed save_scenario_draft gates
|
|
# @TEST_EDGE: foreign_or_missing_run -> 404 via service None/ValueError (ownership boundary)
|
|
# @TEST_INVARIANT: Browser reads require run ownership or admin permission -> VERIFIED_BY: foreign_or_missing_run, missing_permission
|
|
# @TEST_INVARIANT: Terminal runs are immutable -> VERIFIED_BY: service_value_error (409 on terminal run writes)
|
|
import pytest
|
|
from types import SimpleNamespace
|
|
from unittest.mock import ANY, AsyncMock, MagicMock, patch
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from src.api.routes.agent_runs import router
|
|
from src.core.database import get_db
|
|
from src.dependencies import get_current_user
|
|
|
|
# ── Hardcoded fixtures (never computed from production code) ──
|
|
|
|
SNAPSHOT_FIXTURE = {
|
|
"id": "run-1",
|
|
"conversation_id": "conv-1",
|
|
"user_id": "user-1",
|
|
"intent": "dashboard_scenario_build",
|
|
"trigger": "manual",
|
|
"dashboard_id": "42",
|
|
"environment_id": "dev",
|
|
"context_snapshot": {"objectId": "42", "envId": "dev"},
|
|
"status": "RUNNING",
|
|
"current_stage": "context",
|
|
"last_sequence": 1,
|
|
"created_at": "2026-01-01T00:00:00Z",
|
|
"updated_at": "2026-01-01T00:00:00Z",
|
|
}
|
|
|
|
EVENT_FIXTURE = {
|
|
"id": "evt-1",
|
|
"run_id": "run-1",
|
|
"sequence": 1,
|
|
"event_type": "run_started",
|
|
"stage": "context",
|
|
"status": "active",
|
|
"payload": {"dashboard_id": "42"},
|
|
"occurred_at": "2026-01-01T00:00:00Z",
|
|
}
|
|
|
|
DRAFT_FIXTURE = {
|
|
"id": "draft-1",
|
|
"kind": "scenario_pack",
|
|
"name": "scenario.yaml",
|
|
"intended_path": "dashboard-tests/scenario.yaml",
|
|
"sha256": "a" * 64,
|
|
"validation_status": "valid",
|
|
}
|
|
|
|
GATE_FIXTURE = {
|
|
"id": "gate-1",
|
|
"run_id": "run-1",
|
|
"operation": "repository_write",
|
|
"request_hash": "b" * 64,
|
|
"target_paths": ["test.yaml"],
|
|
"risk_level": "guarded",
|
|
"required_permission": "dashboard:testing:WRITE",
|
|
"status": "pending",
|
|
"reason_required": False,
|
|
}
|
|
|
|
CREATE_PAYLOAD = {
|
|
"context": {
|
|
"objectType": "dashboard",
|
|
"objectId": "42",
|
|
"envId": "dev",
|
|
"route": "/dashboards/42",
|
|
"contextVersion": 2,
|
|
"intent": "build_dashboard_test_scenario",
|
|
}
|
|
}
|
|
|
|
EVENT_PAYLOAD = {"event_type": "progress", "stage": "scenario", "status": "active", "sequence": 2}
|
|
EVENT_PAYLOAD_BARE = {"event_type": "heartbeat", "sequence": 3}
|
|
|
|
DRAFT_PAYLOAD = {
|
|
"kind": "scenario_pack",
|
|
"name": "scenario.yaml",
|
|
"intended_path": "dashboard-tests/scenario.yaml",
|
|
"sha256": "a" * 64,
|
|
"validation_status": "valid",
|
|
}
|
|
|
|
GATE_PAYLOAD = {
|
|
"operation": "repository_write",
|
|
"request_hash": "b" * 64,
|
|
"target_paths": ["test.yaml"],
|
|
"required_permission": "dashboard:testing:WRITE",
|
|
}
|
|
|
|
|
|
def _make_client(user, db, raise_server_exceptions=True):
|
|
app = FastAPI()
|
|
app.include_router(router)
|
|
app.dependency_overrides[get_db] = lambda: db
|
|
app.dependency_overrides[get_current_user] = lambda: user
|
|
return TestClient(app, raise_server_exceptions=raise_server_exceptions)
|
|
|
|
|
|
@pytest.fixture
|
|
def admin_user():
|
|
"""Admin identity — has_permission bypasses via is_admin."""
|
|
return SimpleNamespace(
|
|
id="user-1",
|
|
username="admin",
|
|
roles=[SimpleNamespace(is_admin=True, permissions=[])],
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def limited_user():
|
|
"""Non-admin identity with no permissions — every guarded endpoint must 403."""
|
|
return SimpleNamespace(
|
|
id="user-2",
|
|
username="qa_analyst",
|
|
roles=[SimpleNamespace(is_admin=False, permissions=[])],
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
def db():
|
|
return MagicMock()
|
|
|
|
|
|
class TestCreateRun:
|
|
"""POST /api/agent/runs"""
|
|
|
|
def test_success_201(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.create_agent_run", return_value=SNAPSHOT_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs", json=CREATE_PAYLOAD)
|
|
assert resp.status_code == 201
|
|
assert resp.json()["id"] == "run-1"
|
|
svc.assert_called_once_with(db, ANY, user_id="user-1")
|
|
db.commit.assert_called_once()
|
|
|
|
def test_value_error_422_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.create_agent_run",
|
|
side_effect=ValueError("intent must be build_dashboard_test_scenario")):
|
|
resp = client.post("/api/agent/runs", json=CREATE_PAYLOAD)
|
|
assert resp.status_code == 422
|
|
assert resp.json()["detail"] == "intent must be build_dashboard_test_scenario"
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.create_agent_run", side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs", json=CREATE_PAYLOAD)
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.post("/api/agent/runs", json=CREATE_PAYLOAD)
|
|
assert resp.status_code == 403
|
|
|
|
def test_invalid_payload_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
payload = {"context": {"objectType": "dashboard", "envId": "dev", "route": "/dashboards/42",
|
|
"contextVersion": 2, "intent": "build_dashboard_test_scenario"}}
|
|
resp = client.post("/api/agent/runs", json=payload)
|
|
assert resp.status_code == 422 # objectId missing
|
|
|
|
|
|
class TestGetSnapshot:
|
|
"""GET /api/agent/runs/{run_id}"""
|
|
|
|
def test_success_200(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.get_agent_run_snapshot", return_value=SNAPSHOT_FIXTURE) as svc:
|
|
resp = client.get("/api/agent/runs/run-1")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["status"] == "RUNNING"
|
|
svc.assert_called_once_with(db, "run-1", user_id="user-1")
|
|
|
|
|
|
class TestCreateEvent:
|
|
"""POST /api/agent/runs/{run_id}/events"""
|
|
|
|
def test_success_201_with_stage_and_status(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.append_event", return_value=EVENT_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/events", json=EVENT_PAYLOAD)
|
|
assert resp.status_code == 201
|
|
assert resp.json()["id"] == "evt-1"
|
|
svc.assert_called_once_with(
|
|
db, "run-1", user_id="user-1", event_type="progress",
|
|
stage="scenario", status="active", sequence=2, payload=None, payload_hash=None,
|
|
)
|
|
db.commit.assert_called_once()
|
|
|
|
def test_success_201_without_stage_and_status(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.append_event", return_value=EVENT_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/events", json=EVENT_PAYLOAD_BARE)
|
|
assert resp.status_code == 201
|
|
svc.assert_called_once_with(
|
|
db, "run-1", user_id="user-1", event_type="heartbeat",
|
|
stage=None, status=None, sequence=3, payload=None, payload_hash=None,
|
|
)
|
|
|
|
def test_value_error_409_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.append_event",
|
|
side_effect=ValueError("cannot append events to terminal run")):
|
|
resp = client.post("/api/agent/runs/run-1/events", json=EVENT_PAYLOAD)
|
|
assert resp.status_code == 409
|
|
assert resp.json()["detail"] == "cannot append events to terminal run"
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.append_event", side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs/run-1/events", json=EVENT_PAYLOAD)
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_invalid_sequence_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/events", json={"event_type": "progress", "sequence": 0})
|
|
assert resp.status_code == 422
|
|
|
|
def test_invalid_payload_hash_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/events",
|
|
json={"event_type": "progress", "sequence": 1, "payload_hash": "zz"})
|
|
assert resp.status_code == 422
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/events", json=EVENT_PAYLOAD)
|
|
assert resp.status_code == 403
|
|
|
|
|
|
class TestListEvents:
|
|
"""GET /api/agent/runs/{run_id}/events"""
|
|
|
|
def test_success_200(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.get_run_events", return_value=[EVENT_FIXTURE]) as svc:
|
|
resp = client.get("/api/agent/runs/run-1/events")
|
|
assert resp.status_code == 200
|
|
assert len(resp.json()) == 1
|
|
assert resp.json()[0]["sequence"] == 1
|
|
svc.assert_called_once_with(db, "run-1", user_id="user-1")
|
|
|
|
def test_foreign_run_404(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.get_run_events", side_effect=ValueError("run not found")):
|
|
resp = client.get("/api/agent/runs/run-9/events")
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "run not found"
|
|
|
|
|
|
class TestCreateDraft:
|
|
"""POST /api/agent/runs/{run_id}/drafts"""
|
|
|
|
def test_success_201(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.register_draft", return_value=DRAFT_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/drafts", json=DRAFT_PAYLOAD)
|
|
assert resp.status_code == 201
|
|
assert resp.json()["kind"] == "scenario_pack"
|
|
svc.assert_called_once_with(db, "run-1", user_id="user-1", req=ANY)
|
|
db.commit.assert_called_once()
|
|
|
|
def test_value_error_422_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.register_draft",
|
|
side_effect=ValueError("intended_path must be relative and free of parent traversal")):
|
|
resp = client.post("/api/agent/runs/run-1/drafts", json=DRAFT_PAYLOAD)
|
|
assert resp.status_code == 422
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.register_draft", side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs/run-1/drafts", json=DRAFT_PAYLOAD)
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/drafts", json=DRAFT_PAYLOAD)
|
|
assert resp.status_code == 403
|
|
|
|
def test_invalid_sha256_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
payload = {**DRAFT_PAYLOAD, "sha256": "too-short"}
|
|
resp = client.post("/api/agent/runs/run-1/drafts", json=payload)
|
|
assert resp.status_code == 422
|
|
|
|
|
|
class TestGetDraftContent:
|
|
"""GET /api/agent/runs/{run_id}/drafts/{draft_id}/content"""
|
|
|
|
SHA = "a" * 64
|
|
|
|
def _storage_mock(self, data=b"draft-bytes"):
|
|
storage = MagicMock()
|
|
storage.retrieve.return_value = data
|
|
return storage
|
|
|
|
def test_success_200_with_named_file(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
draft = SimpleNamespace(content_ref=f"draft:run-1:{self.SHA}", name="report.md", kind="other")
|
|
with patch("src.api.routes.agent_runs.get_draft", return_value=draft) as svc, \
|
|
patch("src.api.routes.agent_runs.get_draft_storage",
|
|
return_value=self._storage_mock()) as storage_svc:
|
|
resp = client.get("/api/agent/runs/run-1/drafts/draft-1/content")
|
|
assert resp.status_code == 200
|
|
assert resp.content == b"draft-bytes"
|
|
assert resp.headers["content-type"] == "application/octet-stream"
|
|
assert resp.headers["content-disposition"] == 'attachment; filename="report.md"'
|
|
svc.assert_called_once_with(db, "run-1", "draft-1", user_id="user-1")
|
|
storage_svc.assert_called_once()
|
|
|
|
def test_success_200_with_default_filename(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
draft = SimpleNamespace(content_ref=f"draft:run-1:{self.SHA}", name=None, kind="other")
|
|
with patch("src.api.routes.agent_runs.get_draft", return_value=draft), \
|
|
patch("src.api.routes.agent_runs.get_draft_storage", return_value=self._storage_mock()):
|
|
resp = client.get("/api/agent/runs/run-1/drafts/draft-1/content")
|
|
assert resp.status_code == 200
|
|
assert resp.headers["content-disposition"] == 'attachment; filename="draft"'
|
|
|
|
def test_foreign_run_404(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.get_draft", side_effect=ValueError("run not found or access denied")), \
|
|
patch("src.api.routes.agent_runs.get_draft_storage", return_value=self._storage_mock()):
|
|
resp = client.get("/api/agent/runs/run-9/drafts/draft-1/content")
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "run not found or access denied"
|
|
|
|
def test_missing_stored_bytes_404(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
draft = SimpleNamespace(content_ref=f"draft:run-1:{self.SHA}", name="x.yaml")
|
|
with patch("src.api.routes.agent_runs.get_draft", return_value=draft), \
|
|
patch("src.api.routes.agent_runs.get_draft_storage", return_value=self._storage_mock(data=None)):
|
|
resp = client.get("/api/agent/runs/run-1/drafts/draft-1/content")
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "Draft content not found"
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.get("/api/agent/runs/run-1/drafts/draft-1/content")
|
|
assert resp.status_code == 403
|
|
|
|
|
|
class TestCreateGate:
|
|
"""POST /api/agent/runs/{run_id}/gates"""
|
|
|
|
def test_success_201(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.request_approval", return_value=GATE_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/gates", json=GATE_PAYLOAD)
|
|
assert resp.status_code == 201
|
|
assert resp.json()["id"] == "gate-1"
|
|
svc.assert_called_once_with(
|
|
db, "run-1", user_id="user-1", operation="repository_write",
|
|
request_hash="b" * 64, target_paths=["test.yaml"], risk_level="guarded",
|
|
required_permission="dashboard:testing:WRITE", reason_required=False, expire_seconds=300,
|
|
)
|
|
db.commit.assert_called_once()
|
|
|
|
def test_value_error_409_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.request_approval",
|
|
side_effect=ValueError("a pending gate already exists for this run")):
|
|
resp = client.post("/api/agent/runs/run-1/gates", json=GATE_PAYLOAD)
|
|
assert resp.status_code == 409
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.request_approval", side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs/run-1/gates", json=GATE_PAYLOAD)
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/gates", json=GATE_PAYLOAD)
|
|
assert resp.status_code == 403
|
|
|
|
def test_invalid_target_paths_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
payload = {**GATE_PAYLOAD, "target_paths": []}
|
|
resp = client.post("/api/agent/runs/run-1/gates", json=payload)
|
|
assert resp.status_code == 422
|
|
|
|
def test_invalid_expire_seconds_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
payload = {**GATE_PAYLOAD, "expire_seconds": 10}
|
|
resp = client.post("/api/agent/runs/run-1/gates", json=payload)
|
|
assert resp.status_code == 422
|
|
|
|
|
|
class TestRequestScenarioSave:
|
|
"""POST /api/agent/runs/{run_id}/save-request"""
|
|
|
|
def test_success_201(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.request_scenario_save_gate",
|
|
return_value=GATE_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/save-request", json={"scenario_id": "sc-1"})
|
|
assert resp.status_code == 201
|
|
assert resp.json()["operation"] == "repository_write"
|
|
svc.assert_called_once_with(db, "run-1", "user-1", "sc-1")
|
|
db.commit.assert_called_once()
|
|
|
|
def test_value_error_409_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.request_scenario_save_gate",
|
|
side_effect=ValueError("DRAFT_REGENERATION_REQUIRED: no saved draft artifacts for this run")):
|
|
resp = client.post("/api/agent/runs/run-1/save-request", json={"scenario_id": "sc-1"})
|
|
assert resp.status_code == 409
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.request_scenario_save_gate",
|
|
side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs/run-1/save-request", json={"scenario_id": "sc-1"})
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/save-request", json={"scenario_id": "sc-1"})
|
|
assert resp.status_code == 403
|
|
|
|
def test_empty_scenario_id_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/save-request", json={"scenario_id": ""})
|
|
assert resp.status_code == 422
|
|
|
|
|
|
class TestDecideGate:
|
|
"""POST /api/agent/runs/{run_id}/gates/{gate_id}/decide"""
|
|
|
|
def test_success_confirm_200(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.decide_approval", return_value=GATE_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/decide", json={"decision": "confirm"})
|
|
assert resp.status_code == 200
|
|
assert resp.json()["status"] == "pending"
|
|
svc.assert_called_once_with(db, "run-1", "gate-1", user_id="user-1",
|
|
decision="confirm", reason=None)
|
|
db.commit.assert_called_once()
|
|
|
|
def test_success_deny_with_reason_200(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.decide_approval", return_value=GATE_FIXTURE) as svc:
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/decide",
|
|
json={"decision": "deny", "reason": "needs more evidence"})
|
|
assert resp.status_code == 200
|
|
svc.assert_called_once_with(db, "run-1", "gate-1", user_id="user-1",
|
|
decision="deny", reason="needs more evidence")
|
|
|
|
def test_value_error_409_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.decide_approval", side_effect=ValueError("gate already confirmed")):
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/decide", json={"decision": "confirm"})
|
|
assert resp.status_code == 409
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.decide_approval", side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/decide", json={"decision": "confirm"})
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_invalid_decision_422(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/decide", json={"decision": "maybe"})
|
|
assert resp.status_code == 422
|
|
|
|
|
|
class TestGetGateStatus:
|
|
"""GET /api/agent/runs/{run_id}/gates/{gate_id}/decide — read-only gate state"""
|
|
|
|
def test_success_200(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.get_gate_view", return_value=GATE_FIXTURE) as svc:
|
|
resp = client.get("/api/agent/runs/run-1/gates/gate-1/decide")
|
|
assert resp.status_code == 200
|
|
assert resp.json()["id"] == "gate-1"
|
|
svc.assert_called_once_with(db, "run-1", "gate-1", user_id="user-1")
|
|
|
|
def test_missing_gate_404(self, admin_user, db):
|
|
client = _make_client(admin_user, db)
|
|
with patch("src.api.routes.agent_runs.get_gate_view", return_value=None):
|
|
resp = client.get("/api/agent/runs/run-1/gates/gate-9/decide")
|
|
assert resp.status_code == 404
|
|
assert resp.json()["detail"] == "approval gate not found"
|
|
|
|
|
|
class TestConsumeGate:
|
|
"""POST /api/agent/runs/{run_id}/gates/{gate_id}/consume"""
|
|
|
|
def _client_with_gate(self, gate, db, user):
|
|
client = _make_client(user, db)
|
|
repo_cls = MagicMock()
|
|
repo_cls.return_value.get_gate.return_value = gate
|
|
return client, repo_cls
|
|
|
|
def test_success_gate_missing_200(self, admin_user, db):
|
|
client, repo_cls = self._client_with_gate(None, db, admin_user)
|
|
with patch("src.api.routes.agent_runs.AgentRunRepository", repo_cls), \
|
|
patch("src.api.routes.agent_runs.consume_approval", return_value=GATE_FIXTURE) as consume, \
|
|
patch("src.api.routes.agent_runs.materialize_pack_to_worktree", new=AsyncMock()) as materialize:
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 200
|
|
consume.assert_called_once_with(db, "run-1", "gate-1", user_id="user-1")
|
|
materialize.assert_not_called()
|
|
db.commit.assert_called_once()
|
|
|
|
def test_success_confirmed_save_gate_materializes(self, admin_user, db):
|
|
gate = SimpleNamespace(status="confirmed", operation="save_scenario_draft")
|
|
client, repo_cls = self._client_with_gate(gate, db, admin_user)
|
|
with patch("src.api.routes.agent_runs.AgentRunRepository", repo_cls), \
|
|
patch("src.api.routes.agent_runs.consume_approval", return_value=GATE_FIXTURE), \
|
|
patch("src.api.routes.agent_runs.materialize_pack_to_worktree", new=AsyncMock()) as materialize, \
|
|
patch("src.api.routes.agent_runs.register_consumed_save") as register:
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 200
|
|
materialize.assert_awaited_once_with(db, "run-1", "gate-1", "user-1")
|
|
register.assert_called_once_with(
|
|
db, run_id="run-1", user_id="user-1", owner_username="admin"
|
|
)
|
|
|
|
def test_confirmed_non_save_gate_skips_materialize(self, admin_user, db):
|
|
gate = SimpleNamespace(status="confirmed", operation="repository_write")
|
|
client, repo_cls = self._client_with_gate(gate, db, admin_user)
|
|
with patch("src.api.routes.agent_runs.AgentRunRepository", repo_cls), \
|
|
patch("src.api.routes.agent_runs.consume_approval", return_value=GATE_FIXTURE), \
|
|
patch("src.api.routes.agent_runs.materialize_pack_to_worktree", new=AsyncMock()) as materialize:
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 200
|
|
materialize.assert_not_called()
|
|
|
|
def test_pending_gate_skips_materialize(self, admin_user, db):
|
|
gate = SimpleNamespace(status="pending", operation="save_scenario_draft")
|
|
client, repo_cls = self._client_with_gate(gate, db, admin_user)
|
|
with patch("src.api.routes.agent_runs.AgentRunRepository", repo_cls), \
|
|
patch("src.api.routes.agent_runs.consume_approval", return_value=GATE_FIXTURE), \
|
|
patch("src.api.routes.agent_runs.materialize_pack_to_worktree", new=AsyncMock()) as materialize:
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 200
|
|
materialize.assert_not_called()
|
|
|
|
def test_value_error_409_with_rollback(self, admin_user, db):
|
|
client, repo_cls = self._client_with_gate(None, db, admin_user)
|
|
with patch("src.api.routes.agent_runs.AgentRunRepository", repo_cls), \
|
|
patch("src.api.routes.agent_runs.consume_approval",
|
|
side_effect=ValueError("gate must be confirmed, is pending")):
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 409
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_external_failure_500_with_rollback(self, admin_user, db):
|
|
client, repo_cls = self._client_with_gate(None, db, admin_user)
|
|
client = _make_client(admin_user, db, raise_server_exceptions=False)
|
|
with patch("src.api.routes.agent_runs.AgentRunRepository", repo_cls), \
|
|
patch("src.api.routes.agent_runs.consume_approval", side_effect=RuntimeError("db down")):
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 500
|
|
db.rollback.assert_called_once()
|
|
|
|
def test_missing_permission_403(self, limited_user, db):
|
|
client = _make_client(limited_user, db)
|
|
resp = client.post("/api/agent/runs/run-1/gates/gate-1/consume")
|
|
assert resp.status_code == 403
|
|
# #endregion Test.Api.AgentRuns.Coverage
|