Files
rag-technical-docs-assistant/tests/unit/test_gemini_vision.py
T
11linear11 a73a496c54 feat(backend): deliver Phase 3 document and voice integration
Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy.

Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics.

Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
2026-10-09 17:43:52 -04:00

115 lines
5.6 KiB
Python

"""REST boundary fixtures; never real provider-quality evidence."""
from io import BytesIO
import json
import pytest
from app.infrastructure.gemini_vision import GeminiVision, INSTRUCTION
from app.modules.documents.extraction import ExtractionError
from tests.support.extraction import FakeVision
from tests.support.formats import image_bytes
@pytest.fixture
def profile(settings):
return settings.model_copy(update={"vision_provider": "gemini", "vision_endpoint": "https://example.invalid/v1beta",
"vision_model": "fixture-flash"}).processing_profile()
def native(profile):
blocks = FakeVision().transcribe(b"image", page=None, section="image", processing_profile=profile)
return dict(modelVersion="fixture-flash", candidates=[dict(finishReason="STOP", content=dict(parts=[
dict(text=json.dumps(dict(complete=True, warnings=[], blocks=[b.model_dump(mode="json") for b in blocks])))]))])
def run(profile, payload, monkeypatch, *, capture=None):
class Opener:
def open(self, request, *, timeout):
if capture is not None:
capture.append((request, timeout))
return BytesIO(json.dumps(payload).encode())
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
api_key="test-secret", timeout_seconds=60)
return adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
def test_complete_ordered_native_conversion_and_prompt(profile, monkeypatch):
captured = []
blocks = run(profile, native(profile), monkeypatch, capture=captured)
assert len(blocks) == 2 and blocks[1].parent_block_id == blocks[0].block_id
assert blocks[1].search_text == blocks[1].text
request, timeout = captured[0]
assert 0 < timeout <= 60 and request.get_header("X-goog-api-key") == "test-secret"
body = json.loads(request.data)
assert "ALL visible" in body["contents"][0]["parts"][0]["text"]
assert body["generationConfig"]["responseMimeType"] == "application/json"
@pytest.mark.parametrize("change", ["alias", "missing_model", "truncated", "empty", "wrong_page", "wrong_method", "wrong_block_model"])
def test_invalid_native_response_fails_safely(profile, monkeypatch, change):
value = native(profile)
if change == "alias":
value["modelVersion"] = "fixture-flash-resolved"
elif change == "missing_model":
del value["modelVersion"]
elif change == "truncated":
value["candidates"][0]["finishReason"] = "MAX_TOKENS"
else:
part = value["candidates"][0]["content"]["parts"][0]
transcript = json.loads(part["text"])
if change == "empty": transcript["blocks"] = []
if change == "incomplete": transcript["complete"] = False
if change == "warnings": transcript["warnings"] = ["missing region"]
if change == "unreadable": transcript["blocks"][1]["warnings"] = ["unreadable"]
if change == "wrong_page": transcript["blocks"][0]["page"] = 2
if change == "wrong_method": transcript["blocks"][0]["method"] = "direct_pdf"
if change == "wrong_block_model": transcript["blocks"][0]["actual_model"] = "other"
part["text"] = json.dumps(transcript)
with pytest.raises(ExtractionError):
run(profile, value, monkeypatch)
def test_provider_response_byte_limit(profile, monkeypatch):
profile["extraction"]["max_extraction_artifact_bytes"] = 10
with pytest.raises(ExtractionError, match="byte limit"):
run(profile, native(profile), monkeypatch)
def test_provider_failures_redacted(profile, monkeypatch):
class Opener:
def open(self, *a, **kw):
raise TimeoutError("test-secret")
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
api_key="test-secret", timeout_seconds=60)
with pytest.raises(ExtractionError) as error:
adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
assert "test-secret" not in str(error.value)
assert error.value.retryable is True
@pytest.mark.parametrize("status,retryable", [(400, False), (401, False), (408, True), (429, True), (503, True)])
def test_provider_http_errors_preserve_retry_category_without_stacked_retries(profile, monkeypatch, status, retryable):
from urllib.error import HTTPError
calls = []
class Opener:
def open(self, *args, **kwargs):
calls.append(1)
raise HTTPError("https://example.invalid", status, "test-secret", {}, None)
monkeypatch.setattr("urllib.request.build_opener", lambda *a: Opener())
adapter = GeminiVision(endpoint="https://example.invalid/v1beta", model="fixture-flash",
api_key="test-secret", timeout_seconds=60)
with pytest.raises(ExtractionError) as error:
adapter.transcribe(image_bytes(), page=None, section="image", processing_profile=profile)
assert error.value.retryable == retryable and len(calls) == 1
assert error.value.code == "EXTRACTION_PROVIDER_FAILED" and "test-secret" not in str(error.value)
def test_provider_malformed_ordinals_are_rejected(profile, monkeypatch):
value = native(profile)
part = value["candidates"][0]["content"]["parts"][0]
transcript = json.loads(part["text"])
transcript["blocks"][0]["ordinal"] = 1
part["text"] = json.dumps(transcript)
with pytest.raises(ExtractionError):
run(profile, value, monkeypatch)