File size: 2,407 Bytes
3dfe050
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
"""The API must refuse files that aren't bank statements with a clear 4xx, never
return a 200 with junk rows (which the web app would show as a 'successful' result)."""
from __future__ import annotations

import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))

from fastapi.testclient import TestClient  # noqa: E402
from reportlab.lib.pagesizes import A4  # noqa: E402
from reportlab.lib.styles import getSampleStyleSheet  # noqa: E402
from reportlab.platypus import Paragraph, SimpleDocTemplate, Table  # noqa: E402

import app.api.convert as convert_api  # noqa: E402
from app.main import app  # noqa: E402

FIXTURES = ROOT / "tests" / "fixtures"


def _post(client, path: Path):
    with open(path, "rb") as fh:
        return client.post("/convert", files={"file": (path.name, fh, "application/pdf")})


def _client(monkeypatch):
    monkeypatch.setattr(convert_api, "API_KEY", None)
    return TestClient(app)


def test_invoice_with_dated_table_is_rejected(tmp_path, monkeypatch):
    pdf = tmp_path / "invoice.pdf"
    styles = getSampleStyleSheet()
    SimpleDocTemplate(str(pdf), pagesize=A4).build([
        Paragraph("TAX INVOICE  Invoice No: 1042", styles["Title"]),
        Table([["Date", "Item", "Qty", "Amount"],
               ["01/05/2025", "Consulting", "2", "1,200.00"],
               ["03/05/2025", "Hosting", "1", "45.00"],
               ["", "", "Total", "1,245.00"]]),
    ])
    r = _post(_client(monkeypatch), pdf)
    assert r.status_code == 422
    assert "doesn't look like a bank statement" in r.json()["detail"]


def test_text_pdf_without_transactions_is_rejected(tmp_path, monkeypatch):
    pdf = tmp_path / "letter.pdf"
    SimpleDocTemplate(str(pdf), pagesize=A4).build(
        [Paragraph("Dear customer, thank you for your order.", getSampleStyleSheet()["Normal"])])
    r = _post(_client(monkeypatch), pdf)
    assert r.status_code == 422
    assert "doesn't look like a bank statement" in r.json()["detail"]


def test_not_a_pdf_is_rejected(tmp_path, monkeypatch):
    bad = tmp_path / "fake.pdf"
    bad.write_text("hello")
    r = _post(_client(monkeypatch), bad)
    assert r.status_code == 422


def test_real_statement_layout_still_converts(monkeypatch):
    r = _post(_client(monkeypatch), FIXTURES / "hard/t9_india_blank_dates.pdf")
    assert r.status_code == 200
    assert r.json()["count"] == 34