File size: 11,619 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""TestClient tests for pipeline error states.

Covers:
1. .docx upload β†’ 400
2. Corrupted .pptx (truncated bytes) β†’ 400 (invalid zip)
3. Oversized file β†’ 413 (MAX_UPLOAD_MB=1 via env var)
4. Pipeline failure β†’ audit ends status=failed with error captured
   (parse_deck raises)
5. Single-slide review failure β†’ audit ends status=partial with banner data
   (one Runner.run call raises for that slide)
"""
from __future__ import annotations

import asyncio
import inspect
import io
import json
import os
from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import patch

import pytest
from fastapi.testclient import TestClient

from agents.output_schemas import (
    DeckFindings,
    Finding as AgentFinding,
    FindingExtended as AgentFindingExtended,
    FindingMeta as AgentFindingMeta,
    FinalAuditResult,
    SeverityCounts as AgentSeverityCounts,
    SlideEnvelopeExtended as AgentSlideEnvelopeExtended,
    SlideFindings,
)
from schemas.api import AuditExportJson, AuditSlidesResponse


# ---------------------------------------------------------------------------
# Shared fake runner helpers
# ---------------------------------------------------------------------------


class _FakeRunner:
    """Configurable fake runner for error-state tests."""

    def __init__(self, side_effect):
        self._side_effect = side_effect
        self.calls: list[dict[str, Any]] = []

    async def run(self, agent, *, input=None, context=None, max_turns=10, **_):
        self.calls.append({"agent_name": agent.name, "input": input})
        result = self._side_effect(agent, input, context)
        if inspect.isawaitable(result):
            result = await result
        return SimpleNamespace(final_output=result)


def _canned_side_effect(agent, input_, context):
    """Returns minimal valid outputs so the pipeline completes cleanly."""
    if agent.name == "Slide Reviewer Agent":
        data = json.loads(input_) if isinstance(input_, str) else {}
        n = int(data.get("slide_number", 1))
        return SlideFindings(slide_number=n, findings=[])
    if agent.name == "Deck Consistency Agent":
        return DeckFindings(findings=[])
    if agent.name == "Lead Auditor Agent":
        data = json.loads(input_) if isinstance(input_, str) else {}
        slide_count = int(data.get("slide_count", 1))
        return FinalAuditResult(
            job_id=data.get("job_id", ""),
            file_name=data.get("file_name", ""),
            slide_count=slide_count,
            summary=AgentSeverityCounts(),
            slides=[
                AgentSlideEnvelopeExtended(
                    slide_number=n, image_url=None, findings=[]
                )
                for n in range(1, slide_count + 1)
            ],
            errors=[],
        )
    raise AssertionError(f"Unexpected agent {agent.name!r}")


# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------


@pytest.fixture
def jobs_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
    root = tmp_path / "audits"
    root.mkdir(parents=True, exist_ok=True)
    monkeypatch.setenv("AUDIT_JOBS_ROOT", str(root))
    monkeypatch.setenv("MAX_UPLOAD_MB", "60")
    return root


@pytest.fixture
def app_with_mock(jobs_root):
    import services.renderer as renderer_module
    with patch.object(renderer_module, "warmup", lambda: None):
        from main import create_app
        app = create_app()
        app.state.agent_runner_override = _FakeRunner(_canned_side_effect)
        return app


@pytest.fixture
def client(app_with_mock):
    return TestClient(app_with_mock)


def _run_pipeline(job_id: str, jobs_root: Path, runner) -> None:
    from services.jobs import JobStore
    from services.orchestrator import run_audit_pipeline
    store = JobStore(jobs_root)
    asyncio.run(run_audit_pipeline(job_id, store=store, runner=runner))


# ---------------------------------------------------------------------------
# 1. .docx upload β†’ 400
# ---------------------------------------------------------------------------


def test_docx_upload_rejected_400(client: TestClient):
    """Uploading a .docx file must return 400 with a .pptx hint."""
    resp = client.post(
        "/api/audits",
        files={"file": ("report.docx", io.BytesIO(b"PK\x03\x04 fake docx"), "application/octet-stream")},
    )
    assert resp.status_code == 400, resp.text
    detail = resp.json()["detail"]
    assert ".pptx" in detail


# ---------------------------------------------------------------------------
# 2. Corrupted .pptx (truncated bytes) β†’ 400 (invalid zip)
# ---------------------------------------------------------------------------


def test_corrupted_pptx_rejected_400(client: TestClient):
    """Uploading a file with .pptx extension but non-zip content β†’ 400."""
    resp = client.post(
        "/api/audits",
        files={"file": ("deck.pptx", io.BytesIO(b"this is not a zip archive"), "application/octet-stream")},
    )
    assert resp.status_code == 400, resp.text
    detail = resp.json()["detail"].lower()
    assert "zip" in detail or "pptx" in detail


# ---------------------------------------------------------------------------
# 3. Oversized file β†’ 413
# ---------------------------------------------------------------------------


def test_oversized_file_rejected_413(jobs_root: Path, monkeypatch):
    """File exceeding MAX_UPLOAD_MB=1 must be rejected with 413."""
    monkeypatch.setenv("MAX_UPLOAD_MB", "1")

    import services.renderer as renderer_module
    with patch.object(renderer_module, "warmup", lambda: None):
        from main import create_app
        app = create_app()
        app.state.agent_runner_override = _FakeRunner(_canned_side_effect)

    # 2 MiB blob with valid zip magic bytes so it doesn't fail on extension
    # check first (size check comes after extension but before zip check).
    big = b"PK\x03\x04" + os.urandom(2 * 1024 * 1024)

    with TestClient(app) as fresh_client:
        resp = fresh_client.post(
            "/api/audits",
            files={"file": ("big.pptx", io.BytesIO(big), "application/octet-stream")},
        )
    assert resp.status_code == 413, resp.text
    detail = resp.json()["detail"].lower()
    assert "too large" in detail or "max_upload_mb" in detail


# ---------------------------------------------------------------------------
# 4. Pipeline failure (parse_deck raises) β†’ status=failed
# ---------------------------------------------------------------------------


def test_pipeline_parse_failure_status_failed(jobs_root: Path):
    """When parse_deck raises, the pipeline must end status=failed with error captured."""
    import services.renderer as renderer_module
    with patch.object(renderer_module, "warmup", lambda: None):
        from main import create_app
        app = create_app()

    runner = _FakeRunner(_canned_side_effect)
    app.state.agent_runner_override = runner

    # Build a minimal valid zip (pptx magic) so the upload check passes.
    import zipfile
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w") as zf:
        zf.writestr("fake.txt", "not a real pptx")
    buf.seek(0)
    zip_bytes = buf.read()

    with TestClient(app) as tc:
        post_resp = tc.post(
            "/api/audits",
            files={"file": ("deck.pptx", io.BytesIO(zip_bytes), "application/octet-stream")},
        )
    assert post_resp.status_code == 200, post_resp.text
    job_id = post_resp.json()["job_id"]

    # Patch parse_deck to raise
    import services.parser as parser_module
    with patch.object(parser_module, "parse_deck", side_effect=RuntimeError("parse boom")):
        _run_pipeline(job_id, jobs_root, runner)

    from services.jobs import JobStore
    store = JobStore(jobs_root)
    rec = store.read(job_id)
    assert rec.status == "failed", f"Expected failed, got {rec.status}"
    error_messages = [e.message for e in rec.errors]
    assert any("parse" in m.lower() or "boom" in m.lower() for m in error_messages), (
        f"Expected parse error in errors, got: {error_messages}"
    )


# ---------------------------------------------------------------------------
# 5. Single-slide review failure β†’ status=partial
# ---------------------------------------------------------------------------


def test_single_slide_review_failure_status_partial(jobs_root: Path):
    """When one Slide Reviewer Agent call raises, the audit ends partial."""
    import services.renderer as renderer_module
    with patch.object(renderer_module, "warmup", lambda: None):
        from main import create_app
        app = create_app()

    _FAIL_SLIDE = 1  # The slide number whose review will raise.
    call_count = {"n": 0}

    def _partial_side_effect(agent, input_, context):
        if agent.name == "Slide Reviewer Agent":
            data = json.loads(input_) if isinstance(input_, str) else {}
            n = int(data.get("slide_number", 1))
            if n == _FAIL_SLIDE:
                call_count["n"] += 1
                raise RuntimeError(f"slide {n} agent exploded")
            return SlideFindings(slide_number=n, findings=[])
        if agent.name == "Deck Consistency Agent":
            return DeckFindings(findings=[])
        if agent.name == "Lead Auditor Agent":
            data = json.loads(input_) if isinstance(input_, str) else {}
            slide_count = int(data.get("slide_count", 1))
            return FinalAuditResult(
                job_id=data.get("job_id", ""),
                file_name=data.get("file_name", ""),
                slide_count=slide_count,
                summary=AgentSeverityCounts(),
                slides=[
                    AgentSlideEnvelopeExtended(
                        slide_number=sn, image_url=None, findings=[]
                    )
                    for sn in range(1, slide_count + 1)
                ],
                errors=[],
            )
        raise AssertionError(f"Unexpected agent {agent.name!r}")

    runner = _FakeRunner(_partial_side_effect)
    app.state.agent_runner_override = runner

    # Use a real small valid pptx β€” need at least one slide.
    # We create a minimal zip that parse_deck can handle. To avoid needing
    # a real pptx, we rely on the Jacobs deck; if it's not available we skip.
    _DOC_REF = Path(__file__).parents[3] / "Doc Reference"
    jacobs = _DOC_REF / (
        "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx"
    )
    if not jacobs.exists():
        pytest.skip("Jacobs deck not present")

    with TestClient(app) as tc:
        with jacobs.open("rb") as f:
            post_resp = tc.post(
                "/api/audits",
                files={"file": (jacobs.name, f, "application/octet-stream")},
            )
    assert post_resp.status_code == 200, post_resp.text
    job_id = post_resp.json()["job_id"]

    _run_pipeline(job_id, jobs_root, runner)

    from services.jobs import JobStore
    store = JobStore(jobs_root)
    rec = store.read(job_id)

    # Should be partial (some slides failed, rest succeeded).
    assert rec.status == "partial", (
        f"Expected partial, got {rec.status}. Errors: {[e.message for e in rec.errors]}"
    )
    # At least one error must mention the failed slide.
    error_messages = [e.message for e in rec.errors]
    assert any(
        str(_FAIL_SLIDE) in m or "agent exploded" in m or "slide" in m.lower()
        for m in error_messages
    ), f"Expected slide failure in errors, got: {error_messages}"