"""Regression tests for task 017: KS-3 Excel/Word export.""" import io import shutil from decimal import Decimal from pathlib import Path 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 def _make_session(tmp_path): db_path = tmp_path / "t017-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): app.dependency_overrides[dep] = override_db def _clear(): for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db): app.dependency_overrides.pop(dep, None) def _create_ks3(Session, num_ks2=1): with Session() as s: p = Project(name="KS3 export test", customer="Customer LLC", contract_number="DOG-456") s.add(p) s.flush() doc = BoqDocument(project_id=p.id, name="BOQ") s.add(doc) s.flush() ks2_ids = [] for i in range(num_ks2): wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name=f"Item {i+1}", source_number=f"{i+1}.1", unit="м", quantity=Decimal("100"), unit_price=Decimal("50"), amount=Decimal("5000")) s.add(wi) s.flush() dr = DailyReport(project_id=p.id, report_date=__import__("datetime").date(2026, 1, 1)) s.add(dr) s.flush() s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("30"))) s.flush() ks2 = KS2(project_id=p.id, number=str(i+1), date=__import__("datetime").date(2026, 9, 30), status="issued") s.add(ks2) s.flush() s.add(KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("30"), unit_price=Decimal("50"), amount=Decimal("1500"))) s.flush() ks2_ids.append(ks2.id) ks3 = KS3(project_id=p.id, number="1", date=__import__("datetime").date(2026, 9, 30), status="issued") s.add(ks3) s.flush() for kid in ks2_ids: s.add(KS3KS2(ks3_id=ks3.id, ks2_id=kid)) s.commit() return p.id, ks3.id def test_ks3_excel_endpoint_exists(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") assert resp.status_code == 200 finally: _clear() engine.dispose() def test_ks3_word_endpoint_exists(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word") assert resp.status_code == 200 finally: _clear() engine.dispose() def test_ks3_excel_content_type(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") assert "spreadsheetml" in resp.headers["content-type"] finally: _clear() engine.dispose() def test_ks3_word_content_type(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word") assert "wordprocessingml" in resp.headers["content-type"] finally: _clear() engine.dispose() def test_ks3_filename_contains_number(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") assert "filename" in resp.headers["content-disposition"] finally: _clear() engine.dispose() def test_ks3_excel_opens_with_openpyxl(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) assert wb.active is not None finally: _clear() engine.dispose() def test_ks3_word_opens_with_python_docx(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word") from docx import Document d = Document(io.BytesIO(resp.content)) assert len(d.tables) > 0 finally: _clear() engine.dispose() def test_ks3_excel_contains_ks2(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active text = "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value) assert "№1" in text finally: _clear() engine.dispose() def test_ks3_word_contains_ks2(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word") from docx import Document d = Document(io.BytesIO(resp.content)) text = "\n".join(p.text for p in d.paragraphs) for table in d.tables: for row in table.rows: text += "\n" + " | ".join(c.text for c in row.cells) assert "№1" in text finally: _clear() engine.dispose() def test_ks3_excel_total_matches(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active total_found = False for row in ws.iter_rows(): for cell in row: if cell.value == "Итого:": total_cell = ws.cell(row=cell.row, column=5) assert abs(float(total_cell.value) - 1500.0) < 0.01 total_found = True assert total_found finally: _clear() engine.dispose() def test_ks3_export_does_not_modify(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with Session() as s: before_status = s.get(KS3, kid).status with TestClient(app) as client: client.get(f"/projects/{pid}/ks3/{kid}/export/excel") client.get(f"/projects/{pid}/ks3/{kid}/export/word") with Session() as s: assert s.get(KS3, kid).status == before_status finally: _clear() engine.dispose() def test_ks3_export_multiple_ks2(tmp_path): engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session, num_ks2=3) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active text = "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value) assert "№1" in text assert "№2" in text assert "№3" in text # Total = 3 * 1500 = 4500 total_found = False for row in ws.iter_rows(): for cell in row: if cell.value == "Итого:": total_cell = ws.cell(row=cell.row, column=5) assert abs(float(total_cell.value) - 4500.0) < 0.01 total_found = True assert total_found finally: _clear() engine.dispose() def test_ks3_export_no_foreign_ks2(tmp_path): """Only KS-2 linked to this KS-3 appear in the export.""" engine, Session = _make_session(tmp_path) _override(Session) try: pid, kid = _create_ks3(Session) with TestClient(app) as client: resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel") from openpyxl import load_workbook wb = load_workbook(io.BytesIO(resp.content)) ws = wb.active text = "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value) assert "Item 1" not in text # KS-2 item names not in KS-3 export finally: _clear() engine.dispose()