"""Tests for DOC-B8: database reset with physical project storage cleanup.""" from __future__ import annotations from datetime import date from decimal import Decimal from pathlib import Path import pytest from sqlalchemy import create_engine, select 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 import_project 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.project import Project from app.services.database_reset import ( DatabaseResetError, count_project_data, project_storage_path, reset_database, ) from app.services.document_artifact_service import ( persist_artifact, resolve_storage_path, ) from app.services.ks2_service import issue_ks2, save_draft as save_ks2_draft @pytest.fixture def storage_root(tmp_path, monkeypatch): root = tmp_path / "b8-storage" monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(root)) return root @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_project_with_artifact(db, number="A"): """Project + issued KS-2 + artifact file on disk.""" p = Project(name=f"Proj {number}") 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() draft = save_ks2_draft(db, p.id, f"K2-{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() issue_ks2(db, p.id, draft.id) return p.id # --------------------------------------------------------------------------- # Successful reset # --------------------------------------------------------------------------- def test_reset_deletes_db_rows_and_storage(storage_root, db_session): pid = _seed_project_with_artifact(db_session) storage_dir = project_storage_path(pid) assert storage_dir.is_dir() assert db_session.query(DocumentArtifact).count() == 1 result = reset_database(db_session) assert all(v == 0 for v in result.verified.values()) assert result.storage_removed is True assert result.storage_error is None assert not storage_dir.exists() assert db_session.query(Project).count() == 0 assert db_session.query(DocumentArtifact).count() == 0 # --------------------------------------------------------------------------- # Multiple projects # --------------------------------------------------------------------------- def test_reset_multiple_projects_storage(storage_root, db_session): pid1 = _seed_project_with_artifact(db_session, "A") pid2 = _seed_project_with_artifact(db_session, "B") dir1 = project_storage_path(pid1) dir2 = project_storage_path(pid2) assert dir1.is_dir() and dir2.is_dir() # Unrelated orphan storage that must NOT be deleted orphan = (storage_root / "projects" / "999") orphan.mkdir(parents=True, exist_ok=True) (orphan / "keep.txt").write_text("orphan") reset_database(db_session) assert not dir1.exists() assert not dir2.exists() assert orphan.is_dir() assert (orphan / "keep.txt").is_file() # --------------------------------------------------------------------------- # Empty / missing storage # --------------------------------------------------------------------------- def test_reset_missing_storage_is_success(storage_root, db_session): pid = _seed_project_with_artifact(db_session) # Remove storage before reset import shutil shutil.rmtree(project_storage_path(pid)) result = reset_database(db_session) assert result.storage_removed is True assert result.storage_error is None def test_reset_empty_storage_dir(storage_root, db_session): pid = _seed_project_with_artifact(db_session) # Empty the directory import shutil d = project_storage_path(pid) for f in d.rglob("*"): if f.is_file(): f.unlink() result = reset_database(db_session) assert result.storage_removed is True assert not d.exists() # empty dir is also removed # --------------------------------------------------------------------------- # DB rollback → no FS deletion # --------------------------------------------------------------------------- def test_db_rollback_does_not_touch_storage(storage_root, db_session, monkeypatch): pid = _seed_project_with_artifact(db_session) storage_dir = project_storage_path(pid) assert storage_dir.is_dir() # Force DB deletion to fail def boom(*args, **kwargs): raise RuntimeError("forced db failure") monkeypatch.setattr(db_session, "execute", boom) with pytest.raises(DatabaseResetError): reset_database(db_session) monkeypatch.undo() db_session.rollback() # Storage untouched assert storage_dir.is_dir() assert db_session.query(Project).count() == 1 # --------------------------------------------------------------------------- # FS failure after DB commit # --------------------------------------------------------------------------- def test_fs_failure_does_not_rollback_db(storage_root, db_session, monkeypatch): pid = _seed_project_with_artifact(db_session) storage_dir = project_storage_path(pid) import shutil as _shutil original_rmtree = _shutil.rmtree def failing_rmtree(path, *args, **kwargs): raise OSError("forced rmtree failure") monkeypatch.setattr("app.services.database_reset.shutil.rmtree", failing_rmtree) result = reset_database(db_session) monkeypatch.setattr("app.services.database_reset.shutil.rmtree", original_rmtree) # DB is clean assert all(v == 0 for v in result.verified.values()) # FS still exists assert storage_dir.is_dir() # Error reported assert result.storage_removed is False assert result.storage_error is not None assert "rmtree" in result.storage_error or "OSError" in result.storage_error # --------------------------------------------------------------------------- # Security # --------------------------------------------------------------------------- def test_project_storage_path_rejects_bad_ids(storage_root): with pytest.raises(ValueError): project_storage_path(-1) with pytest.raises(ValueError): project_storage_path(0) # Large id is fine — path is still inside projects root p = project_storage_path(999999) assert p.parent == (storage_root / "projects").resolve() def test_project_storage_path_inside_root(storage_root): p = project_storage_path(1) root = storage_root.resolve() assert p.is_relative_to(root) assert p.parent == (root / "projects") def test_reset_does_not_delete_other_projects(storage_root, db_session): pid1 = _seed_project_with_artifact(db_session, "A") # Create a second project without artifacts p2 = Project(name="No storage") db_session.add(p2) db_session.commit() dir1 = project_storage_path(pid1) dir2 = project_storage_path(p2.id) dir2.mkdir(parents=True, exist_ok=True) (dir2 / "x.txt").write_text("keep") # Reset only deletes DB rows for ALL projects (existing behavior), # but FS cleanup only touches project IDs that were in DB. result = reset_database(db_session) assert not dir1.exists() # dir2 was for p2 which WAS in DB, so it gets deleted too assert not dir2.exists() # --------------------------------------------------------------------------- # Idempotency # --------------------------------------------------------------------------- def test_repeated_reset_safe(storage_root, db_session): pid = _seed_project_with_artifact(db_session) result1 = reset_database(db_session) assert result1.storage_removed is True result2 = reset_database(db_session) assert result2.storage_removed is True # nothing to remove, still ok assert result2.storage_error is None assert not project_storage_path(pid).exists() # --------------------------------------------------------------------------- # Integration # --------------------------------------------------------------------------- def test_export_reset_import_artifacts_survive(storage_root, db_session): pid = _seed_project_with_artifact(db_session) data, _ = export_project(db_session, pid) result = reset_database(db_session) assert result.storage_removed is True imported = import_project(db_session, data) art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one() path = resolve_storage_path(art.storage_key) assert path.is_file() # New project storage exists assert project_storage_path(imported.id).is_dir()