File size: 11,524 Bytes
b613c13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
"""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