Files
work-volume-tracker/tests/test_doc_b1_document_artifacts.py
T
2026-09-29 15:29:45 +03:00

323 lines
11 KiB
Python

"""Tests for DOC-B1: document_artifacts model, migration, storage root config."""
from __future__ import annotations
import os
import sqlite3
from datetime import datetime
from pathlib import Path
import pytest
from sqlalchemy import create_engine, inspect, text
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.config import (
ENV_DOCUMENT_STORAGE_ROOT,
document_storage_root,
)
from app.database.database import Base
from app.database.migrations import DOCUMENT_ARTIFACTS_MIGRATION, run_migrations
# Import all models so SQLAlchemy can resolve Project relationships.
from app.models import ( # noqa: F401
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
@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()
def _artifact(project_id, **overrides):
defaults = dict(
project_id=project_id,
document_type="ks2",
document_id=1,
format="xlsx",
storage_key="projects/1/documents/ks2/1/act.xlsx",
template_type="ks2_act",
template_version=1,
content_hash="a" * 64,
input_hash="b" * 64,
is_current=True,
generated_at=datetime(2026, 9, 28, 12, 0, 0),
)
defaults.update(overrides)
return DocumentArtifact(**defaults)
# ---------------------------------------------------------------------------
# Model
# ---------------------------------------------------------------------------
def test_create_document_artifact(db_session):
p = Project(name="Artifacts")
db_session.add(p)
db_session.flush()
art = _artifact(p.id)
db_session.add(art)
db_session.commit()
assert art.id is not None
assert art.document_type == "ks2"
assert art.is_current is True or art.is_current == 1
def test_required_fields_enforced(db_session):
p = Project(name="Required")
db_session.add(p)
db_session.flush()
# missing document_type
with pytest.raises(IntegrityError):
db_session.add(
_artifact(p.id, document_type=None)
)
db_session.commit()
db_session.rollback()
# missing storage_key
with pytest.raises(IntegrityError):
db_session.add(_artifact(p.id, storage_key=None))
db_session.commit()
db_session.rollback()
# missing content_hash
with pytest.raises(IntegrityError):
db_session.add(_artifact(p.id, content_hash=None))
db_session.commit()
db_session.rollback()
def test_is_current_defaults_to_true(db_session):
p = Project(name="Default current")
db_session.add(p)
db_session.flush()
art = DocumentArtifact(
project_id=p.id,
document_type="ks3",
document_id=7,
format="docx",
storage_key="k",
template_type="ks3_act",
template_version=1,
content_hash="c" * 64,
input_hash="d" * 64,
generated_at=datetime(2026, 1, 1),
)
db_session.add(art)
db_session.commit()
assert art.is_current in (True, 1)
def test_project_fk_relation(db_session):
p = Project(name="FK")
db_session.add(p)
db_session.flush()
art = _artifact(p.id)
db_session.add(art)
db_session.commit()
assert art.project_id == p.id
assert art.project.name == "FK"
def test_multiple_historical_artifacts_allowed(db_session):
p = Project(name="History")
db_session.add(p)
db_session.flush()
for i in range(3):
db_session.add(_artifact(p.id, is_current=False, storage_key=f"old-{i}.xlsx"))
db_session.commit()
assert db_session.query(DocumentArtifact).filter_by(is_current=False).count() == 3
def test_two_current_artifacts_same_key_rejected(db_session):
p = Project(name="Unique current")
db_session.add(p)
db_session.flush()
db_session.add(_artifact(p.id, is_current=True))
db_session.commit()
db_session.add(_artifact(p.id, is_current=True, storage_key="other.xlsx"))
with pytest.raises(IntegrityError):
db_session.commit()
db_session.rollback()
def test_current_allowed_for_different_formats(db_session):
p = Project(name="Multi format")
db_session.add(p)
db_session.flush()
db_session.add(_artifact(p.id, format="xlsx", is_current=True))
db_session.add(_artifact(p.id, format="pdf", is_current=True))
db_session.commit()
assert db_session.query(DocumentArtifact).filter_by(is_current=True).count() == 2
# ---------------------------------------------------------------------------
# Migration
# ---------------------------------------------------------------------------
def _migrate_db(tmp_path):
"""Create a DB with prior migrations applied, so only the new one runs."""
from app.database.migrations import (
MIGRATION, BASE_LINK_MIGRATION, SCOPE_MIGRATION,
ITEM_WORK_ITEM_MIGRATION, WORK_ITEM_OPTIONAL_BOQ_MIGRATION,
DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION, KS2_REPORTING_PERIOD_MIGRATION,
PAYMENT_STATUS_MIGRATION, KS3_NUMBER_UNIQUE_MIGRATION,
BOQ_DOCUMENT_REQUISITES_MIGRATION,
)
db_path = tmp_path / "migrate.db"
conn = sqlite3.connect(db_path, isolation_level=None)
conn.execute("PRAGMA foreign_keys=OFF")
conn.execute("""CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT PRIMARY KEY, applied_at TEXT NOT NULL)""")
conn.execute("""CREATE TABLE projects (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR NOT NULL,
contract_number VARCHAR, contract_date DATE, customer VARCHAR,
currency VARCHAR, start_date DATE, end_date DATE, status VARCHAR,
created_at DATETIME, updated_at DATETIME)""")
conn.execute(
"INSERT INTO projects (id, name, status) VALUES (1, 'Keep me', 'active')"
)
# Mark all prior migrations as applied so run_migrations only adds ours.
for version in (
MIGRATION, BASE_LINK_MIGRATION, SCOPE_MIGRATION,
ITEM_WORK_ITEM_MIGRATION, WORK_ITEM_OPTIONAL_BOQ_MIGRATION,
DAILY_REPORT_OPTIONAL_SYSTEM_MIGRATION, KS2_REPORTING_PERIOD_MIGRATION,
PAYMENT_STATUS_MIGRATION, KS3_NUMBER_UNIQUE_MIGRATION,
BOQ_DOCUMENT_REQUISITES_MIGRATION,
):
conn.execute(
"INSERT OR IGNORE INTO schema_migrations(version, applied_at) VALUES (?, ?)",
(version, "2026-01-01T00:00:00+00:00"),
)
conn.commit()
conn.close()
return db_path
def test_migration_creates_document_artifacts_table(tmp_path):
db_path = _migrate_db(tmp_path)
engine = create_engine(f"sqlite:///{db_path.as_posix()}")
run_migrations(engine)
engine.dispose()
conn = sqlite3.connect(db_path)
tables = {
row[0]
for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
}
assert "document_artifacts" in tables
cols = {
row[1] for row in conn.execute("PRAGMA table_info(document_artifacts)")
}
expected = {
"id", "project_id", "document_type", "document_id", "format",
"storage_key", "template_type", "template_version",
"content_hash", "input_hash", "is_current",
"generated_at", "created_at", "updated_at",
}
assert expected <= cols
applied = {
row[0] for row in conn.execute("SELECT version FROM schema_migrations")
}
assert DOCUMENT_ARTIFACTS_MIGRATION in applied
# partial unique index exists
indexes = {
row[1] for row in conn.execute("PRAGMA index_list(document_artifacts)")
}
assert "uq_document_artifact_current" in indexes
conn.close()
def test_migration_downgrade_drops_table(tmp_path):
db_path = _migrate_db(tmp_path)
engine = create_engine(f"sqlite:///{db_path.as_posix()}")
run_migrations(engine)
engine.dispose()
conn = sqlite3.connect(db_path, isolation_level=None)
# downgrade for this migration: drop table + indexes + version row
conn.execute("DROP INDEX IF EXISTS uq_document_artifact_current")
conn.execute("DROP INDEX IF EXISTS ix_document_artifacts_current")
conn.execute("DROP INDEX IF EXISTS ix_document_artifacts_type_doc")
conn.execute("DROP INDEX IF EXISTS ix_document_artifacts_project_id")
conn.execute("DROP INDEX IF EXISTS ix_document_artifacts_id")
conn.execute("DROP TABLE IF EXISTS document_artifacts")
conn.execute(
"DELETE FROM schema_migrations WHERE version = ?", (DOCUMENT_ARTIFACTS_MIGRATION,)
)
conn.commit()
tables = {
row[0]
for row in conn.execute("SELECT name FROM sqlite_master WHERE type='table'")
}
assert "document_artifacts" not in tables
# schema_migrations itself remains
assert "schema_migrations" in tables
conn.close()
def test_migration_preserves_existing_data(tmp_path):
db_path = _migrate_db(tmp_path)
engine = create_engine(f"sqlite:///{db_path.as_posix()}")
run_migrations(engine)
engine.dispose()
conn = sqlite3.connect(db_path)
rows = list(conn.execute("SELECT id, name FROM projects"))
assert rows == [(1, "Keep me")]
conn.close()
# ---------------------------------------------------------------------------
# Storage root config
# ---------------------------------------------------------------------------
def test_default_storage_root_independent_of_cwd(tmp_path, monkeypatch):
monkeypatch.delenv(ENV_DOCUMENT_STORAGE_ROOT, raising=False)
monkeypatch.chdir(tmp_path)
root = document_storage_root()
# Anchored to the app package parent, not cwd
assert root.is_absolute()
assert root.name == "storage"
assert tmp_path not in root.parents and root != tmp_path
def test_custom_storage_root_from_env(tmp_path, monkeypatch):
custom = tmp_path / "custom-docs"
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(custom))
root = document_storage_root()
assert root == custom.resolve()
def test_config_import_does_not_create_storage_dir(tmp_path, monkeypatch):
custom = tmp_path / "never-created"
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(custom))
# reload-free: just calling the accessor must not mkdir
_ = document_storage_root()
assert not custom.exists()
# default root also must not be created by accessor alone
monkeypatch.delenv(ENV_DOCUMENT_STORAGE_ROOT, raising=False)
default = document_storage_root()
# The default may exist already in a real workspace; the rule is that
# calling the function is side-effect free. We only assert the function
# returns a path and does not raise.
assert isinstance(default, Path)