"""End-to-end API test on synthetic data (fast; isolated temp DB).""" from __future__ import annotations import os import tempfile # Point the app at an isolated temp data dir BEFORE importing the app/config/db. _TMP = tempfile.mkdtemp(prefix="ar_api_test_") os.environ["AR_DATA_DIR"] = _TMP from fastapi.testclient import TestClient # noqa: E402 from app.db.database import init_db # noqa: E402 from app.api.main import app # noqa: E402 from tests.test_excel_export import make_amazon_xlsx # noqa: E402 def test_full_api_flow(): init_db() synth = os.path.join(_TMP, "USA synthetic.xlsx") make_amazon_xlsx(synth, order_rows=20) with TestClient(app) as c: assert c.get("/api/health").json()["status"] == "ok" sid = c.post("/api/sessions", json={ "name": "test", "month_end_date": "2026-01-31", "clearing_lag_days": 2, }).json()["id"] with open(synth, "rb") as fh: up = c.post(f"/api/sessions/{sid}/files", files={"files": ("USA synthetic.xlsx", fh)}) assert up.status_code == 200 assert up.json()[0]["status"] == "parsed" c.put(f"/api/sessions/{sid}/reserves", json=[{"marketplace": "USA", "account_type": "Standard Orders", "amount": 0.0}]) assert c.post(f"/api/sessions/{sid}/process").status_code == 200 st = c.get(f"/api/sessions/{sid}/status").json() assert st["status"] == "processed", st summ = c.get(f"/api/sessions/{sid}/summary").json() assert summ["closing_receivable_usd"] == 2580.0 assert summ["num_settlements"] == 5 assert summ["num_receivable_settlements"] == 3 setts = {s["settlement_id"]: s for s in c.get(f"/api/sessions/{sid}/settlements").json()} assert setts["200"]["status"] == "receivable" assert setts["100"]["status"] == "paid" txns = c.get(f"/api/sessions/{sid}/transactions?receivable=true&limit=5").json() assert txns["total"] == 22 recon = c.get(f"/api/sessions/{sid}/reconciliation").json() assert recon["status"] == "Reconciled" assert abs(recon["identity_difference"]) <= 0.01 assert c.post(f"/api/sessions/{sid}/export").status_code == 200 dl = c.get(f"/api/sessions/{sid}/export/download") assert dl.status_code == 200 assert len(dl.content) > 5000 # a real xlsx workbook assert dl.content[:2] == b"PK" # zip/xlsx magic def test_invalid_file_rejected(): init_db() bad = os.path.join(_TMP, "bad.txt") with open(bad, "w") as f: f.write("not a spreadsheet") with TestClient(app) as c: sid = c.post("/api/sessions", json={"name": "bad", "month_end_date": "2026-01-31"}).json()["id"] with open(bad, "rb") as fh: r = c.post(f"/api/sessions/{sid}/files", files={"files": ("bad.txt", fh)}) assert r.status_code == 400 # unsupported extension