Spaces:
Sleeping
Sleeping
File size: 6,020 Bytes
9dfc563 d66d64c 9dfc563 d66d64c 9dfc563 d66d64c 9dfc563 d66d64c 9dfc563 d66d64c 9dfc563 86226ed 9dfc563 86226ed 9dfc563 86226ed 9dfc563 86226ed 9dfc563 86226ed d66d64c 86226ed 9dfc563 d66d64c 9dfc563 d66d64c 9dfc563 86226ed 9dfc563 d66d64c 9dfc563 d66d64c 9dfc563 86226ed 9dfc563 d66d64c 9dfc563 86226ed | 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 | """Tests for RAG lesson inference error taxonomy mapping.
TASK: Prove that POST /api/rag/lesson currently maps all inference failures
to blanket 502 {"error": "inference_failed"}.
Test cases:
(a) Mock Claude to raise anthropic.AuthenticationError (HTTP 401)
-> assert response body error == "inference_auth_failed" (FAILS in RED state: currently "inference_failed")
(b) Mock anthropic.APIConnectionError
-> assert response body error == "inference_connection_failed" (FAILS in RED state: currently "inference_failed")
(c) Mock generic Exception
-> assert response body error == "inference_failed" (PASSES in RED state: pins fallback)
Status codes remain 502 for all three cases.
"""
from __future__ import annotations
import os
from unittest.mock import patch
import anthropic
import httpx2
import pytest
from fastapi.testclient import TestClient
# Ensure test env vars are configured before importing application modules
os.environ["ANTHROPIC_API_KEY"] = "mock-key-for-testing"
os.environ["INFERENCE_MAX_RETRIES"] = "1"
os.environ["INFERENCE_BACKGROUND_MAX_RETRIES"] = "1"
os.environ["INFERENCE_INTERACTIVE_MAX_RETRIES"] = "1"
os.environ["INFERENCE_BACKOFF_SEC"] = "0"
os.environ["INFERENCE_BACKGROUND_BACKOFF_SEC"] = "0"
import json
import main as main_module
from main import app
from routes import rag_routes
# We hit the HTTP endpoint via FastAPI TestClient (following test_api.py / test_audit_remediation.py).
# We authenticate with a teacher mock token and bypass vectorstore retrieval with minimal mock chunks.
client = TestClient(app, headers={"Authorization": "Bearer mock_token_teacher_T"})
MOCK_CHUNKS = [
{
"content": "Functions and equations for Senior High School STEM.",
"source_file": "SHS_GM_Q1.pdf",
"score": 0.95,
"content_domain": "general",
}
]
LESSON_PAYLOAD = {
"topic": "Rational Functions",
"subject": "General Mathematics",
"quarter": 1,
"lessonTitle": "Introduction to Rational Functions",
}
@pytest.fixture(autouse=True)
def _setup_rag_mocks():
"""Bypass Firebase token verification, time.sleep backoff, and curriculum retrieval."""
with patch.object(
main_module.firebase_auth,
"verify_id_token",
return_value={"uid": "teacher_T", "role": "teacher"},
), patch(
"routes.rag_routes.retrieve_lesson_pdf_context",
return_value=(MOCK_CHUNKS, "exact_file"),
), patch(
"time.sleep",
return_value=None,
), patch(
"routes.rag_routes._read_student_lesson",
return_value=None,
), patch(
"routes.rag_routes._load_learner_profile",
return_value="",
):
rag_routes._lesson_memory.clear()
rag_routes._retrieval_memory.clear()
yield
rag_routes._lesson_memory.clear()
rag_routes._retrieval_memory.clear()
def _post_both(error: Exception) -> tuple:
"""POST /api/rag/lesson and /api/rag/lesson/stream with Claude raising `error` on both the streamed reasoner
call (rag_routes seam) and the chat fallback (inference client seam); return (plain response, terminal SSE event)."""
with patch("routes.rag_routes.open_stream", side_effect=error), \
patch("services.inference_client.create_message", side_effect=error):
response = client.post("/api/rag/lesson", json=LESSON_PAYLOAD)
streamed = client.post("/api/rag/lesson/stream", json=LESSON_PAYLOAD)
blocks = [b for b in streamed.text.replace("\r\n", "\n").split("\n\n") if b.startswith("event:")]
event_line, data_line = blocks[-1].split("\n", 1)
return response, (event_line[len("event:"):].strip(), json.loads(data_line[len("data:"):].strip()))
def _extract_error(response_json: dict) -> str | None:
"""Extract error code from response whether in detail dict or top-level."""
detail = response_json.get("detail")
if isinstance(detail, dict):
return detail.get("error")
return response_json.get("error")
class TestRagInferenceTaxonomy:
"""Taxonomy mapping tests for POST /api/rag/lesson inference failures."""
def test_rag_lesson_inference_auth_failed_maps_to_taxonomy(self):
"""(a) 401 AuthenticationError should map to 502 with error='inference_auth_failed'."""
req = httpx2.Request("POST", "https://api.anthropic.com/v1/messages")
auth_error_401 = anthropic.AuthenticationError(
"invalid x-api-key",
response=httpx2.Response(401, request=req),
body=None,
)
response, (event, data) = _post_both(auth_error_401)
assert response.status_code == 502
body = response.json()
assert _extract_error(body) == "inference_auth_failed"
assert event == "error"
assert data["status"] == 502 and data["detail"]["error"] == "inference_auth_failed"
def test_rag_lesson_inference_connection_failed_maps_to_taxonomy(self):
"""(b) APIConnectionError should map to 502 with error='inference_connection_failed'."""
req = httpx2.Request("POST", "https://api.anthropic.com/v1/messages")
conn_error = anthropic.APIConnectionError(request=req)
response, (event, data) = _post_both(conn_error)
assert response.status_code == 502
body = response.json()
assert _extract_error(body) == "inference_connection_failed"
assert event == "error"
assert data["status"] == 502 and data["detail"]["error"] == "inference_connection_failed"
def test_rag_lesson_inference_generic_exception_fallback(self):
"""(c) Generic Exception should map to 502 with error='inference_failed'."""
generic_error = RuntimeError("Unexpected model engine crash")
response, (event, data) = _post_both(generic_error)
assert response.status_code == 502
body = response.json()
assert _extract_error(body) == "inference_failed"
assert event == "error"
assert data["status"] == 502 and data["detail"]["error"] == "inference_failed"
|