Spaces:
Sleeping
Sleeping
Download tests/test_acceptance.py from DerXanity/farient-deckcheck: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/tests/test_acceptance.py
- Command line
-
hf download hf://spaces/DerXanity/farient-deckcheck/tests/test_acceptance.py
-
curl -L -o test_acceptance.py https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/tests/test_acceptance.py
11 kB
| """End-to-end acceptance test for the Jacobs deck must-flag guarantee. | |
| Strategy | |
| -------- | |
| * Patches ``agents.runner.Runner.run`` so every agent call returns an empty | |
| ``SlideFindings`` / ``DeckFindings`` / ``FinalAuditResult`` (no agent findings). | |
| * Posts the real Jacobs .pptx through the FastAPI TestClient. | |
| * Drives the pipeline manually (TestClient tears down the asyncio loop between | |
| requests so the background task never completes on its own). | |
| * Asserts the deterministic safety-net injection in ``agents/runner.py`` still | |
| produces the 5 must-flag findings on slides 1, 6, 7, 23, 24. | |
| This test is the authoritative proof of the "safety-net guarantee" β i.e. the | |
| must-flag acceptance bar holds in Python regardless of agent quota or LLM behaviour. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import inspect | |
| import json | |
| import time | |
| 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, | |
| FinalAuditResult, | |
| FindingMeta as AgentFindingMeta, | |
| SeverityCounts as AgentSeverityCounts, | |
| SlideEnvelopeExtended as AgentSlideEnvelopeExtended, | |
| SlideFindings, | |
| ) | |
| from schemas.api import AuditExportJson, AuditSlidesResponse | |
| # --------------------------------------------------------------------------- | |
| # Paths | |
| # --------------------------------------------------------------------------- | |
| _DOC_REF = Path(__file__).parents[3] / "Doc Reference" | |
| JACOBS_PATH = _DOC_REF / ( | |
| "20260429 Jacobs Assessment of Compensation Peers - DRAFT 20260327 (3).pptx" | |
| ) | |
| MUST_FLAG_SLIDES = {1, 6, 7, 23, 24} | |
| MUST_FLAG_MARKER_SUBSTRINGS = { | |
| 1: "DRAFT", | |
| 6: "TW question", | |
| 7: "TW question", | |
| 23: "Page to be updated", | |
| 24: "Page to be updated", | |
| } | |
| # --------------------------------------------------------------------------- | |
| # Empty-agent runner β returns zero findings from every agent call | |
| # --------------------------------------------------------------------------- | |
| class _EmptyAgentRunner: | |
| """Fake runner that returns empty outputs from every agent invocation. | |
| The safety-net injection in ``agents/runner._finalise`` must still inject | |
| the 5 must-flag findings based on the pre-agent marker scan alone. | |
| """ | |
| def __init__(self): | |
| 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}) | |
| data = {} | |
| try: | |
| data = json.loads(input) if isinstance(input, str) else {} | |
| except (json.JSONDecodeError, TypeError): | |
| pass | |
| if agent.name == "Slide Reviewer Agent": | |
| slide_n = int(data.get("slide_number", 1)) | |
| result = SlideFindings(slide_number=slide_n, findings=[]) | |
| elif agent.name == "Deck Consistency Agent": | |
| result = DeckFindings(findings=[]) | |
| elif agent.name == "Lead Auditor Agent": | |
| slide_count = int(data.get("slide_count", 0)) | |
| result = 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=[], | |
| ) | |
| else: | |
| raise AssertionError(f"Unexpected agent name {agent.name!r}") | |
| return SimpleNamespace(final_output=result) | |
| # --------------------------------------------------------------------------- | |
| # 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_and_runner(jobs_root): | |
| import services.renderer as renderer_module | |
| with patch.object(renderer_module, "warmup", lambda: None): | |
| from main import create_app | |
| app = create_app() | |
| runner = _EmptyAgentRunner() | |
| app.state.agent_runner_override = runner | |
| return app, runner | |
| def client(app_and_runner): | |
| app, _ = app_and_runner | |
| return TestClient(app) | |
| # --------------------------------------------------------------------------- | |
| # Helper: drive the pipeline synchronously in the test process | |
| # --------------------------------------------------------------------------- | |
| def _run_pipeline(job_id: str, jobs_root: Path, runner) -> dict[str, Any]: | |
| 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)) | |
| # Return the final job record as a dict via the store. | |
| return store.read(job_id).__dict__ | |
| def _poll_until_terminal( | |
| client: TestClient, job_id: str, *, timeout_s: float = 5.0 | |
| ) -> dict[str, Any]: | |
| 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.05) | |
| raise AssertionError(f"job {job_id} never reached terminal: last={last!r}") | |
| # --------------------------------------------------------------------------- | |
| # Core acceptance test | |
| # --------------------------------------------------------------------------- | |
| def test_jacobs_must_flag_safety_net( | |
| app_and_runner, client: TestClient, jobs_root: Path | |
| ): | |
| """POST Jacobs deck, run pipeline with empty agents, assert 5 must-flag findings.""" | |
| app, runner = app_and_runner | |
| # 1. Upload the Jacobs deck. | |
| with JACOBS_PATH.open("rb") as f: | |
| post_resp = client.post( | |
| "/api/audits", | |
| files={ | |
| "file": ( | |
| JACOBS_PATH.name, | |
| f, | |
| "application/vnd.openxmlformats-officedocument.presentationml.presentation", | |
| ) | |
| }, | |
| ) | |
| assert post_resp.status_code == 200, post_resp.text | |
| job_id = post_resp.json()["job_id"] | |
| assert job_id | |
| # 2. Drive the pipeline (TestClient's event-loop is torn down between calls). | |
| _run_pipeline(job_id, jobs_root, runner) | |
| # 3. Poll status β should be terminal. | |
| status = _poll_until_terminal(client, job_id) | |
| assert status["status"] in ("reviewed", "partial"), ( | |
| f"Expected reviewed/partial, got {status['status']!r}. " | |
| f"Errors: {status.get('errors')}" | |
| ) | |
| # 4. GET /api/audits/{id}/slides β extended shape. | |
| slides_resp = client.get(f"/api/audits/{job_id}/slides") | |
| assert slides_resp.status_code == 200, slides_resp.text | |
| slides_body = slides_resp.json() | |
| # Validate full shape. | |
| validated_slides = AuditSlidesResponse.model_validate(slides_body) | |
| # 4a. Exactly 33 slides. | |
| assert slides_body["slide_count"] == 33, ( | |
| f"Expected 33 slides, got {slides_body['slide_count']}" | |
| ) | |
| assert len(slides_body["slides"]) == 33 | |
| # 4b. At least 5 findings tagged must_flag=true. | |
| all_extended_findings = [ | |
| f | |
| for slide in slides_body["slides"] | |
| for f in slide["findings"] | |
| ] | |
| must_flag_findings = [ | |
| f for f in all_extended_findings if f["finding_meta"]["must_flag"] is True | |
| ] | |
| assert len(must_flag_findings) >= 5, ( | |
| f"Expected β₯5 must_flag findings, got {len(must_flag_findings)}" | |
| ) | |
| # 4c. Slides 1, 6, 7, 23, 24 each carry at least one safety_net finding | |
| # with the expected marker substring in evidence. | |
| slides_by_n = {s["slide_number"]: s for s in slides_body["slides"]} | |
| for slide_n, marker_substr in MUST_FLAG_MARKER_SUBSTRINGS.items(): | |
| slide = slides_by_n.get(slide_n) | |
| assert slide is not None, f"Slide {slide_n} missing from response" | |
| safety_net_findings = [ | |
| f | |
| for f in slide["findings"] | |
| if f["finding_meta"]["source"] == "safety_net" | |
| and f["finding_meta"]["must_flag"] is True | |
| and f["severity"] == "high" | |
| ] | |
| assert len(safety_net_findings) >= 1, ( | |
| f"Slide {slide_n}: expected β₯1 safety_net high finding, " | |
| f"got {len(safety_net_findings)}. All findings: {slide['findings']}" | |
| ) | |
| # At least one safety_net finding's evidence contains the marker substring. | |
| evidences = [f["evidence"] for f in safety_net_findings] | |
| matched = any(marker_substr.lower() in ev.lower() for ev in evidences) | |
| assert matched, ( | |
| f"Slide {slide_n}: no safety_net finding evidence contains " | |
| f"{marker_substr!r}. Evidences: {evidences}" | |
| ) | |
| # 5. GET /api/audits/{id}/export?fmt=json β strict shape. | |
| export_resp = client.get(f"/api/audits/{job_id}/export?fmt=json") | |
| assert export_resp.status_code == 200, export_resp.text | |
| export_body = export_resp.json() | |
| # 5a. Validates against AuditExportJson schema (additionalProperties: false). | |
| validated_export = AuditExportJson.model_validate(export_body) | |
| schema = AuditExportJson.model_json_schema() | |
| assert schema.get("additionalProperties") is False | |
| # 5b. Export contains the 5 must-flag findings (evidence contains marker). | |
| # The strict export strips finding_meta; we check evidence substrings. | |
| export_slides_by_n = {s["slide_number"]: s for s in export_body["slides"]} | |
| for slide_n, marker_substr in MUST_FLAG_MARKER_SUBSTRINGS.items(): | |
| slide = export_slides_by_n.get(slide_n) | |
| assert slide is not None, f"Export slide {slide_n} missing" | |
| evidences = [f["evidence"] for f in slide["findings"]] | |
| matched = any(marker_substr.lower() in ev.lower() for ev in evidences) | |
| assert matched, ( | |
| f"Export slide {slide_n}: no finding evidence contains " | |
| f"{marker_substr!r}. Evidences: {evidences}" | |
| ) | |
| # 6. GET /api/audits/{id}/export?fmt=md β Markdown export. | |
| md_resp = client.get(f"/api/audits/{job_id}/export?fmt=md") | |
| assert md_resp.status_code == 200, md_resp.text | |
| md_text = md_resp.text | |
| # Must contain all three marker substrings somewhere in the markdown. | |
| for marker in ("DRAFT", "TW question", "Page to be updated"): | |
| assert marker in md_text, ( | |
| f"Markdown export missing marker {marker!r}. " | |
| f"(first 2000 chars): {md_text[:2000]}" | |
| ) | |