briga-core-api / tests /test_admin_integration.py
yabeskn's picture
fix: change EXPOSE and uvicorn port from 8080 to 7860 in Dockerfile
b613c13
Raw History Blame Contribute Delete
11.5 kB
"""Integration tests for admin API endpoints.
Tests the full HTTP request/response cycle using httpx.AsyncClient
with an in-memory SQLite database. Unlike test_admin.py (unit tests
with mocked DB), these tests exercise the real database layer,
SQLAlchemy ORM, and FastAPI dependency injection.
Covers:
- GET /v1/admin/workflows -> list_workflows
- PATCH /v1/admin/workflows/{name} -> update_workflow
- POST /v1/admin/workflows/{name}/run -> run_workflow
"""
import os
# Force SQLite fallback before any app imports touch DATABASE_URL
os.environ["USE_SQLITE_FALLBACK"] = "true"
os.environ["DATABASE_URL"] = "sqlite+aiosqlite:///:memory:"
import pytest
import pytest_asyncio
from httpx import AsyncClient, ASGITransport
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from fastapi import FastAPI, Request
from starlette.middleware.base import BaseHTTPMiddleware
from app.database import get_db
from app.api.admin import router as admin_router
# ─── Test Database ──────────────────────────────────────────────────────────
TEST_DATABASE_URL = "sqlite+aiosqlite:///:memory:"
test_engine = create_async_engine(TEST_DATABASE_URL, echo=False)
TestSessionLocal = async_sessionmaker(
test_engine, class_=AsyncSession, expire_on_commit=False
)
async def override_get_db():
"""Yield a session from the in-memory test database."""
async with TestSessionLocal() as session:
yield session
# ─── Auth Middleware for Tests ──────────────────────────────────────────────
class TestAuthMiddleware(BaseHTTPMiddleware):
"""Inject admin auth state into every request during tests."""
def __init__(self, app, role="admin", email="admin@briga.id"):
super().__init__(app)
self.role = role
self.email = email
async def dispatch(self, request: Request, call_next):
request.state.user_role = self.role
request.state.user_email = self.email
return await call_next(request)
# ─── App Factory ────────────────────────────────────────────────────────────
def create_test_app(role="admin", email="admin@briga.id"):
"""Build a minimal FastAPI app with the admin router for testing."""
app = FastAPI()
app.add_middleware(TestAuthMiddleware, role=role, email=email)
app.include_router(admin_router)
app.dependency_overrides[get_db] = override_get_db
return app
# ─── Fixtures ───────────────────────────────────────────────────────────────
@pytest_asyncio.fixture(autouse=True)
async def setup_database():
"""Create only the two tables admin endpoints touch.
Uses ``Base.metadata.create_all`` with an explicit ``tables`` list
so we never trigger the import of ``app.models.security`` (which
registers ``audit.audit_trail`` with a PostgreSQL-specific schema
that SQLite cannot handle).
"""
from app.models.base import Base
from app.models.system import WorkflowConfig, ActivityLog
async with test_engine.begin() as conn:
await conn.run_sync(
Base.metadata.create_all,
tables=[WorkflowConfig.__table__, ActivityLog.__table__],
)
yield
async with test_engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
@pytest_asyncio.fixture
async def seed_workflow():
"""Insert a test workflow row and return it."""
from app.models.system import WorkflowConfig
async with TestSessionLocal() as session:
wf = WorkflowConfig(
workflow_name="autonomous_dev",
is_active=True,
schedule_cron="0 * * * *",
)
session.add(wf)
await session.commit()
await session.refresh(wf)
return wf
@pytest_asyncio.fixture
async def admin_client():
"""Async HTTP client with admin role."""
app = create_test_app(role="admin")
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
@pytest_asyncio.fixture
async def non_admin_client():
"""Async HTTP client with a non-admin role (editor)."""
app = create_test_app(role="editor")
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield client
# ─── GET /v1/admin/workflows ────────────────────────────────────────────────
class TestListWorkflowsIntegration:
@pytest.mark.asyncio
async def test_empty_list(self, admin_client):
resp = await admin_client.get("/v1/admin/workflows")
assert resp.status_code == 200
assert resp.json() == []
@pytest.mark.asyncio
async def test_returns_seeded_workflow(self, admin_client, seed_workflow):
resp = await admin_client.get("/v1/admin/workflows")
assert resp.status_code == 200
data = resp.json()
assert len(data) == 1
assert data[0]["workflow_name"] == "autonomous_dev"
assert data[0]["is_active"] is True
assert data[0]["schedule_cron"] == "0 * * * *"
@pytest.mark.asyncio
async def test_non_admin_forbidden(self, non_admin_client, seed_workflow):
resp = await non_admin_client.get("/v1/admin/workflows")
assert resp.status_code == 403
# ─── PATCH /v1/admin/workflows/{name} ───────────────────────────────────────
class TestUpdateWorkflowIntegration:
@pytest.mark.asyncio
async def test_toggle_is_active(self, admin_client, seed_workflow):
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"is_active": False},
)
assert resp.status_code == 200
body = resp.json()
assert body["success"] is True
assert body["updated"]["is_active"] is False
# Verify the change persisted
resp2 = await admin_client.get("/v1/admin/workflows")
assert resp2.json()[0]["is_active"] is False
@pytest.mark.asyncio
async def test_update_schedule_cron(self, admin_client, seed_workflow):
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"schedule_cron": "*/5 * * * *"},
)
assert resp.status_code == 200
assert resp.json()["updated"]["schedule_cron"] == "*/5 * * * *"
@pytest.mark.asyncio
async def test_update_multiple_allowed_fields(self, admin_client, seed_workflow):
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"is_active": False, "schedule_cron": "30 9 * * 1"},
)
assert resp.status_code == 200
updated = resp.json()["updated"]
assert updated["is_active"] is False
assert updated["schedule_cron"] == "30 9 * * 1"
@pytest.mark.asyncio
async def test_nonexistent_workflow_returns_404(self, admin_client, seed_workflow):
resp = await admin_client.patch(
"/v1/admin/workflows/does_not_exist",
json={"is_active": True},
)
assert resp.status_code == 404
assert "not found" in resp.json()["detail"].lower()
@pytest.mark.asyncio
async def test_only_disallowed_fields_returns_400(self, admin_client, seed_workflow):
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"workflow_name": "hacked"},
)
assert resp.status_code == 400
assert "No valid fields" in resp.json()["detail"]
@pytest.mark.asyncio
async def test_mixed_fields_ignores_disallowed(self, admin_client, seed_workflow):
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"is_active": True, "workflow_name": "hacked"},
)
assert resp.status_code == 200
updated = resp.json()["updated"]
assert "is_active" in updated
assert "workflow_name" not in updated
@pytest.mark.asyncio
async def test_non_admin_forbidden(self, non_admin_client, seed_workflow):
resp = await non_admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"is_active": True},
)
assert resp.status_code == 403
# ─── POST /v1/admin/workflows/{name}/run ────────────────────────────────────
class TestRunWorkflowIntegration:
@pytest.mark.asyncio
async def test_manual_trigger_success(self, admin_client, seed_workflow):
resp = await admin_client.post("/v1/admin/workflows/autonomous_dev/run")
assert resp.status_code == 200
body = resp.json()
assert body["success"] is True
assert "run recorded" in body["message"].lower()
# Verify last_run was updated (no longer None)
resp2 = await admin_client.get("/v1/admin/workflows")
wf = resp2.json()[0]
assert wf["last_run"] is not None
@pytest.mark.asyncio
async def test_nonexistent_workflow_returns_404(self, admin_client, seed_workflow):
resp = await admin_client.post("/v1/admin/workflows/does_not_exist/run")
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_non_admin_forbidden(self, non_admin_client, seed_workflow):
resp = await non_admin_client.post("/v1/admin/workflows/autonomous_dev/run")
assert resp.status_code == 403
# ─── End-to-End Workflow ────────────────────────────────────────────────────
class TestEndToEndWorkflow:
"""Tests that exercise a realistic multi-step workflow."""
@pytest.mark.asyncio
async def test_full_lifecycle(self, admin_client, seed_workflow):
# 1. List β€” confirm seeded workflow exists
resp = await admin_client.get("/v1/admin/workflows")
assert resp.status_code == 200
assert len(resp.json()) == 1
# 2. Disable the workflow
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"is_active": False},
)
assert resp.status_code == 200
assert resp.json()["updated"]["is_active"] is False
# 3. Change the schedule
resp = await admin_client.patch(
"/v1/admin/workflows/autonomous_dev",
json={"schedule_cron": "0 8 * * 1-5"},
)
assert resp.status_code == 200
# 4. Manual trigger
resp = await admin_client.post("/v1/admin/workflows/autonomous_dev/run")
assert resp.status_code == 200
# 5. List β€” verify final state
resp = await admin_client.get("/v1/admin/workflows")
wf = resp.json()[0]
assert wf["is_active"] is False
assert wf["schedule_cron"] == "0 8 * * 1-5"
assert wf["last_run"] is not None