File size: 11,373 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
"""Unit tests for admin API endpoints.

Covers:
- GET  /v1/admin/workflows           -> list_workflows
- PATCH /v1/admin/workflows/{name}   -> update_workflow
- POST  /v1/admin/workflows/{name}/run -> run_workflow
- Helper functions: _ensure_admin, _get_workflow_or_404, _log_activity
"""

import pytest
from unittest.mock import AsyncMock, MagicMock
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from datetime import datetime

from app.api.admin import (
    _ensure_admin,
    _get_workflow_or_404,
    _log_activity,
    list_workflows,
    update_workflow,
    run_workflow,
)
from app.models.system import WorkflowConfig


# --- Mock Fixtures ---


class MockState:
    def __init__(self, role="admin", email="admin@briga.id"):
        self.user_role = role
        self.user_email = email


class MockRequest:
    def __init__(self, role="admin", email="admin@briga.id"):
        self.state = MockState(role=role, email=email)
        self.client = MagicMock(host="127.0.0.1")
        self.headers = {}


def make_workflow_row(name="autonomous_dev", active=True, cron="0 * * * *"):
    row = MagicMock(spec=WorkflowConfig)
    row.workflow_name = name
    row.is_active = active
    row.schedule_cron = cron
    row.last_run = None
    row.updated_at = datetime(2026, 1, 1)
    return row


# --- Helper Function Tests ---


class TestEnsureAdmin:
    def test_admin_passes(self):
        _ensure_admin(MockRequest(role="admin"))

    def test_admin_uppercase_passes(self):
        _ensure_admin(MockRequest(role="ADMIN"))

    def test_non_admin_rejected(self):
        with pytest.raises(HTTPException) as exc_info:
            _ensure_admin(MockRequest(role="editor"))
        assert exc_info.value.status_code == 403

    def test_no_role_rejected(self):
        req = MockRequest()
        req.state.user_role = None
        with pytest.raises(HTTPException) as exc_info:
            _ensure_admin(req)
        assert exc_info.value.status_code == 403

    def test_empty_role_rejected(self):
        with pytest.raises(HTTPException) as exc_info:
            _ensure_admin(MockRequest(role=""))
        assert exc_info.value.status_code == 403


class TestGetWorkflowOr404:
    @pytest.mark.asyncio
    async def test_found_returns_row(self):
        db = AsyncMock(spec=AsyncSession)
        mock_row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = mock_row
        db.execute.return_value = mock_result

        result = await _get_workflow_or_404("autonomous_dev", db)
        assert result == mock_row

    @pytest.mark.asyncio
    async def test_not_found_raises_404(self):
        db = AsyncMock(spec=AsyncSession)
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = None
        db.execute.return_value = mock_result

        with pytest.raises(HTTPException) as exc_info:
            await _get_workflow_or_404("nonexistent_workflow", db)
        assert exc_info.value.status_code == 404
        assert "nonexistent_workflow" in str(exc_info.value.detail)

    @pytest.mark.asyncio
    async def test_empty_name_raises_404(self):
        db = AsyncMock(spec=AsyncSession)
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = None
        db.execute.return_value = mock_result

        with pytest.raises(HTTPException) as exc_info:
            await _get_workflow_or_404("", db)
        assert exc_info.value.status_code == 404


class TestLogActivity:
    @pytest.mark.asyncio
    async def test_logs_successfully(self):
        db = AsyncMock(spec=AsyncSession)
        req = MockRequest()
        await _log_activity(db, req, "test_action", "{}")
        db.add.assert_called_once()
        db.commit.assert_awaited_once()

    @pytest.mark.asyncio
    async def test_commit_failure_rolls_back(self):
        db = AsyncMock(spec=AsyncSession)
        db.commit.side_effect = Exception("commit failed")
        req = MockRequest()
        # Should not raise
        await _log_activity(db, req, "test_action", "{}")
        db.rollback.assert_awaited_once()

    @pytest.mark.asyncio
    async def test_rollback_failure_swallows(self):
        db = AsyncMock(spec=AsyncSession)
        db.commit.side_effect = Exception("commit failed")
        db.rollback.side_effect = Exception("rollback failed")
        req = MockRequest()
        # Should not raise even if rollback fails
        await _log_activity(db, req, "test_action", "{}")

    @pytest.mark.asyncio
    async def test_uses_system_actor_when_no_email(self):
        db = AsyncMock(spec=AsyncSession)
        req = MockRequest()
        req.state.user_email = None
        await _log_activity(db, req, "test_action", "{}")
        # Verify the ActivityLog was created with actor='system'
        # The source uses: actor=request.state.user_email or 'system'
        call_args = db.add.call_args[0][0]
        assert call_args.actor == "system"

    @pytest.mark.asyncio
    async def test_uses_system_actor_when_no_attribute(self):
        db = AsyncMock(spec=AsyncSession)
        req = MockRequest()
        # Remove the attribute entirely
        del req.state.user_email
        await _log_activity(db, req, "test_action", "{}")
        call_args = db.add.call_args[0][0]
        assert call_args.actor == "system"


# --- Endpoint Tests ---


class TestListWorkflows:
    @pytest.mark.asyncio
    async def test_list_returns_array(self):
        db = AsyncMock(spec=AsyncSession)
        row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalars.return_value.all.return_value = [row]
        db.execute.return_value = mock_result

        result = await list_workflows(MockRequest(), db)
        assert len(result) == 1
        assert result[0]["workflow_name"] == "autonomous_dev"
        assert result[0]["is_active"] is True

    @pytest.mark.asyncio
    async def test_list_empty(self):
        db = AsyncMock(spec=AsyncSession)
        mock_result = MagicMock()
        mock_result.scalars.return_value.all.return_value = []
        db.execute.return_value = mock_result

        result = await list_workflows(MockRequest(), db)
        assert result == []

    @pytest.mark.asyncio
    async def test_non_admin_rejected(self):
        db = AsyncMock(spec=AsyncSession)
        with pytest.raises(HTTPException) as exc_info:
            await list_workflows(MockRequest(role="editor"), db)
        assert exc_info.value.status_code == 403


class TestUpdateWorkflow:
    @pytest.mark.asyncio
    async def test_update_is_active(self):
        db = AsyncMock(spec=AsyncSession)
        row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = row
        db.execute.return_value = mock_result

        result = await update_workflow("autonomous_dev", {"is_active": False}, MockRequest(), db)
        assert result["success"] is True
        assert "is_active" in result["updated"]
        # Two commits: one for the update, one for activity log
        assert db.commit.await_count == 2

    @pytest.mark.asyncio
    async def test_update_schedule_cron(self):
        db = AsyncMock(spec=AsyncSession)
        row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = row
        db.execute.return_value = mock_result

        result = await update_workflow("autonomous_dev", {"schedule_cron": "*/5 * * * *"}, MockRequest(), db)
        assert result["success"] is True
        assert result["updated"]["schedule_cron"] == "*/5 * * * *"
        assert db.commit.await_count == 2

    @pytest.mark.asyncio
    async def test_update_mixed_allowed_and_disallowed_fields(self):
        """Disallowed fields are silently ignored; allowed ones go through."""
        db = AsyncMock(spec=AsyncSession)
        row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = row
        db.execute.return_value = mock_result

        result = await update_workflow(
            "autonomous_dev",
            {"is_active": True, "workflow_name": "hacked"},
            MockRequest(),
            db,
        )
        assert result["success"] is True
        assert "is_active" in result["updated"]
        assert "workflow_name" not in result["updated"]

    @pytest.mark.asyncio
    async def test_update_no_valid_fields_raises_400(self):
        db = AsyncMock(spec=AsyncSession)
        row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = row
        db.execute.return_value = mock_result

        with pytest.raises(HTTPException) as exc_info:
            await update_workflow("autonomous_dev", {"workflow_name": "hacked"}, MockRequest(), db)
        assert exc_info.value.status_code == 400

    @pytest.mark.asyncio
    async def test_update_nonexistent_returns_404(self):
        db = AsyncMock(spec=AsyncSession)
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = None
        db.execute.return_value = mock_result

        with pytest.raises(HTTPException) as exc_info:
            await update_workflow("nonexistent", {"is_active": True}, MockRequest(), db)
        assert exc_info.value.status_code == 404

    @pytest.mark.asyncio
    async def test_non_admin_rejected(self):
        db = AsyncMock(spec=AsyncSession)
        with pytest.raises(HTTPException) as exc_info:
            await update_workflow("autonomous_dev", {"is_active": True}, MockRequest(role="editor"), db)
        assert exc_info.value.status_code == 403


class TestRunWorkflow:
    @pytest.mark.asyncio
    async def test_manual_trigger_success(self):
        db = AsyncMock(spec=AsyncSession)
        row = make_workflow_row()
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = row
        db.execute.return_value = mock_result

        result = await run_workflow("autonomous_dev", MockRequest(), db)
        assert result["success"] is True
        # Two commits: one for the trigger update, one for activity log
        assert db.commit.await_count == 2

    @pytest.mark.asyncio
    async def test_manual_trigger_nonexistent_404(self):
        db = AsyncMock(spec=AsyncSession)
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = None
        db.execute.return_value = mock_result

        with pytest.raises(HTTPException) as exc_info:
            await run_workflow("nonexistent", MockRequest(), db)
        assert exc_info.value.status_code == 404

    @pytest.mark.asyncio
    async def test_non_admin_rejected(self):
        db = AsyncMock(spec=AsyncSession)
        with pytest.raises(HTTPException) as exc_info:
            await run_workflow("autonomous_dev", MockRequest(role="viewer"), db)
        assert exc_info.value.status_code == 403

    @pytest.mark.asyncio
    async def test_empty_name_raises_404(self):
        db = AsyncMock(spec=AsyncSession)
        mock_result = MagicMock()
        mock_result.scalar_one_or_none.return_value = None
        db.execute.return_value = mock_result

        with pytest.raises(HTTPException) as exc_info:
            await run_workflow("", MockRequest(), db)
        assert exc_info.value.status_code == 404