Spaces:
Sleeping
Sleeping
Download tests/test_api.py from DerXanity/farient-deckcheck: direct link, hf CLI and curl.
- Browser
- Download file 24.3 kB
-
https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/tests/test_api.py
- Command line
-
hf download hf://spaces/DerXanity/farient-deckcheck/tests/test_api.py
-
curl -L -o test_api.py https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/tests/test_api.py
24.3 kB
| """End-to-end FastAPI tests with the agent runner mocked. | |
| These tests exercise the route layer + orchestrator integration without | |
| making OpenAI calls. The fake runner returns canned :class:`SlideFindings` | |
| / :class:`DeckFindings` / :class:`FinalAuditResult` instances based on the | |
| agent's name. | |
| The Jacobs deck under ``Doc Reference/`` is used for the happy-path | |
| integration test (33 slides). All other tests use small synthetic decks | |
| or a one-byte payload. | |
| """ | |
| from __future__ import annotations | |
| import inspect | |
| import io | |
| import json | |
| import os | |
| import shutil | |
| 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, | |
| FinalAuditResult, | |
| FindingMeta as AgentFindingMeta, | |
| SeverityCounts as AgentSeverityCounts, | |
| SlideEnvelopeExtended as AgentSlideEnvelopeExtended, | |
| SlideFindings, | |
| ) | |
| from schemas.api import ( | |
| AuditExportJson, | |
| AuditListResponse, | |
| AuditSlidesResponse, | |
| Finding, | |
| FindingMeta, | |
| ) | |
| _DOC_REF = Path(__file__).parents[3] / "Doc Reference" | |
| JACOBS_PATH = _DOC_REF / ( | |
| "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx" | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Fixtures: tmp jobs root + app with mocked agent runner | |
| # --------------------------------------------------------------------------- | |
| 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 | |
| class _FakeRunner: | |
| """Drop-in replacement for ``agents.Runner`` β returns canned outputs. | |
| The run side-effect is a callable: ``side_effect(agent, input, context) | |
| -> Any`` (sync or awaitable). The runner wraps the value as | |
| ``SimpleNamespace(final_output=...)`` so it matches the SDK shape. | |
| """ | |
| 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, "max_turns": max_turns} | |
| ) | |
| result = self._side_effect(agent, input, context) | |
| if inspect.isawaitable(result): | |
| result = await result | |
| return SimpleNamespace(final_output=result) | |
| def _canned_responder(*, must_flag_slide: int | None = None): | |
| """Return a side-effect that emits one finding per slide for the reviewer.""" | |
| def side_effect(agent, input_, context): | |
| if agent.name == "Slide Reviewer Agent": | |
| data = json.loads(input_) | |
| n = int(data["slide_number"]) | |
| return SlideFindings( | |
| slide_number=n, | |
| findings=[ | |
| AgentFinding( | |
| category="title_slide", | |
| severity="high" if n == must_flag_slide else "low", | |
| confidence=0.9, | |
| title=f"Test finding for slide {n}", | |
| description=f"Synthetic finding on slide {n}", | |
| evidence=f"slide {n} evidence", | |
| suggested_fix="Fix it", | |
| guideline_reference="title_slide.no_draft", | |
| ) | |
| ], | |
| ) | |
| if agent.name == "Deck Consistency Agent": | |
| return DeckFindings(findings=[]) | |
| if agent.name == "Lead Auditor Agent": | |
| data = json.loads(input_) | |
| slide_count = int(data["slide_count"]) | |
| return FinalAuditResult( | |
| job_id=data["job_id"], | |
| file_name=data["file_name"], | |
| slide_count=slide_count, | |
| summary=AgentSeverityCounts(), | |
| slides=[ | |
| AgentSlideEnvelopeExtended( | |
| slide_number=n, | |
| image_url=None, | |
| findings=[ | |
| AgentFindingExtended( | |
| category="title_slide", | |
| severity="low", | |
| confidence=0.9, | |
| title=f"Test finding for slide {n}", | |
| description=f"Synthetic finding on slide {n}", | |
| evidence=f"slide {n} evidence", | |
| suggested_fix="Fix it", | |
| guideline_reference="title_slide.no_draft", | |
| finding_meta=AgentFindingMeta( | |
| source="agent_slide", must_flag=False | |
| ), | |
| ) | |
| ], | |
| ) | |
| for n in range(1, slide_count + 1) | |
| ], | |
| errors=[], | |
| ) | |
| raise AssertionError(f"Unexpected agent name {agent.name!r}") | |
| return side_effect | |
| def app_with_mock(jobs_root, monkeypatch): | |
| # Avoid renderer warmup hitting LibreOffice during tests. | |
| import services.renderer as renderer_module | |
| monkeypatch.setattr(renderer_module, "warmup", lambda: None) | |
| from main import create_app | |
| app = create_app() | |
| app.state.agent_runner_override = _FakeRunner(_canned_responder()) | |
| return app | |
| def client(app_with_mock): | |
| return TestClient(app_with_mock) | |
| # --------------------------------------------------------------------------- | |
| # 1. Schema sanity β additionalProperties:false everywhere | |
| # --------------------------------------------------------------------------- | |
| def test_finding_schema_forbids_extra_properties(): | |
| schema = Finding.model_json_schema() | |
| assert schema["additionalProperties"] is False | |
| def test_audit_export_schema_forbids_extra_properties(): | |
| schema = AuditExportJson.model_json_schema() | |
| assert schema["additionalProperties"] is False | |
| def test_audit_slides_response_schema_forbids_extra_properties(): | |
| schema = AuditSlidesResponse.model_json_schema() | |
| assert schema["additionalProperties"] is False | |
| def test_finding_meta_schema_forbids_extra_properties(): | |
| schema = FindingMeta.model_json_schema() | |
| assert schema["additionalProperties"] is False | |
| # --------------------------------------------------------------------------- | |
| # 2. POST /api/audits β happy path with Jacobs deck | |
| # --------------------------------------------------------------------------- | |
| def test_post_audit_jacobs_happy_path( | |
| app_with_mock, client: TestClient, jobs_root: Path | |
| ): | |
| with JACOBS_PATH.open("rb") as f: | |
| response = client.post( | |
| "/api/audits", | |
| files={ | |
| "file": ( | |
| JACOBS_PATH.name, | |
| f, | |
| "application/vnd.openxmlformats-officedocument.presentationml.presentation", | |
| ) | |
| }, | |
| ) | |
| assert response.status_code == 200, response.text | |
| body = response.json() | |
| assert "job_id" in body and body["status"] == "queued" | |
| job_id = body["job_id"] | |
| # The TestClient tears down the asyncio loop between requests, so the | |
| # background pipeline task does not survive past the POST. We drive it | |
| # manually here. (Production: uvicorn keeps the loop alive β see main.py.) | |
| import asyncio as _asyncio | |
| from services.jobs import JobStore | |
| from services.orchestrator import run_audit_pipeline | |
| store = JobStore(jobs_root) | |
| runner = app_with_mock.state.agent_runner_override | |
| _asyncio.run(run_audit_pipeline(job_id, store=store, runner=runner)) | |
| # Now status is terminal. | |
| status_resp = client.get(f"/api/audits/{job_id}") | |
| assert status_resp.status_code == 200 | |
| final_status = status_resp.json() | |
| assert final_status["status"] in ("reviewed", "partial"), final_status | |
| # /slides β extended shape | |
| slides_resp = client.get(f"/api/audits/{job_id}/slides") | |
| assert slides_resp.status_code == 200 | |
| slides_body = slides_resp.json() | |
| AuditSlidesResponse.model_validate(slides_body) | |
| assert slides_body["slide_count"] == 33 | |
| assert len(slides_body["slides"]) == 33 | |
| for slide in slides_body["slides"]: | |
| for f in slide["findings"]: | |
| assert "finding_meta" in f | |
| assert "source" in f["finding_meta"] | |
| assert "must_flag" in f["finding_meta"] | |
| # --------------------------------------------------------------------------- | |
| # 3. POST /api/audits β .docx rejected with 400 | |
| # --------------------------------------------------------------------------- | |
| def test_post_audit_rejects_docx(client: TestClient): | |
| response = client.post( | |
| "/api/audits", | |
| files={"file": ("notes.docx", io.BytesIO(b"PK\x03\x04 fake docx"), "application/octet-stream")}, | |
| ) | |
| assert response.status_code == 400 | |
| assert ".pptx" in response.json()["detail"] | |
| # --------------------------------------------------------------------------- | |
| # 4. POST /api/audits β non-zip rejected with 400 (magic bytes) | |
| # --------------------------------------------------------------------------- | |
| def test_post_audit_rejects_non_zip(client: TestClient): | |
| response = client.post( | |
| "/api/audits", | |
| files={"file": ("not_real.pptx", io.BytesIO(b"this is not a zip"), "application/octet-stream")}, | |
| ) | |
| assert response.status_code == 400 | |
| detail = response.json()["detail"].lower() | |
| assert "pptx" in detail or "zip" in detail | |
| # --------------------------------------------------------------------------- | |
| # 5. POST /api/audits β oversized payload rejected with 413 | |
| # --------------------------------------------------------------------------- | |
| def test_post_audit_rejects_oversized(monkeypatch, jobs_root, app_with_mock): | |
| monkeypatch.setenv("MAX_UPLOAD_MB", "1") # 1 MiB cap | |
| # Recreate the app so it re-reads MAX_UPLOAD_MB. | |
| import services.renderer as renderer_module | |
| monkeypatch.setattr(renderer_module, "warmup", lambda: None) | |
| from main import create_app | |
| app = create_app() | |
| app.state.agent_runner_override = _FakeRunner(_canned_responder()) | |
| # Build a 2 MiB blob that has the zip magic so it doesn't 400 first. | |
| big = b"PK\x03\x04" + os.urandom(2 * 1024 * 1024) | |
| with TestClient(app) as fresh_client: | |
| response = fresh_client.post( | |
| "/api/audits", | |
| files={"file": ("big.pptx", io.BytesIO(big), "application/octet-stream")}, | |
| ) | |
| assert response.status_code == 413 | |
| detail = response.json()["detail"].lower() | |
| assert "too large" in detail or "max_upload_mb" in detail | |
| # --------------------------------------------------------------------------- | |
| # 6. /export?fmt=json β strict shape (no finding_meta) + schema validation | |
| # --------------------------------------------------------------------------- | |
| def test_export_json_strict_shape(client: TestClient, jobs_root: Path): | |
| job_id = _seed_synthetic_job(jobs_root, slides=3) | |
| response = client.get(f"/api/audits/{job_id}/export?fmt=json") | |
| assert response.status_code == 200 | |
| body = response.json() | |
| # Validates against the strict shape. | |
| parsed = AuditExportJson.model_validate(body) | |
| # No finding_meta anywhere. | |
| for slide in body["slides"]: | |
| for f in slide["findings"]: | |
| assert "finding_meta" not in f | |
| # And the strict Finding schema accepts it. | |
| Finding.model_validate(f) | |
| # Content-Disposition: attachment with .json filename | |
| cd = response.headers.get("content-disposition", "") | |
| assert "attachment" in cd and ".json" in cd | |
| assert parsed.job_id == job_id | |
| # --------------------------------------------------------------------------- | |
| # 7. /export?fmt=md β text/markdown + Content-Disposition | |
| # --------------------------------------------------------------------------- | |
| def test_export_md_content_type(client: TestClient, jobs_root: Path): | |
| job_id = _seed_synthetic_job(jobs_root, slides=2) | |
| response = client.get(f"/api/audits/{job_id}/export?fmt=md") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"].startswith("text/markdown") | |
| cd = response.headers.get("content-disposition", "") | |
| assert "attachment" in cd and ".md" in cd | |
| body = response.text | |
| assert "# Brand Compliance Audit" in body | |
| # Every finding visible in /slides should appear in the markdown. | |
| assert "slide 1 evidence" in body | |
| assert "slide 2 evidence" in body | |
| # --------------------------------------------------------------------------- | |
| # 8. /slides β extended shape with finding_meta on every finding | |
| # --------------------------------------------------------------------------- | |
| def test_slides_extended_shape(client: TestClient, jobs_root: Path): | |
| job_id = _seed_synthetic_job(jobs_root, slides=3) | |
| response = client.get(f"/api/audits/{job_id}/slides") | |
| assert response.status_code == 200 | |
| body = response.json() | |
| AuditSlidesResponse.model_validate(body) | |
| for slide in body["slides"]: | |
| for f in slide["findings"]: | |
| meta = f["finding_meta"] | |
| assert meta["source"] in ( | |
| "agent_slide", "agent_deck", "safety_net", "merged" | |
| ) | |
| assert isinstance(meta["must_flag"], bool) | |
| # --------------------------------------------------------------------------- | |
| # 9. /slides/{n}/image β 404 when not rendered | |
| # --------------------------------------------------------------------------- | |
| def test_slide_image_404_when_not_rendered(client: TestClient, jobs_root: Path): | |
| job_id = _seed_synthetic_job(jobs_root, slides=2) | |
| response = client.get(f"/api/audits/{job_id}/slides/1/image") | |
| assert response.status_code == 404 | |
| def test_slide_image_streams_png(client: TestClient, jobs_root: Path): | |
| job_id = _seed_synthetic_job(jobs_root, slides=2) | |
| # Drop a fake PNG into the slides dir. | |
| png_bytes = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32 | |
| target = jobs_root / job_id / "slides" / "slide_001.png" | |
| target.parent.mkdir(parents=True, exist_ok=True) | |
| target.write_bytes(png_bytes) | |
| response = client.get(f"/api/audits/{job_id}/slides/1/image") | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"] == "image/png" | |
| assert response.headers.get("cache-control") == "public, max-age=86400" | |
| assert response.content == png_bytes | |
| # --------------------------------------------------------------------------- | |
| # 10. GET /api/audits/{id} β 404 for unknown job | |
| # --------------------------------------------------------------------------- | |
| def test_get_unknown_job_returns_404(client: TestClient): | |
| response = client.get("/api/audits/this-job-does-not-exist") | |
| assert response.status_code == 404 | |
| # --------------------------------------------------------------------------- | |
| # 11. Status endpoint reflects terminal state after pipeline runs | |
| # --------------------------------------------------------------------------- | |
| def test_status_after_pipeline_completion(client: TestClient, jobs_root: Path): | |
| job_id = _seed_synthetic_job(jobs_root, slides=2) | |
| response = client.get(f"/api/audits/{job_id}") | |
| assert response.status_code == 200 | |
| body = response.json() | |
| # Synthetic job seeded directly as "reviewed" | |
| assert body["status"] == "reviewed" | |
| assert body["stage"] is None # terminal => null | |
| assert body["slide_count"] == 2 | |
| # --------------------------------------------------------------------------- | |
| # 12. Partial status flow β error captured during pipeline | |
| # --------------------------------------------------------------------------- | |
| def test_partial_status_when_errors_present(jobs_root: Path): | |
| """Seed a job with partial state on disk and confirm endpoints surface it.""" | |
| from services.jobs import JobStore | |
| store = JobStore(jobs_root) | |
| rec = store.create(file_name="seeded.pptx") | |
| store.set_slide_count(rec.job_id, 3) | |
| # Build a strict-PRD findings.json with 3 slides. | |
| export = AuditExportJson( | |
| job_id=rec.job_id, | |
| file_name="seeded.pptx", | |
| slide_count=3, | |
| slides=[], | |
| ) | |
| store.findings_path(rec.job_id).write_text( | |
| json.dumps(export.model_dump()), encoding="utf-8" | |
| ) | |
| store.append_error( | |
| rec.job_id, "slide render failed: timeout", slide_number=2, stage="rendering" | |
| ) | |
| # Force into 'processing' first, then partial (terminal). | |
| store.set_status(rec.job_id, "processing", stage="reviewing") | |
| store.set_status(rec.job_id, "partial") | |
| # Recreate the app pointed at this jobs_root. | |
| import services.renderer as renderer_module | |
| with patch.object(renderer_module, "warmup", lambda: None): | |
| os.environ["AUDIT_JOBS_ROOT"] = str(jobs_root) | |
| from main import create_app | |
| app = create_app() | |
| with TestClient(app) as fresh: | |
| response = fresh.get(f"/api/audits/{rec.job_id}") | |
| assert response.status_code == 200 | |
| body = response.json() | |
| assert body["status"] == "partial" | |
| assert body["stage"] is None | |
| assert len(body["errors"]) == 1 | |
| assert body["errors"][0]["slide_number"] == 2 | |
| # --------------------------------------------------------------------------- | |
| # 13. GET /api/audits β listing endpoint returns all jobs sorted desc | |
| # --------------------------------------------------------------------------- | |
| def test_list_audits_returns_all_jobs(client: TestClient, jobs_root: Path): | |
| """Seed 3 jobs and confirm GET /api/audits returns them newest first.""" | |
| import time as _time | |
| job_ids: list[str] = [] | |
| for i in range(3): | |
| # Each call to _seed_synthetic_job uses _now_iso (1 second resolution), | |
| # so sleep briefly between seeds to guarantee distinct created_at. | |
| job_ids.append(_seed_synthetic_job(jobs_root, slides=2 + i)) | |
| _time.sleep(1.05) | |
| response = client.get("/api/audits") | |
| assert response.status_code == 200, response.text | |
| body = response.json() | |
| # Validates against the response shape. | |
| parsed = AuditListResponse.model_validate(body) | |
| assert len(parsed.jobs) == 3 | |
| # additionalProperties:false on the response shape. | |
| schema = AuditListResponse.model_json_schema() | |
| assert schema["additionalProperties"] is False | |
| # All three seeded jobs come back. | |
| returned_ids = {j.job_id for j in parsed.jobs} | |
| assert returned_ids == set(job_ids) | |
| # Sorted by created_at descending (newest first). | |
| created_ats = [j.created_at for j in parsed.jobs] | |
| assert created_ats == sorted(created_ats, reverse=True) | |
| # The newest seed (last appended) should be first. | |
| assert parsed.jobs[0].job_id == job_ids[-1] | |
| # Every entry has the expected shape. | |
| for entry in parsed.jobs: | |
| assert entry.status in ("queued", "processing", "reviewed", "partial", "failed") | |
| assert entry.errors_count == 0 | |
| assert entry.slide_count >= 2 | |
| # --------------------------------------------------------------------------- | |
| # Helpers | |
| # --------------------------------------------------------------------------- | |
| def _poll_until_terminal( | |
| client: TestClient, job_id: str, *, timeout_s: float = 30.0 | |
| ) -> dict[str, Any]: | |
| """Block until the job lands in a terminal status, or raise on timeout.""" | |
| import time | |
| deadline = time.time() + timeout_s | |
| last: dict[str, Any] | None = None | |
| while time.time() < deadline: | |
| r = client.get(f"/api/audits/{job_id}") | |
| assert r.status_code == 200, r.text | |
| last = r.json() | |
| if last["status"] in ("reviewed", "partial", "failed"): | |
| return last | |
| time.sleep(0.1) | |
| raise AssertionError(f"job {job_id} never reached terminal: last={last!r}") | |
| def _seed_synthetic_job(jobs_root: Path, *, slides: int) -> str: | |
| """Drop a fully-cooked job on disk so route tests don't have to wait. | |
| Creates ``job.json`` (status=reviewed) and ``findings.json`` (strict shape | |
| with one canned finding per slide) plus the ``findings_extended.json`` | |
| sidecar that ``/slides`` uses to recover ``finding_meta``. | |
| """ | |
| from services.jobs import JobStore | |
| store = JobStore(jobs_root) | |
| rec = store.create(file_name="seeded.pptx") | |
| store.set_slide_count(rec.job_id, slides) | |
| strict_payload = { | |
| "job_id": rec.job_id, | |
| "file_name": "seeded.pptx", | |
| "slide_count": slides, | |
| "summary": {"high": 0, "medium": 0, "low": slides}, | |
| "slides": [ | |
| { | |
| "slide_number": n, | |
| "findings": [ | |
| { | |
| "category": "title_slide", | |
| "severity": "low", | |
| "confidence": 0.9, | |
| "title": f"Finding {n}", | |
| "description": f"Description {n}", | |
| "evidence": f"slide {n} evidence", | |
| "suggested_fix": "fix", | |
| "guideline_reference": "title_slide.no_draft", | |
| } | |
| ], | |
| } | |
| for n in range(1, slides + 1) | |
| ], | |
| } | |
| store.findings_path(rec.job_id).write_text( | |
| json.dumps(strict_payload), encoding="utf-8" | |
| ) | |
| sidecar_payload = { | |
| "slides": [ | |
| { | |
| "slide_number": n, | |
| "findings": [ | |
| { | |
| "finding_meta": { | |
| "source": "agent_slide", | |
| "must_flag": False, | |
| } | |
| } | |
| ], | |
| } | |
| for n in range(1, slides + 1) | |
| ], | |
| } | |
| (store.job_dir(rec.job_id) / "findings_extended.json").write_text( | |
| json.dumps(sidecar_payload), encoding="utf-8" | |
| ) | |
| store.set_summary( | |
| rec.job_id, AgentSeverityCounts(high=0, medium=0, low=slides) # type: ignore[arg-type] | |
| ) | |
| store.set_status(rec.job_id, "processing", stage="reviewing") | |
| store.set_status(rec.job_id, "reviewed") | |
| return rec.job_id | |
| # --------------------------------------------------------------------------- | |
| # 13. GET /api/audits/{id}/events β SSE stream | |
| # --------------------------------------------------------------------------- | |
| def test_sse_events_unknown_job_returns_404(client: TestClient): | |
| response = client.get("/api/audits/no-such-job/events") | |
| assert response.status_code == 404 | |
| def test_sse_events_terminal_job_emits_initial_then_closes( | |
| client: TestClient, jobs_root: Path | |
| ): | |
| """For a job already in a terminal state, the SSE stream should emit at | |
| least one ``data:`` frame containing valid status JSON, then close. | |
| We use ``client.get(..., stream=True)`` (Starlette TestClient streams the | |
| response body). Once the generator hits the terminal branch it emits a | |
| ``done`` event and returns, so the stream closes cleanly. | |
| """ | |
| job_id = _seed_synthetic_job(jobs_root, slides=2) | |
| # `httpx`-style streaming via the TestClient. | |
| with client.stream("GET", f"/api/audits/{job_id}/events") as response: | |
| assert response.status_code == 200 | |
| assert response.headers["content-type"].startswith("text/event-stream") | |
| # Read the body β for a terminal job this completes quickly because | |
| # the generator returns after emitting the `done` event. | |
| body = b"".join(response.iter_bytes()).decode("utf-8") | |
| # Must contain at least one data frame with parseable JSON. | |
| data_frames = [ | |
| line[len("data: ") :] | |
| for line in body.splitlines() | |
| if line.startswith("data: ") | |
| ] | |
| assert data_frames, f"no data frames in body:\n{body}" | |
| parsed = json.loads(data_frames[0]) | |
| assert parsed["job_id"] == job_id | |
| assert parsed["status"] == "reviewed" | |
| # Terminal stream should also include the `done` event line. | |
| assert "event: done" in body | |