feat: include document artifacts in project export/import round-trip

This commit is contained in:
Арсентьев Александр
2026-09-30 12:24:49 +03:00
parent bc0e04a482
commit 8302250325
6 changed files with 1482 additions and 4 deletions
@@ -0,0 +1,420 @@
"""Tests for DOC-B7: Export/Import DocumentArtifact."""
from __future__ import annotations
import hashlib
import io
import json
import zipfile
from datetime import date
from decimal import Decimal
import pytest
from sqlalchemy import create_engine
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.exporters.project_export import export_project
from app.exporters.project_import import ProjectImportError, import_project, validate_archive
from app.models import ( # noqa: F401
agreement, boq, daily_report, document_artifact,
ks2, ks3, payment, project, work_journal,
)
from app.models.boq import BoqDocument, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.document_artifact import DocumentArtifact
from app.models.ks2 import KS2
from app.models.ks3 import KS3
from app.models.project import Project
from app.services.database_reset import reset_database
from app.services.document_artifact_service import compute_content_hash, resolve_storage_path
from app.services.ks2_service import cancel_ks2, issue_ks2, save_draft as save_ks2_draft
from app.services.ks3_service import cancel_ks3, issue_ks3, save_draft as save_ks3_draft
@pytest.fixture
def storage_root(tmp_path, monkeypatch):
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(tmp_path / "b7-storage"))
return tmp_path / "b7-storage"
@pytest.fixture
def db_session(storage_root):
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()
def _seed(db):
p = Project(name="B7 export", status="active")
db.add(p)
db.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
db.add(doc)
db.flush()
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="W", unit="шт",
quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"))
db.add(wi)
db.flush()
dr = DailyReport(project_id=p.id, report_date=date(2026, 2, 1))
db.add(dr)
db.flush()
db.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("50")))
db.commit()
return p.id, wi.id
def _issue_ks2(db, pid, wi_id, number="K2-B7"):
draft = save_ks2_draft(db, pid, number, date(2026, 3, 1), None,
[(wi_id, Decimal("10"))],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db.commit()
return issue_ks2(db, pid, draft.id)
def _issue_ks3(db, pid, ks2_id, number="K3-B7"):
draft = save_ks3_draft(db, pid, number, date(2026, 4, 1), None, [ks2_id],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db.commit()
return issue_ks3(db, pid, draft.id)
# ---------------------------------------------------------------------------
# Export
# ---------------------------------------------------------------------------
def test_export_includes_issued_ks2_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
assert "document_artifacts.json" in zf.namelist()
arts = json.loads(zf.read("document_artifacts.json"))
assert len(arts) == 1
assert arts[0]["document_type"] == "KS2"
assert arts[0]["format"] == "xlsx"
assert arts[0]["document_export_id"] == "ks2:00000001"
assert arts[0]["is_current"] is True
assert "artifacts/ks2/" in arts[0]["archive_path"]
# Physical file present
assert arts[0]["archive_path"] in zf.namelist()
# Checksum matches
file_bytes = zf.read(arts[0]["archive_path"])
assert compute_content_hash(file_bytes) == arts[0]["content_hash"]
def test_export_includes_issued_ks3_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
ks3 = _issue_ks3(db_session, pid, ks2.id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
arts = json.loads(zf.read("document_artifacts.json"))
ks3_arts = [a for a in arts if a["document_type"] == "KS3"]
assert len(ks3_arts) == 1
assert ks3_arts[0]["format"] == "docx"
assert ks3_arts[0]["archive_path"] in zf.namelist()
def test_export_includes_cancelled_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
cancel_ks2(db_session, pid, ks2.id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
arts = json.loads(zf.read("document_artifacts.json"))
assert len(arts) == 1
assert arts[0]["document_type"] == "KS2"
# Cancelled artifact is the original issued one
assert arts[0]["is_current"] is True
def test_export_skips_draft_artifacts(db_session):
pid, wi_id = _seed(db_session)
# Create a draft KS-2 (no artifact)
save_ks2_draft(db_session, pid, "K2-D", date(2026, 3, 1), None,
[(wi_id, Decimal("5"))],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db_session.commit()
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
arts = json.loads(zf.read("document_artifacts.json"))
assert len(arts) == 0
assert not any(n.startswith("artifacts/") for n in zf.namelist())
def test_export_manifest_count(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
manifest = json.loads(zipfile.ZipFile(io.BytesIO(data)).read("manifest.json"))
assert manifest["counts"]["document_artifacts"] == 1
def test_export_checksums_include_artifact_files(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
checksums = json.loads(zf.read("checksums.json"))
art = json.loads(zf.read("document_artifacts.json"))[0]
assert art["archive_path"] in checksums
# ---------------------------------------------------------------------------
# Import
# ---------------------------------------------------------------------------
def test_import_restores_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
assert art.document_type == "KS2"
assert art.format == "xlsx"
assert art.is_current is True
assert art.template_type == "ks2"
assert art.template_version == 1
# New IDs
assert art.project_id == imported.id
new_ks2 = db_session.query(KS2).filter_by(project_id=imported.id).one()
assert art.document_id == new_ks2.id
# File exists
path = resolve_storage_path(art.storage_key)
assert path.is_file()
# content_hash matches
assert art.content_hash == compute_content_hash(path.read_bytes())
def test_import_preserves_hashes_and_template(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
orig_art = db_session.query(DocumentArtifact).filter_by(project_id=pid).one()
ch, ih = orig_art.content_hash, orig_art.input_hash
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
assert art.content_hash == ch
assert art.input_hash == ih
assert art.template_type == "ks2"
assert art.template_version == 1
def test_import_cancelled_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
cancel_ks2(db_session, pid, ks2.id)
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
assert art.is_current is True
assert resolve_storage_path(art.storage_key).is_file()
def test_old_archive_without_artifacts_imports(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Strip document_artifacts.json and artifact files (old archive format)
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()
if n != "document_artifacts.json" and not n.startswith("artifacts/")}
zin.close()
checksums = json.loads(parts["checksums.json"].decode("utf-8"))
for k in list(checksums):
if k.startswith("artifacts/") or k == "document_artifacts.json":
del checksums[k]
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
old = buf.getvalue()
preview = validate_archive(old)
assert preview["counts"]["document_artifacts"] == 0
reset_database(db_session)
imported = import_project(db_session, old)
assert db_session.query(DocumentArtifact).filter_by(project_id=imported.id).count() == 0
def test_import_unknown_document_export_id_rejected(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Corrupt document_export_id
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
arts = json.loads(parts["document_artifacts.json"].decode("utf-8"))
arts[0]["document_export_id"] = "ks2:99999999"
parts["document_artifacts.json"] = json.dumps(arts).encode("utf-8")
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="document_export_id"):
validate_archive(buf.getvalue())
def test_import_draft_artifact_rejected(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Change KS-2 status to draft in the archive
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
ks2_rows = json.loads(parts["ks2.json"].decode("utf-8"))
ks2_rows[0]["status"] = "draft"
parts["ks2.json"] = json.dumps(ks2_rows).encode("utf-8")
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="issued/cancelled"):
validate_archive(buf.getvalue())
def test_import_checksum_mismatch_rejected(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Tamper with artifact file bytes but keep document_artifacts.json hash
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
art = json.loads(parts["document_artifacts.json"].decode("utf-8"))[0]
parts[art["archive_path"]] = b"tampered"
# Update checksums to match tampered file (so checksum check passes)
# but content_hash in JSON won't match
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="hash mismatch|сумма"):
validate_archive(buf.getvalue())
def test_import_path_traversal_rejected(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
arts = json.loads(parts["document_artifacts.json"].decode("utf-8"))
arts[0]["archive_path"] = "artifacts/../../etc/passwd.xlsx"
parts["document_artifacts.json"] = json.dumps(arts).encode("utf-8")
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="archive_path|небезопасный"):
validate_archive(buf.getvalue())
# ---------------------------------------------------------------------------
# Round-trip
# ---------------------------------------------------------------------------
def test_roundtrip_export_reset_import_export(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
ks3 = _issue_ks3(db_session, pid, ks2.id)
data1, _ = export_project(db_session, pid)
arts1 = json.loads(zipfile.ZipFile(io.BytesIO(data1)).read("document_artifacts.json"))
assert len(arts1) == 2 # KS2 + KS3
reset_database(db_session)
imported = import_project(db_session, data1)
# Verify artifacts restored
new_arts = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).all()
assert len(new_arts) == 2
for art in new_arts:
assert art.is_current is True
path = resolve_storage_path(art.storage_key)
assert path.is_file()
assert art.content_hash == compute_content_hash(path.read_bytes())
# Second export
data2, _ = export_project(db_session, imported.id)
arts2 = json.loads(zipfile.ZipFile(io.BytesIO(data2)).read("document_artifacts.json"))
assert len(arts2) == 2
# Hashes match original
h1 = {a["content_hash"] for a in arts1}
h2 = {a["content_hash"] for a in arts2}
assert h1 == h2
# Statuses preserved
ks2_statuses = {r["status"] for r in json.loads(zipfile.ZipFile(io.BytesIO(data2)).read("ks2.json"))}
assert "issued" in ks2_statuses
def test_roundtrip_cancelled_artifact_preserved(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
cancel_ks2(db_session, pid, ks2.id)
orig_bytes = resolve_storage_path(
db_session.query(DocumentArtifact).filter_by(project_id=pid).one().storage_key
).read_bytes()
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
new_bytes = resolve_storage_path(art.storage_key).read_bytes()
assert new_bytes == orig_bytes
# Cancelled status preserved
new_ks2 = db_session.query(KS2).filter_by(project_id=imported.id).one()
assert new_ks2.status == "cancelled"
def test_rollback_removes_physical_files_on_error(db_session, monkeypatch):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
art_count_before = db_session.query(DocumentArtifact).count()
# Force failure after artifact file write but before commit
from app.exporters import project_import as pi
original = pi._import_entities
def failing(db, payload):
project = original(db, payload)
raise RuntimeError("forced failure after artifact write")
monkeypatch.setattr(pi, "_import_entities", failing)
with pytest.raises(ProjectImportError):
import_project(db_session, data)
monkeypatch.setattr(pi, "_import_entities", original)
db_session.rollback()
# No new artifact rows from the failed import
assert db_session.query(DocumentArtifact).count() == art_count_before