Spaces:
Sleeping
Sleeping
File size: 24,253 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 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 | """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
# ---------------------------------------------------------------------------
@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
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
@pytest.fixture
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
@pytest.fixture
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
# ---------------------------------------------------------------------------
@pytest.mark.skipif(not JACOBS_PATH.exists(), reason="Jacobs deck not present")
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
|