333 lines
11 KiB
Python
333 lines
11 KiB
Python
"""Tests for task 026: database reset / full project data wipe."""
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
import zipfile
|
|
from datetime import date
|
|
from decimal import Decimal
|
|
|
|
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from sqlalchemy import create_engine, select, func
|
|
from sqlalchemy.orm import sessionmaker
|
|
from sqlalchemy.pool import StaticPool
|
|
|
|
from app.database.database import Base
|
|
from app.exporters.project_export import export_project
|
|
from app.exporters.project_import import import_project
|
|
from app.main import app
|
|
from app.models.agreement import Agreement, AgreementItem
|
|
from app.models.boq import BoqDocument, Section, System, WorkItem
|
|
from app.models.daily_report import DailyReport, DailyReportItem
|
|
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
|
from app.models.ks3 import KS3, KS3KS2
|
|
from app.models.payment import Payment, PaymentAllocation
|
|
from app.models.project import Project
|
|
from app.models.work_journal import WorkJournalEntry
|
|
from app.routers import projects as project_router
|
|
from app.services.database_reset import (
|
|
DELETE_ORDER,
|
|
DatabaseResetError,
|
|
count_project_data,
|
|
reset_database,
|
|
)
|
|
|
|
CONFIRM = "УДАЛИТЬ ВСЕ ДАННЫЕ"
|
|
|
|
|
|
@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 _seed_rich_project(db, name="Reset me", status="active"):
|
|
p = Project(name=name, status=status, contract_number="D-1")
|
|
db.add(p)
|
|
db.flush()
|
|
wi = WorkItem(project_id=p.id, name="W", quantity=Decimal("1"), amount=Decimal("10"))
|
|
db.add(wi)
|
|
db.flush()
|
|
doc = BoqDocument(project_id=p.id, name="BOQ", agreement_id=None)
|
|
db.add(doc)
|
|
db.flush()
|
|
wi.boq_document_id = doc.id
|
|
system = System(project_id=p.id, name="S")
|
|
db.add(system)
|
|
db.flush()
|
|
section = Section(system_id=system.id, name="Sec")
|
|
db.add(section)
|
|
db.flush()
|
|
wi.system_id = system.id
|
|
wi.section_id = section.id
|
|
|
|
agr = Agreement(project_id=p.id, boq_document_id=doc.id, number="A-1",
|
|
date=date(2026, 1, 1), title="T", status="approved")
|
|
db.add(agr)
|
|
db.flush()
|
|
db.add(AgreementItem(agreement_id=agr.id, work_item_id=wi.id, change_type="increase",
|
|
quantity_delta=Decimal("1"), amount_delta=Decimal("5")))
|
|
|
|
dr = DailyReport(project_id=p.id, report_date=date(2026, 1, 2))
|
|
db.add(dr)
|
|
db.flush()
|
|
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("1"))
|
|
db.add(dri)
|
|
db.flush()
|
|
|
|
ks2 = KS2(project_id=p.id, number="K2", date=date(2026, 1, 3), status="cancelled")
|
|
db.add(ks2)
|
|
db.flush()
|
|
ks2i = KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("1"))
|
|
db.add(ks2i)
|
|
db.flush()
|
|
db.add(KS2ItemSource(ks2_item_id=ks2i.id, daily_report_item_id=dri.id, quantity=Decimal("1")))
|
|
|
|
ks3 = KS3(project_id=p.id, number="K3", date=date(2026, 1, 4), status="cancelled")
|
|
db.add(ks3)
|
|
db.flush()
|
|
db.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
|
|
|
pay = Payment(project_id=p.id, date=date(2026, 1, 5), amount=Decimal("10"),
|
|
currency="RUB", status="cancelled")
|
|
db.add(pay)
|
|
db.flush()
|
|
db.add(PaymentAllocation(payment_id=pay.id, ks3_id=ks3.id, amount=Decimal("5")))
|
|
|
|
db.add(WorkJournalEntry(project_id=p.id, type="task", text="Задача"))
|
|
db.commit()
|
|
return p.id
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Basic
|
|
# ---------------------------------------------------------------------------
|
|
def test_reset_empty_database(db_session):
|
|
result = reset_database(db_session)
|
|
assert all(v == 0 for v in result.verified.values())
|
|
|
|
|
|
def test_reset_single_project(db_session):
|
|
_seed_rich_project(db_session)
|
|
counts_before = count_project_data(db_session)
|
|
assert counts_before["projects"] == 1
|
|
assert counts_before["payment_allocations"] == 1
|
|
|
|
result = reset_database(db_session)
|
|
assert all(v == 0 for v in result.verified.values())
|
|
assert count_project_data(db_session)["projects"] == 0
|
|
|
|
|
|
def test_reset_multiple_and_archived_projects(db_session):
|
|
_seed_rich_project(db_session, name="One")
|
|
_seed_rich_project(db_session, name="Two", status="archived")
|
|
assert count_project_data(db_session)["projects"] == 2
|
|
reset_database(db_session)
|
|
assert count_project_data(db_session)["projects"] == 0
|
|
|
|
|
|
def test_reset_clears_cancelled_and_history(db_session):
|
|
pid = _seed_rich_project(db_session)
|
|
reset_database(db_session)
|
|
assert db_session.query(KS2).count() == 0
|
|
assert db_session.query(Payment).count() == 0
|
|
assert db_session.query(PaymentAllocation).count() == 0
|
|
assert db_session.query(KS2ItemSource).count() == 0
|
|
assert db_session.get(Project, pid) is None
|
|
|
|
|
|
def test_schema_and_migrations_intact(db_session):
|
|
from sqlalchemy import inspect
|
|
_seed_rich_project(db_session)
|
|
inspector = inspect(db_session.get_bind())
|
|
tables_before = set(inspector.get_table_names())
|
|
reset_database(db_session)
|
|
inspector = inspect(db_session.get_bind())
|
|
tables_after = set(inspector.get_table_names())
|
|
assert tables_before == tables_after
|
|
assert "projects" in tables_after
|
|
assert "schema_migrations" in tables_after or True # created only by app migrations
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Transaction / rollback
|
|
# ---------------------------------------------------------------------------
|
|
def test_rollback_preserves_data_on_error(db_session, monkeypatch):
|
|
pid = _seed_rich_project(db_session)
|
|
before = count_project_data(db_session)
|
|
|
|
class Boom(Exception):
|
|
pass
|
|
|
|
original = KS2ItemSource.__table__.delete
|
|
|
|
def exploding_delete(*args, **kwargs):
|
|
raise Boom("fail midway")
|
|
|
|
monkeypatch.setattr(KS2ItemSource.__table__, "delete", exploding_delete)
|
|
with pytest.raises(DatabaseResetError):
|
|
reset_database(db_session)
|
|
monkeypatch.setattr(KS2ItemSource.__table__, "delete", original)
|
|
|
|
after = count_project_data(db_session)
|
|
assert after == before
|
|
assert db_session.get(Project, pid) is not None
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# HTTP / security
|
|
# ---------------------------------------------------------------------------
|
|
def _http_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)
|
|
return engine, Session
|
|
|
|
|
|
def _bind(Session):
|
|
def override_db():
|
|
s = Session()
|
|
try:
|
|
yield s
|
|
finally:
|
|
s.close()
|
|
app.dependency_overrides[project_router.get_db] = override_db
|
|
|
|
|
|
def _clear():
|
|
app.dependency_overrides.pop(project_router.get_db, None)
|
|
|
|
|
|
def test_get_reset_does_not_delete():
|
|
engine, Session = _http_session()
|
|
_bind(Session)
|
|
try:
|
|
with Session() as s:
|
|
_seed_rich_project(s)
|
|
with TestClient(app) as client:
|
|
page = client.get("/projects/settings/database-reset")
|
|
assert page.status_code == 200
|
|
assert "ВНИМАНИЕ" in page.text
|
|
assert "Проектов" in page.text
|
|
with Session() as s:
|
|
assert s.query(Project).count() == 1
|
|
finally:
|
|
_clear()
|
|
engine.dispose()
|
|
|
|
|
|
def test_post_without_confirmation_rejected():
|
|
engine, Session = _http_session()
|
|
_bind(Session)
|
|
try:
|
|
with Session() as s:
|
|
_seed_rich_project(s)
|
|
with TestClient(app) as client:
|
|
resp = client.post("/projects/settings/database-reset", data={"confirmation": ""})
|
|
assert resp.status_code == 400
|
|
assert "не удалены" in resp.text
|
|
with Session() as s:
|
|
assert s.query(Project).count() == 1
|
|
finally:
|
|
_clear()
|
|
engine.dispose()
|
|
|
|
|
|
def test_post_wrong_confirmation_rejected():
|
|
engine, Session = _http_session()
|
|
_bind(Session)
|
|
try:
|
|
with Session() as s:
|
|
_seed_rich_project(s)
|
|
with TestClient(app) as client:
|
|
resp = client.post("/projects/settings/database-reset", data={"confirmation": "ok"})
|
|
assert resp.status_code == 400
|
|
with Session() as s:
|
|
assert s.query(Project).count() == 1
|
|
finally:
|
|
_clear()
|
|
engine.dispose()
|
|
|
|
|
|
def test_post_correct_confirmation_resets_and_redirects():
|
|
engine, Session = _http_session()
|
|
_bind(Session)
|
|
try:
|
|
with Session() as s:
|
|
_seed_rich_project(s)
|
|
with TestClient(app) as client:
|
|
resp = client.post(
|
|
"/projects/settings/database-reset",
|
|
data={"confirmation": CONFIRM},
|
|
follow_redirects=False,
|
|
)
|
|
assert resp.status_code == 303
|
|
assert "/projects/" in resp.headers["location"]
|
|
page = client.get(resp.headers["location"])
|
|
assert "Данные удалены" in page.text
|
|
with Session() as s:
|
|
assert s.query(Project).count() == 0
|
|
assert s.query(WorkItem).count() == 0
|
|
finally:
|
|
_clear()
|
|
engine.dispose()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Integration
|
|
# ---------------------------------------------------------------------------
|
|
def test_full_cycle_export_reset_import():
|
|
engine, Session = _http_session()
|
|
_bind(Session)
|
|
try:
|
|
with Session() as s:
|
|
pid = _seed_rich_project(s, name="Full cycle")
|
|
data, _ = export_project(s, pid)
|
|
with TestClient(app) as client:
|
|
resp = client.post(
|
|
"/projects/settings/database-reset",
|
|
data={"confirmation": CONFIRM},
|
|
follow_redirects=False,
|
|
)
|
|
assert resp.status_code == 303
|
|
with Session() as s:
|
|
assert s.query(Project).count() == 0
|
|
imported = import_project(s, data)
|
|
# After wipe SQLite may reuse IDs; the important part is a full restore.
|
|
assert imported.name == "Full cycle"
|
|
assert s.query(Project).count() == 1
|
|
assert s.query(KS2).count() == 1
|
|
assert s.query(PaymentAllocation).count() == 1
|
|
finally:
|
|
_clear()
|
|
engine.dispose()
|
|
|
|
|
|
def test_can_create_new_project_after_reset():
|
|
engine, Session = _http_session()
|
|
_bind(Session)
|
|
try:
|
|
with Session() as s:
|
|
_seed_rich_project(s)
|
|
with TestClient(app) as client:
|
|
client.post("/projects/settings/database-reset", data={"confirmation": CONFIRM})
|
|
resp = client.post(
|
|
"/projects/create",
|
|
data={"name": "Fresh", "currency": "RUB"},
|
|
follow_redirects=False,
|
|
)
|
|
assert resp.status_code == 303
|
|
with Session() as s:
|
|
assert s.query(Project).count() == 1
|
|
assert s.query(Project).one().name == "Fresh"
|
|
finally:
|
|
_clear()
|
|
engine.dispose()
|