Files
work-volume-tracker/tests/test_task019_document_package.py
Арсентьев Александр d8e92386d9 feat: add document package ZIP export
2026-09-27 14:58:51 +03:00

500 lines
20 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Regression tests for task 019: document package ZIP export."""
import datetime
import io
import shutil
import zipfile
from decimal import Decimal
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.database.database import Base, DATABASE_PATH
from app.main import app
from app.models.project import Project
from app.models.boq import BoqDocument, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.ks2 import KS2, KS2Item
from app.models.ks3 import KS3, KS3KS2
from app.routers import projects, ks2 as ks2_router, ks3 as ks3_router, ks6a as ks6a_router
def _make_session(tmp_path):
db_path = tmp_path / "t019-copy.db"
shutil.copy2(DATABASE_PATH, db_path)
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
Base.metadata.create_all(bind=engine)
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
def _override(Session):
def override_db():
s = Session()
try:
yield s
finally:
s.close()
for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db, ks6a_router.get_db):
app.dependency_overrides[dep] = override_db
def _clear():
for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db, ks6a_router.get_db):
app.dependency_overrides.pop(dep, None)
def _create_project_package_data(Session):
"""One project with DailyReportItems, issued/draft/cancelled KS-2 and KS-3."""
with Session() as s:
p = Project(name="Саудовская Аравия", customer="Customer LLC", contract_number="DOG-019")
s.add(p)
s.flush()
other = Project(name="Other project", customer="Other")
s.add(other)
s.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
s.add(doc)
s.flush()
other_doc = BoqDocument(project_id=other.id, name="BOQ other")
s.add(other_doc)
s.flush()
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Монтаж трубы",
source_number="1.1", unit="м", quantity=Decimal("100"),
unit_price=Decimal("50"), amount=Decimal("5000"))
other_wi = WorkItem(project_id=other.id, boq_document_id=other_doc.id, name="Чужая работа",
source_number="9.9", unit="шт", quantity=Decimal("10"),
unit_price=Decimal("1"), amount=Decimal("10"))
s.add_all([wi, other_wi])
s.flush()
dr = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 10))
other_dr = DailyReport(project_id=other.id, report_date=datetime.date(2026, 3, 10))
s.add_all([dr, other_dr])
s.flush()
s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("10")))
s.add(DailyReportItem(daily_report_id=other_dr.id, work_item_id=other_wi.id, completed_quantity=Decimal("5")))
s.flush()
period_from = datetime.date(2026, 3, 1)
period_to = datetime.date(2026, 3, 31)
ks2_ok = KS2(project_id=p.id, number="1", date=datetime.date(2026, 3, 20),
status="issued", reporting_period_from=period_from, reporting_period_to=period_to)
ks2_draft = KS2(project_id=p.id, number="2", date=datetime.date(2026, 3, 21),
status="draft", reporting_period_from=period_from, reporting_period_to=period_to)
ks2_cancelled = KS2(project_id=p.id, number="3", date=datetime.date(2026, 3, 22),
status="cancelled", reporting_period_from=period_from, reporting_period_to=period_to)
ks2_other_period = KS2(project_id=p.id, number="4", date=datetime.date(2026, 5, 1),
status="issued",
reporting_period_from=datetime.date(2026, 5, 1),
reporting_period_to=datetime.date(2026, 5, 31))
ks2_other_project = KS2(project_id=other.id, number="1", date=datetime.date(2026, 3, 20),
status="issued", reporting_period_from=period_from, reporting_period_to=period_to)
s.add_all([ks2_ok, ks2_draft, ks2_cancelled, ks2_other_period, ks2_other_project])
s.flush()
for ks2 in (ks2_ok, ks2_draft, ks2_cancelled, ks2_other_period, ks2_other_project):
item_wi = wi if ks2.project_id == p.id else other_wi
s.add(KS2Item(ks2_id=ks2.id, work_item_id=item_wi.id,
quantity=Decimal("5"), unit_price=Decimal("50"), amount=Decimal("250")))
s.flush()
ks3_ok = KS3(project_id=p.id, number="1", date=datetime.date(2026, 3, 25),
status="issued", reporting_period_from=period_from, reporting_period_to=period_to)
ks3_draft = KS3(project_id=p.id, number="2", date=datetime.date(2026, 3, 26),
status="draft", reporting_period_from=period_from, reporting_period_to=period_to)
ks3_cancelled = KS3(project_id=p.id, number="3", date=datetime.date(2026, 3, 27),
status="cancelled", reporting_period_from=period_from, reporting_period_to=period_to)
ks3_other_period = KS3(project_id=p.id, number="4", date=datetime.date(2026, 6, 1),
status="issued",
reporting_period_from=datetime.date(2026, 6, 1),
reporting_period_to=datetime.date(2026, 6, 30))
s.add_all([ks3_ok, ks3_draft, ks3_cancelled, ks3_other_period])
s.flush()
s.add(KS3KS2(ks3_id=ks3_ok.id, ks2_id=ks2_ok.id))
s.commit()
return {"pid": p.id, "other_pid": other.id}
PERIOD = "date_from=2026-03-01&date_to=2026-03-31"
ALL_DOCS = "include=ks6a&include=ks2&include=ks3"
def _package_url(pid, query=""):
base = f"/projects/{pid}/export/package?{PERIOD}"
return f"{base}&{query}" if query else base
def _zip_namelist(resp):
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
return zf.namelist()
def _zip_read(resp, name):
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
return zf.read(name)
def test_package_form_available_on_project_page(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
page = client.get(f"/projects/{data['pid']}")
assert page.status_code == 200
assert "Комплект документов" in page.text
assert "/export/package" in page.text
finally:
_clear()
engine.dispose()
def test_package_endpoint_available(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
assert resp.status_code == 200
assert "application/zip" in resp.headers["content-type"]
finally:
_clear()
engine.dispose()
def test_package_zip_created(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
assert zipfile.is_zipfile(io.BytesIO(resp.content))
names = _zip_namelist(resp)
assert len(names) > 0
finally:
_clear()
engine.dispose()
def test_package_contains_ks6a(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks6a&format=both"))
names = _zip_namelist(resp)
assert any(n.startswith("КС-6а/") and n.endswith(".xlsx") for n in names)
assert any(n.startswith("КС-6а/") and n.endswith(".docx") for n in names)
finally:
_clear()
engine.dispose()
def test_package_contains_ks2(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks2&format=excel"))
names = _zip_namelist(resp)
ks2_files = [n for n in names if n.startswith("КС-2/") and n.endswith(".xlsx")]
assert len(ks2_files) == 1
assert "1" in ks2_files[0]
finally:
_clear()
engine.dispose()
def test_package_contains_ks3(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks3&format=excel"))
names = _zip_namelist(resp)
ks3_files = [n for n in names if n.startswith("КС-3/") and n.endswith(".xlsx")]
assert len(ks3_files) == 1
assert "1" in ks3_files[0]
finally:
_clear()
engine.dispose()
def test_package_single_doc_type_only(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks6a&format=excel"))
names = _zip_namelist(resp)
assert names
assert all(n.startswith("КС-6а/") for n in names)
assert not any(n.startswith("КС-2/") for n in names)
assert not any(n.startswith("КС-3/") for n in names)
finally:
_clear()
engine.dispose()
def test_package_excel_only(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=excel"))
names = _zip_namelist(resp)
assert names
assert all(n.endswith(".xlsx") for n in names)
assert not any(n.endswith(".docx") for n in names)
finally:
_clear()
engine.dispose()
def test_package_word_only(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=word"))
names = _zip_namelist(resp)
assert names
assert all(n.endswith(".docx") for n in names)
assert not any(n.endswith(".xlsx") for n in names)
finally:
_clear()
engine.dispose()
def test_package_both_formats(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks6a&format=both"))
names = _zip_namelist(resp)
assert any(n.endswith(".xlsx") for n in names)
assert any(n.endswith(".docx") for n in names)
finally:
_clear()
engine.dispose()
def test_package_skips_cancelled_ks2(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks2&format=excel"))
names = _zip_namelist(resp)
# Only issued #1; cancelled #3 must be absent
assert len(names) == 1
assert "_№1_" in names[0]
assert "_№3_" not in names[0]
finally:
_clear()
engine.dispose()
def test_package_skips_cancelled_ks3(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks3&format=excel"))
names = _zip_namelist(resp)
assert len(names) == 1
assert "_№1_" in names[0]
assert "_№3_" not in names[0]
finally:
_clear()
engine.dispose()
def test_package_skips_draft_documents(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks2&include=ks3&format=excel"))
names = _zip_namelist(resp)
basenames = [n.split("/")[-1] for n in names]
assert len(names) == 2 # issued KS-2 #1 + issued KS-3 #1
for name in basenames:
assert "_№2_" not in name # draft numbers
finally:
_clear()
engine.dispose()
def test_package_excludes_other_period(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks2&include=ks3&format=excel"))
names = _zip_namelist(resp)
basenames = [n.split("/")[-1] for n in names]
assert len(names) == 2
for name in basenames:
assert "_№4_" not in name # other-period numbers
finally:
_clear()
engine.dispose()
def test_package_excludes_other_project(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
for name in zf.namelist():
payload = zf.read(name)
if name.endswith((".xlsx", ".docx")) and not name.startswith("КС-6а/"):
assert b"Other project" not in payload
if name.startswith("KS-2/") or name.startswith("KS-3/"):
raise AssertionError("unexpected")
# Also: other project's package must not contain this project's work
other_resp = client.get(_package_url(data["other_pid"], "include=ks2&format=excel"))
other_names = _zip_namelist(other_resp)
assert len(other_names) == 1
assert "9.9" not in other_names[0]
finally:
_clear()
engine.dispose()
def test_package_empty_composition(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
# No matching issued KS-2/KS-3 for this narrow window; KS-6a also empty
resp = client.get(
f"/projects/{data['pid']}/export/package"
f"?date_from=2026-07-01&date_to=2026-07-31&include=ks2&include=ks3&format=both"
)
assert resp.status_code == 400
assert "нет документов" in resp.json()["detail"].lower() or "нет документов" in resp.text.lower()
finally:
_clear()
engine.dispose()
def test_package_only_ks6a_still_builds_zip(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks6a&format=excel"))
assert resp.status_code == 200
names = _zip_namelist(resp)
assert len(names) == 1
assert names[0].startswith("КС-6а/")
finally:
_clear()
engine.dispose()
def test_package_filename_contains_project_and_period(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
disposition = resp.headers["content-disposition"]
assert "01.03.2026-31.03.2026" in disposition
assert "Саудовская" in disposition or "filename" in disposition
finally:
_clear()
engine.dispose()
def test_package_members_openable(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
names = _zip_namelist(resp)
excel_name = next(n for n in names if n.startswith("КС-2/") and n.endswith(".xlsx"))
word_name = next(n for n in names if n.startswith("КС-3/") and n.endswith(".docx"))
from openpyxl import load_workbook
wb = load_workbook(io.BytesIO(_zip_read(resp, excel_name)))
assert wb.active is not None
text = "\n".join(
str(cell.value) for row in wb.active.iter_rows() for cell in row if cell.value is not None
)
assert "Монтаж трубы" in text
from docx import Document
d = Document(io.BytesIO(_zip_read(resp, word_name)))
assert len(d.tables) > 0
finally:
_clear()
engine.dispose()
def test_package_includes_money_regardless_of_privacy(tmp_path):
"""ZIP contains real amounts; eye icon is UI-only."""
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with TestClient(app) as client:
resp = client.get(_package_url(data["pid"], "include=ks2&format=excel"))
name = _zip_namelist(resp)[0]
from openpyxl import load_workbook
wb = load_workbook(io.BytesIO(_zip_read(resp, name)))
text = "\n".join(
str(cell.value) for row in wb.active.iter_rows() for cell in row if cell.value is not None
)
assert "250" in text # KS-2 amount present
finally:
_clear()
engine.dispose()
def test_individual_exports_still_work(tmp_path):
engine, Session = _make_session(tmp_path)
_override(Session)
try:
data = _create_project_package_data(Session)
with Session() as s:
ks2_id = s.query(KS2).filter(KS2.project_id == data["pid"], KS2.number == "1").one().id
ks3_id = s.query(KS3).filter(KS3.project_id == data["pid"], KS3.number == "1").one().id
with TestClient(app) as client:
assert client.get(f"/projects/{data['pid']}/ks2/{ks2_id}/export/excel").status_code == 200
assert client.get(f"/projects/{data['pid']}/ks2/{ks2_id}/export/word").status_code == 200
assert client.get(f"/projects/{data['pid']}/ks3/{ks3_id}/export/excel").status_code == 200
assert client.get(f"/projects/{data['pid']}/ks3/{ks3_id}/export/word").status_code == 200
assert client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}").status_code == 200
assert client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}").status_code == 200
finally:
_clear()
engine.dispose()