feat: add document artifact service for hash, persist, resolve, and invalidate
This commit is contained in:
@@ -0,0 +1,604 @@
|
||||
"""Tests for DOC-B2: document artifact service."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.config import ENV_DOCUMENT_STORAGE_ROOT
|
||||
from app.database.database import Base
|
||||
from app.models import ( # noqa: F401 — register mappers
|
||||
agreement,
|
||||
boq,
|
||||
daily_report,
|
||||
document_artifact,
|
||||
ks2,
|
||||
ks3,
|
||||
payment,
|
||||
project,
|
||||
work_journal,
|
||||
)
|
||||
from app.models.document_artifact import DocumentArtifact
|
||||
from app.models.project import Project
|
||||
from app.services.document_artifact_service import (
|
||||
ArtifactHashMismatchError,
|
||||
ArtifactNotFoundError,
|
||||
ArtifactPathError,
|
||||
DocumentArtifactError,
|
||||
build_storage_key,
|
||||
canonical_json,
|
||||
compute_content_hash,
|
||||
compute_input_hash,
|
||||
invalidate_artifacts,
|
||||
persist_artifact,
|
||||
resolve_artifact,
|
||||
resolve_artifact_by_id,
|
||||
resolve_storage_path,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SampleDto:
|
||||
name: str
|
||||
amount: Decimal
|
||||
when: date
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def storage_root(tmp_path, monkeypatch):
|
||||
root = tmp_path / "artifact-storage"
|
||||
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(root))
|
||||
return root
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session():
|
||||
engine = create_engine(
|
||||
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
|
||||
)
|
||||
Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
session = Session()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project_id(db_session):
|
||||
p = Project(name="Artifact service")
|
||||
db_session.add(p)
|
||||
db_session.commit()
|
||||
return p.id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Hash
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_content_hash_identical():
|
||||
assert compute_content_hash(b"abc") == compute_content_hash(b"abc")
|
||||
assert compute_content_hash(b"abc") == hashlib.sha256(b"abc").hexdigest()
|
||||
|
||||
|
||||
def test_content_hash_different():
|
||||
assert compute_content_hash(b"abc") != compute_content_hash(b"abd")
|
||||
|
||||
|
||||
def test_input_hash_dict_key_order_irrelevant():
|
||||
a = compute_input_hash({"a": 1, "b": 2}, "ks2_act", 1)
|
||||
b = compute_input_hash({"b": 2, "a": 1}, "ks2_act", 1)
|
||||
assert a == b
|
||||
|
||||
|
||||
def test_input_hash_decimal_canonical():
|
||||
a = compute_input_hash({"v": Decimal("1.50")}, "t", 1)
|
||||
b = compute_input_hash({"v": Decimal("1.5")}, "t", 1)
|
||||
assert a == b
|
||||
assert a != compute_input_hash({"v": Decimal("1.51")}, "t", 1)
|
||||
|
||||
|
||||
def test_input_hash_date_datetime():
|
||||
d1 = compute_input_hash({"d": date(2026, 1, 2)}, "t", 1)
|
||||
d2 = compute_input_hash({"d": date(2026, 1, 2)}, "t", 1)
|
||||
assert d1 == d2
|
||||
assert d1 != compute_input_hash({"d": date(2026, 1, 3)}, "t", 1)
|
||||
dt1 = compute_input_hash({"t": datetime(2026, 1, 2, 3, 4, 5)}, "t", 1)
|
||||
dt2 = compute_input_hash({"t": datetime(2026, 1, 2, 3, 4, 5)}, "t", 1)
|
||||
assert dt1 == dt2
|
||||
|
||||
|
||||
def test_input_hash_dataclass():
|
||||
dto = SampleDto(name="X", amount=Decimal("2.5"), when=date(2026, 1, 1))
|
||||
a = compute_input_hash(dto, "ks2_act", 1)
|
||||
b = compute_input_hash(
|
||||
{"name": "X", "amount": Decimal("2.5"), "when": date(2026, 1, 1)}, "ks2_act", 1
|
||||
)
|
||||
assert a == b
|
||||
|
||||
|
||||
def test_input_hash_nested_list_dict():
|
||||
dto = {"items": [{"a": 1, "b": [Decimal("3"), date(2026, 1, 1)]}]}
|
||||
a = compute_input_hash(dto, "t", 1)
|
||||
b = compute_input_hash({"items": [{"b": [Decimal("3.0"), date(2026, 1, 1)], "a": 1}]}, "t", 1)
|
||||
assert a == b
|
||||
assert a != compute_input_hash({"items": [{"a": 1, "b": [Decimal("3.1"), date(2026, 1, 1)]}]}, "t", 1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Persist
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_persist_creates_directory_file_and_row(storage_root, db_session, project_id):
|
||||
art = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=15,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"hello-bytes",
|
||||
dto={"n": 1},
|
||||
)
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
assert path.is_file()
|
||||
assert path.read_bytes() == b"hello-bytes"
|
||||
assert path.parent == (
|
||||
storage_root.resolve()
|
||||
/ "projects"
|
||||
/ str(project_id)
|
||||
/ "documents"
|
||||
/ "ks2"
|
||||
/ "15"
|
||||
)
|
||||
assert art.content_hash == compute_content_hash(b"hello-bytes")
|
||||
assert art.input_hash == compute_input_hash({"n": 1}, "ks2_act", 1)
|
||||
assert art.is_current is True or art.is_current == 1
|
||||
assert art.project_id == project_id
|
||||
# service does not commit
|
||||
assert art.id is not None # flushed
|
||||
assert db_session.in_transaction()
|
||||
|
||||
|
||||
def test_persist_no_internal_commit(storage_root, db_session, project_id):
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=1,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"x",
|
||||
dto={},
|
||||
)
|
||||
# Row is visible in this session (flush) but caller still owns the tx
|
||||
assert db_session.in_transaction()
|
||||
db_session.rollback()
|
||||
# After rollback the row is gone — proving no commit happened
|
||||
assert db_session.execute(select(DocumentArtifact)).all() == []
|
||||
|
||||
|
||||
def test_persist_new_current_and_old_becomes_historical(storage_root, db_session, project_id):
|
||||
old = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=3,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"v1",
|
||||
dto={},
|
||||
)
|
||||
old_id = old.id
|
||||
new = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=3,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"v2",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
db_session.refresh(old)
|
||||
db_session.refresh(new)
|
||||
assert old.is_current in (False, 0)
|
||||
assert new.is_current in (True, 1)
|
||||
# History preserved
|
||||
assert db_session.get(DocumentArtifact, old_id) is not None
|
||||
assert resolve_storage_path(old.storage_key).is_file()
|
||||
assert resolve_storage_path(new.storage_key).is_file()
|
||||
|
||||
|
||||
def test_persist_different_formats_both_current(storage_root, db_session, project_id):
|
||||
a = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=4,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"excel",
|
||||
dto={},
|
||||
)
|
||||
b = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=4,
|
||||
format="pdf",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"pdf",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
assert a.is_current in (True, 1)
|
||||
assert b.is_current in (True, 1)
|
||||
|
||||
|
||||
def test_persist_db_failure_cleans_created_file(storage_root, db_session, project_id, monkeypatch):
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=5,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"first",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
first = resolve_storage_path(
|
||||
db_session.execute(select(DocumentArtifact)).scalar_one().storage_key
|
||||
)
|
||||
assert first.is_file()
|
||||
|
||||
def boom(*args, **kwargs):
|
||||
raise RuntimeError("forced db failure")
|
||||
|
||||
monkeypatch.setattr(db_session, "flush", boom)
|
||||
with pytest.raises(RuntimeError, match="forced db failure"):
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=5,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"should-be-cleaned",
|
||||
dto={},
|
||||
)
|
||||
monkeypatch.undo()
|
||||
db_session.rollback()
|
||||
after_files = list((storage_root / "projects").rglob("*.xlsx"))
|
||||
leaked = [p for p in after_files if p.read_bytes() == b"should-be-cleaned"]
|
||||
assert leaked == []
|
||||
# Existing artifact file is untouched
|
||||
assert first.is_file()
|
||||
assert first.read_bytes() == b"first"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Resolve
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_resolve_current(storage_root, db_session, project_id):
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=7,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"current-bytes",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
art, content = resolve_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=7,
|
||||
format="xlsx",
|
||||
)
|
||||
assert content == b"current-bytes"
|
||||
assert art.document_id == 7
|
||||
|
||||
|
||||
def test_resolve_historical_by_id(storage_root, db_session, project_id):
|
||||
old = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=8,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"old",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
old_id = old.id
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=8,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"new",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
art, content = resolve_artifact_by_id(
|
||||
db_session, artifact_id=old_id, project_id=project_id
|
||||
)
|
||||
assert content == b"old"
|
||||
assert art.is_current in (False, 0)
|
||||
|
||||
|
||||
def test_resolve_wrong_project_rejected(storage_root, db_session, project_id):
|
||||
art = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=9,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"data",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
with pytest.raises(DocumentArtifactError, match="does not belong"):
|
||||
resolve_artifact_by_id(
|
||||
db_session, artifact_id=art.id, project_id=project_id + 999
|
||||
)
|
||||
with pytest.raises(ArtifactNotFoundError):
|
||||
resolve_artifact(
|
||||
db_session,
|
||||
project_id=project_id + 999,
|
||||
document_type="ks2",
|
||||
document_id=9,
|
||||
format="xlsx",
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_missing_file(storage_root, db_session, project_id):
|
||||
art = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=10,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"soon-deleted",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
resolve_storage_path(art.storage_key).unlink()
|
||||
with pytest.raises(ArtifactNotFoundError, match="not found"):
|
||||
resolve_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=10,
|
||||
format="xlsx",
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_hash_mismatch(storage_root, db_session, project_id):
|
||||
art = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=11,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"original",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
path.write_bytes(b"tampered")
|
||||
with pytest.raises(ArtifactHashMismatchError):
|
||||
resolve_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=11,
|
||||
format="xlsx",
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_path_traversal_rejected(storage_root, db_session, project_id):
|
||||
with pytest.raises(ArtifactPathError):
|
||||
resolve_storage_path("../secret.txt")
|
||||
with pytest.raises(ArtifactPathError):
|
||||
resolve_storage_path("/etc/passwd")
|
||||
with pytest.raises(ArtifactPathError):
|
||||
resolve_storage_path("projects/1/../../../etc/passwd")
|
||||
with pytest.raises(ArtifactPathError):
|
||||
resolve_storage_path("")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Invalidate
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_invalidate_current(storage_root, db_session, project_id):
|
||||
art = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=20,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"a",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
updated = invalidate_artifacts(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=20,
|
||||
format="xlsx",
|
||||
)
|
||||
db_session.commit()
|
||||
assert updated == 1
|
||||
db_session.refresh(art)
|
||||
assert art.is_current in (False, 0)
|
||||
# file remains
|
||||
assert resolve_storage_path(art.storage_key).is_file()
|
||||
|
||||
|
||||
def test_invalidate_leaves_historical_unchanged(storage_root, db_session, project_id):
|
||||
old = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=21,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"old",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
old_id = old.id
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=21,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"new",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
# old is already historical
|
||||
row = db_session.get(DocumentArtifact, old_id)
|
||||
assert row.is_current in (False, 0)
|
||||
invalidate_artifacts(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=21,
|
||||
format="xlsx",
|
||||
)
|
||||
db_session.commit()
|
||||
assert db_session.get(DocumentArtifact, old_id).is_current in (False, 0)
|
||||
|
||||
|
||||
def test_invalidate_one_format_only(storage_root, db_session, project_id):
|
||||
xlsx = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=22,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"x",
|
||||
dto={},
|
||||
)
|
||||
pdf = persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=22,
|
||||
format="pdf",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"p",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
invalidate_artifacts(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=22,
|
||||
format="xlsx",
|
||||
)
|
||||
db_session.commit()
|
||||
db_session.refresh(xlsx)
|
||||
db_session.refresh(pdf)
|
||||
assert xlsx.is_current in (False, 0)
|
||||
assert pdf.is_current in (True, 1)
|
||||
|
||||
|
||||
def test_invalidate_all_formats(storage_root, db_session, project_id):
|
||||
for fmt in ("xlsx", "pdf"):
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks3",
|
||||
document_id=23,
|
||||
format=fmt,
|
||||
template_type="ks3_act",
|
||||
template_version=1,
|
||||
content=f"b-{fmt}".encode(),
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
updated = invalidate_artifacts(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks3",
|
||||
document_id=23,
|
||||
)
|
||||
db_session.commit()
|
||||
assert updated == 2
|
||||
assert (
|
||||
db_session.execute(
|
||||
select(DocumentArtifact).where(DocumentArtifact.is_current.is_(True))
|
||||
).all()
|
||||
== []
|
||||
)
|
||||
|
||||
|
||||
def test_invalidate_idempotent(storage_root, db_session, project_id):
|
||||
persist_artifact(
|
||||
db_session,
|
||||
project_id=project_id,
|
||||
document_type="ks2",
|
||||
document_id=24,
|
||||
format="xlsx",
|
||||
template_type="ks2_act",
|
||||
template_version=1,
|
||||
content=b"z",
|
||||
dto={},
|
||||
)
|
||||
db_session.commit()
|
||||
assert invalidate_artifacts(
|
||||
db_session, project_id=project_id, document_type="ks2", document_id=24
|
||||
) == 1
|
||||
db_session.commit()
|
||||
assert invalidate_artifacts(
|
||||
db_session, project_id=project_id, document_type="ks2", document_id=24
|
||||
) == 0
|
||||
db_session.commit()
|
||||
Reference in New Issue
Block a user