Spaces:
Sleeping
Sleeping
Download tests/test_error_states.py from DerXanity/farient-deckcheck: direct link, hf CLI and curl.
- Browser
- Download file 11.6 kB
-
https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/tests/test_error_states.py
- Command line
-
hf download hf://spaces/DerXanity/farient-deckcheck/tests/test_error_states.py
-
curl -L -o test_error_states.py https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/tests/test_error_states.py
11.6 kB
| """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 | |
| # --------------------------------------------------------------------------- | |
| 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 | |
| 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 | |
| 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}" | |