farient-deckcheck / tests /test_grader.py
Xander Labide
Claude Opus 4.7 (1M context)
Initial commit β€” Farient DeckCheck
fdfe81a
Raw History Blame Contribute Delete
11.2 kB
"""Unit tests for scripts.grader β€” EVAL_MAPPING projection + grading logic.
Covers:
* EVAL_MAPPING projection: synthetic findings produce expected eval categories.
* Matching logic: synthetic agent + GT pairs produce expected TP/FP/FN.
* --cached path: grader runs without invoking run_audit (mock asserts not called).
* Pass-bar: 4 covered eval categories β†’ PASS; 3 β†’ FAIL.
"""
from __future__ import annotations
from dataclasses import dataclass
from unittest.mock import AsyncMock, patch
import pytest
from scripts.grader import (
EVAL_CATEGORIES,
EVAL_MAPPING,
PASS_BAR_MIN,
GradeResult,
grade,
project_findings,
)
# ---------------------------------------------------------------------------
# Minimal FindingLike stub
# ---------------------------------------------------------------------------
@dataclass
class _F:
"""Minimal finding stub that satisfies FindingLike."""
category: str
# ---------------------------------------------------------------------------
# 1. EVAL_MAPPING projection tests
# ---------------------------------------------------------------------------
class TestEvalMappingProjection:
def test_known_category_maps_correctly(self) -> None:
findings = [_F("confidentiality_statement")]
assert project_findings(findings) == {"confidentiality_statement"}
def test_slide_title_maps_to_slide_title_position(self) -> None:
assert project_findings([_F("slide_title")]) == {"slide_title_position"}
def test_title_slide_maps_to_slide_title_position(self) -> None:
assert project_findings([_F("title_slide")]) == {"slide_title_position"}
def test_bullets_maps_to_spacing_and_terminology(self) -> None:
assert project_findings([_F("bullets")]) == {"spacing", "terminology"}
def test_chart_content_maps_to_key_vs_legend(self) -> None:
assert project_findings([_F("chart_content")]) == {"key_vs_legend"}
def test_table_header_maps_to_table_labeling(self) -> None:
assert project_findings([_F("table_header")]) == {"table_labeling"}
def test_footnotes_maps_to_terminology(self) -> None:
assert project_findings([_F("footnotes")]) == {"terminology"}
def test_emphasis_annotations_maps_to_empty(self) -> None:
assert project_findings([_F("emphasis_annotations")]) == set()
def test_color_palette_maps_to_empty(self) -> None:
assert project_findings([_F("color_palette")]) == set()
def test_terminology_maps_to_terminology_and_table_labeling(self) -> None:
assert project_findings([_F("terminology")]) == {"terminology", "table_labeling"}
def test_unknown_category_is_ignored(self) -> None:
assert project_findings([_F("nonexistent_category")]) == set()
def test_multiple_findings_union(self) -> None:
findings = [_F("slide_title"), _F("confidentiality_statement"), _F("chart_content")]
result = project_findings(findings)
assert result == {
"slide_title_position",
"confidentiality_statement",
"key_vs_legend",
}
def test_empty_findings_returns_empty(self) -> None:
assert project_findings([]) == set()
def test_all_eval_mapping_values_are_valid_eval_categories(self) -> None:
valid = set(EVAL_CATEGORIES)
for rubric_cat, eval_cats in EVAL_MAPPING.items():
for ec in eval_cats:
assert ec in valid, (
f"EVAL_MAPPING['{rubric_cat}'] contains '{ec}' which is not "
f"in EVAL_CATEGORIES"
)
# ---------------------------------------------------------------------------
# 2. Grading logic tests
# ---------------------------------------------------------------------------
class TestGradingLogic:
def test_perfect_match_single_slide(self) -> None:
agent = {1: [_F("confidentiality_statement")]}
gt = {1: {"confidentiality_statement"}}
result = grade(agent, gt, total_slides=1)
assert result.per_category["confidentiality_statement"].tp_count == 1
assert result.per_category["confidentiality_statement"].fp_count == 0
assert result.per_category["confidentiality_statement"].fn_count == 0
assert result.per_slide[0].hit is True
def test_false_negative_no_agent_findings(self) -> None:
agent: dict = {}
gt = {1: {"spacing"}}
result = grade(agent, gt, total_slides=1)
stats = result.per_category["spacing"]
assert stats.tp_count == 0
assert stats.fn_count == 1
assert result.per_slide[0].hit is False
def test_false_positive_agent_fires_no_gt(self) -> None:
agent = {1: [_F("chart_content")]} # β†’ key_vs_legend
gt: dict = {}
result = grade(agent, gt, total_slides=1)
stats = result.per_category["key_vs_legend"]
assert stats.fp_count == 1
assert stats.tp_count == 0
assert result.per_slide[0].hit is False
def test_partial_overlap_counts_as_hit(self) -> None:
# GT has table_labeling + spacing; agent covers only table_labeling.
agent = {1: [_F("table_header")]} # β†’ table_labeling
gt = {1: {"table_labeling", "spacing"}}
result = grade(agent, gt, total_slides=1)
# Slide-level hit is True because there is overlap.
assert result.per_slide[0].hit is True
# table_labeling: TP=1, spacing: FN=1
assert result.per_category["table_labeling"].tp_count == 1
assert result.per_category["spacing"].fn_count == 1
def test_multi_slide_deck(self) -> None:
agent = {
1: [_F("confidentiality_statement")],
2: [_F("slide_title")],
3: [],
}
gt = {
1: {"confidentiality_statement"},
2: {"slide_title_position"},
3: {"key_vs_legend"},
}
result = grade(agent, gt, total_slides=3)
assert result.per_slide[0].hit is True
assert result.per_slide[1].hit is True
assert result.per_slide[2].hit is False
assert result.per_category["key_vs_legend"].fn_count == 1
def test_deck_recall_computation(self) -> None:
agent = {1: [_F("confidentiality_statement")]}
gt = {1: {"confidentiality_statement"}, 2: {"spacing"}}
result = grade(agent, gt, total_slides=2)
# 1 of 2 GT slides hit β†’ recall = 0.5
assert result.deck_recall == pytest.approx(0.5)
def test_deck_precision_computation(self) -> None:
agent = {1: [_F("confidentiality_statement")], 2: [_F("chart_content")]}
gt = {1: {"confidentiality_statement"}}
result = grade(agent, gt, total_slides=2)
# 1 of 2 agent-active slides hit β†’ precision = 0.5
assert result.deck_precision == pytest.approx(0.5)
def test_total_slides_respected(self) -> None:
result = grade({}, {}, total_slides=10)
assert result.total_slides == 10
assert len(result.per_slide) == 10
# ---------------------------------------------------------------------------
# 3. Pass-bar tests
# ---------------------------------------------------------------------------
class TestPassBar:
def _make_agent_for_cats(self, eval_cats: list[str]) -> dict[int, list[_F]]:
"""Build a single-slide agent dict that covers the given eval categories
by choosing appropriate rubric categories."""
cat_to_rubric = {
"confidentiality_statement": "confidentiality_statement",
"slide_title_position": "slide_title",
"table_labeling": "table_header",
"key_vs_legend": "chart_content",
"spacing": "chart_title",
"terminology": "footnotes",
}
findings = [_F(cat_to_rubric[ec]) for ec in eval_cats if ec in cat_to_rubric]
return {1: findings}
def _make_gt_for_cats(self, eval_cats: list[str]) -> dict[int, set[str]]:
return {1: set(eval_cats)}
def test_four_categories_is_pass(self) -> None:
cats = ["confidentiality_statement", "slide_title_position", "table_labeling", "key_vs_legend"]
agent = self._make_agent_for_cats(cats)
gt = self._make_gt_for_cats(cats)
result = grade(agent, gt, total_slides=1)
assert result.pass_bar is True
assert result.categories_with_tp >= PASS_BAR_MIN
def test_three_categories_is_fail(self) -> None:
cats = ["confidentiality_statement", "slide_title_position", "table_labeling"]
agent = self._make_agent_for_cats(cats)
gt = self._make_gt_for_cats(cats)
result = grade(agent, gt, total_slides=1)
assert result.pass_bar is False
assert result.categories_with_tp < PASS_BAR_MIN
def test_all_six_categories_is_pass(self) -> None:
cats = EVAL_CATEGORIES[:]
agent = self._make_agent_for_cats(cats)
gt = self._make_gt_for_cats(cats)
result = grade(agent, gt, total_slides=1)
assert result.pass_bar is True
assert result.categories_with_tp == 6
def test_zero_categories_is_fail(self) -> None:
result = grade({}, {}, total_slides=1)
assert result.pass_bar is False
assert result.categories_with_tp == 0
def test_pass_bar_min_constant_is_four(self) -> None:
assert PASS_BAR_MIN == 4
# ---------------------------------------------------------------------------
# 4. --cached path: grader runs without invoking run_audit
# ---------------------------------------------------------------------------
class TestCachedPath:
"""Verify that --cached skips run_audit entirely."""
def test_cached_does_not_call_run_audit(self, tmp_path: Path) -> None:
"""Simulate the --cached flow: load final.json, grade, assert no run_audit call."""
import json
from pathlib import Path as _Path
from agents.output_schemas import FinalAuditResult
# Write a minimal final.json to a synthetic run dir.
run_dir = tmp_path / "calibration_runs" / "synthetic"
run_dir.mkdir(parents=True)
payload = {
"job_id": "calib_test",
"file_name": "test.pptx",
"slide_count": 1,
"summary": {"high": 0, "medium": 0, "low": 0},
"slides": [],
"errors": [],
}
(run_dir / "final.json").write_text(json.dumps(payload), encoding="utf-8")
loaded = FinalAuditResult.model_validate(payload)
mock_run_audit = AsyncMock()
with patch("agents.runner.run_audit", mock_run_audit):
# When --cached is used we load from disk; run_audit must NOT be called.
from scripts.calibrate import _build_agent_findings
agent_findings = _build_agent_findings(loaded)
gt: dict = {}
result = grade(agent_findings, gt, total_slides=loaded.slide_count)
# The critical assertion: run_audit was never invoked.
mock_run_audit.assert_not_called()
# Grader still produces a valid GradeResult.
assert isinstance(result, GradeResult)
assert result.total_slides == 1