docling-studio/document-parser/tests/test_models.py
Pier-Jean Malandrino efc27932dd refactor(audit): remediate 0.5.0 audit findings — clean architecture, security, DRY, SOLID, perf
Closes the 12 MAJ raised by the release/0.5.0 audit pipeline (cf.
docs/audit/reports/release-0.5.0/summary.md → summary-reaudit.md).

Volet 1 — Reasoning architecture (audits 01/02/06/07 strengthening)
  * Domain ports: LLMProvider, ReasoningRunner, ReasoningParseError
  * Domain DTOs: LLMProviderType, ReasoningResult, ReasoningIteration
  * infra/llm/ollama_provider.py — OllamaProvider with health_check
  * infra/docling_agent_reasoning.py — runner adapter, encapsulates the
    private _rag_loop call (tracked at docling-project/docling-agent#26),
    commits OLLAMA_HOST once at boot (eliminates the per-request env race),
    translates upstream IndexError into ReasoningParseError
  * api/reasoning.py — zero coupling to docling-agent / mellea / docling-core,
    consumes app.state.reasoning_runner via the port
  * main.py — DI wires OllamaProvider + DoclingAgentReasoningRunner at boot
    when REASONING_ENABLED=true and deps are importable
  * Rename RAG_* env vars → REASONING_*, endpoint /rag → /reasoning,
    type RAGResult → ReasoningResult, frontend feature flag wiring,
    i18n strings, tests, docs (BREAKING — pre-1.0 surface, no external
    consumers in production)
  * 17 new tests: adapter unit tests with sys.modules stubs, OllamaProvider
    httpx tests, R3 concurrent-host isolation, R6 multi-iteration trace
    serialization, R13 Protocol conformance via isinstance
  * E2E Karate scenario: nav-reasoning hidden when REASONING_ENABLED=false
  * README — Live Reasoning section (env vars, archi, link to issue #26)

Bloc B — Security (audit 08, dev-only context)
  * docker-compose.yml — DEV DEFAULTS header, OpenSearch DISABLE_SECURITY_PLUGIN
    flagged as dev-only with link to OpenSearch security docs
  * main.py — boot warning if NEO4J_URI is set with the default 'changeme'
    password, so prod operators can't silently inherit it

Bloc C — DRY frontend (audit 05)
  * shared/storage/keys.ts — STORAGE_KEYS centralised (theme, locale)
  * features/settings/store.ts — dead apiUrl ref + orphan i18n keys removed
  * api/schemas.py — DOCUMENT_STATUS_UPLOADED constant

Bloc D — Quality (audits 02/06/07/09/10/12)
  * domain/ports.py — DocumentConverter.supports_page_batching property
    (LSP fix, replaces isinstance(ServeConverter) check)
  * domain/ports.py — VectorStore.ping() (encapsulation, replaces
    _vector_store._client.info() reach-around)
  * api/analyses.py + api/ingestion.py — path params {job_id} → {analysis_id}
    aligned with the user-facing terminology (URLs unchanged)
  * api/documents.py — Path.read_bytes() + generate_preview() wrapped in
    asyncio.to_thread, unblocks the FastAPI event loop on /preview
  * infra/docling_tree.py — PEP 604 union for isinstance (Ruff UP038)
  * src/__tests__/integration/ — cross-feature integration test relocated
    out of features/history/ so feature folders stay self-contained
  * Tightened terminal `assert X is not None` checks (isinstance(.., datetime),
    exact value comparisons)

Validation
  * 446 backend pytest, 202 frontend vitest — all green
  * ruff + ruff format + ESLint + Prettier + vue-tsc clean
  * Re-audit verdict: 0 CRIT / 0 MAJ, score ~94/100, GO

Closes #200
2026-04-29 14:00:00 +02:00

176 lines
5.6 KiB
Python

"""Tests for domain models."""
from datetime import datetime
import pytest
from domain.models import AnalysisJob, AnalysisStatus, Document
class TestDocument:
def test_default_values(self):
doc = Document()
assert doc.id # auto-generated UUID
assert doc.filename == ""
assert doc.content_type is None
assert doc.file_size is None
assert doc.page_count is None
assert doc.storage_path == ""
assert isinstance(doc.created_at, datetime)
def test_custom_values(self):
doc = Document(
id="doc-1",
filename="test.pdf",
content_type="application/pdf",
file_size=1024,
page_count=5,
storage_path="/tmp/test.pdf",
)
assert doc.id == "doc-1"
assert doc.filename == "test.pdf"
assert doc.file_size == 1024
assert doc.page_count == 5
def test_unique_ids(self):
d1 = Document()
d2 = Document()
assert d1.id != d2.id
class TestAnalysisJob:
def test_default_values(self):
job = AnalysisJob()
assert job.id
assert job.document_id == ""
assert job.status == AnalysisStatus.PENDING
assert job.content_markdown is None
assert job.content_html is None
assert job.pages_json is None
assert job.error_message is None
assert job.started_at is None
assert job.completed_at is None
def test_mark_running(self):
job = AnalysisJob()
assert job.started_at is None
job.mark_running()
assert job.status == AnalysisStatus.RUNNING
assert isinstance(job.started_at, datetime)
def test_mark_completed(self):
job = AnalysisJob()
job.mark_running()
job.mark_completed(
markdown="# Title",
html="<h1>Title</h1>",
pages_json='[{"page": 1}]',
)
assert job.status == AnalysisStatus.COMPLETED
assert job.content_markdown == "# Title"
assert job.content_html == "<h1>Title</h1>"
assert job.pages_json == '[{"page": 1}]'
assert isinstance(job.completed_at, datetime)
assert job.completed_at >= job.started_at
def test_mark_failed(self):
job = AnalysisJob()
job.mark_running()
job.mark_failed("Something went wrong")
assert job.status == AnalysisStatus.FAILED
assert job.error_message == "Something went wrong"
assert isinstance(job.completed_at, datetime)
assert job.completed_at >= job.started_at
def test_status_transitions(self):
"""Test full lifecycle: PENDING -> RUNNING -> COMPLETED."""
job = AnalysisJob()
assert job.status == AnalysisStatus.PENDING
job.mark_running()
assert job.status == AnalysisStatus.RUNNING
job.mark_completed(markdown="md", html="html", pages_json="[]")
assert job.status == AnalysisStatus.COMPLETED
class TestAnalysisJobGuardClauses:
"""Guard clauses prevent invalid state transitions."""
def test_mark_running_from_running_raises(self):
job = AnalysisJob()
job.mark_running()
with pytest.raises(ValueError, match="Cannot mark as RUNNING"):
job.mark_running()
def test_mark_running_from_completed_raises(self):
job = AnalysisJob()
job.mark_running()
job.mark_completed(markdown="", html="", pages_json="[]")
with pytest.raises(ValueError, match="Cannot mark as RUNNING"):
job.mark_running()
def test_mark_running_from_failed_raises(self):
job = AnalysisJob()
job.mark_failed("err")
with pytest.raises(ValueError, match="Cannot mark as RUNNING"):
job.mark_running()
def test_mark_completed_from_pending_raises(self):
job = AnalysisJob()
with pytest.raises(ValueError, match="Cannot mark as COMPLETED"):
job.mark_completed(markdown="", html="", pages_json="[]")
def test_mark_completed_from_failed_raises(self):
job = AnalysisJob()
job.mark_failed("err")
with pytest.raises(ValueError, match="Cannot mark as COMPLETED"):
job.mark_completed(markdown="", html="", pages_json="[]")
def test_mark_failed_from_completed_raises(self):
job = AnalysisJob()
job.mark_running()
job.mark_completed(markdown="", html="", pages_json="[]")
with pytest.raises(ValueError, match="Cannot mark as FAILED"):
job.mark_failed("err")
def test_mark_failed_from_pending_allowed(self):
job = AnalysisJob()
job.mark_failed("err")
assert job.status == AnalysisStatus.FAILED
def test_mark_failed_from_running_allowed(self):
job = AnalysisJob()
job.mark_running()
job.mark_failed("err")
assert job.status == AnalysisStatus.FAILED
def test_update_progress_from_pending_raises(self):
job = AnalysisJob()
with pytest.raises(ValueError, match="Cannot update progress"):
job.update_progress(1, 10)
def test_update_progress_from_running_allowed(self):
job = AnalysisJob()
job.mark_running()
job.update_progress(5, 10)
assert job.progress_current == 5
assert job.progress_total == 10
class TestAnalysisStatus:
def test_values(self):
assert AnalysisStatus.PENDING == "PENDING"
assert AnalysisStatus.RUNNING == "RUNNING"
assert AnalysisStatus.COMPLETED == "COMPLETED"
assert AnalysisStatus.FAILED == "FAILED"
def test_from_string(self):
assert AnalysisStatus("PENDING") == AnalysisStatus.PENDING
assert AnalysisStatus("COMPLETED") == AnalysisStatus.COMPLETED