File size: 1,469 Bytes
3a4ffcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from datetime import datetime
from typing import List

import pytest
from fastapi import HTTPException
from fastapi.testclient import TestClient

from app.main import app, _resolve_transactions
from app.schemas import InsightRequest, Transaction


def _txn() -> Transaction:
    return Transaction(
        timestamp=datetime.utcnow(),
        category="Travel",
        amount=100.0,
        currency="INR",
    )


def test_resolve_transactions_handles_payload_list(monkeypatch):
    payload = InsightRequest(user_id="abc", transactions=[_txn()])
    result = _resolve_transactions(payload)
    assert len(result) == 1


def test_resolve_transactions_requires_user_id_when_no_transactions():
    payload = InsightRequest(user_id=None, transactions=[])
    with pytest.raises(HTTPException):
        _resolve_transactions(payload)


def test_resolve_transactions_fetches_from_db(monkeypatch):
    payload = InsightRequest(user_id="6686280844fc8cbae596aa51", transactions=[])

    def fake_fetch(user_id: str) -> List[Transaction]:
        assert user_id == payload.user_id
        return [_txn()]

    monkeypatch.setattr("app.main.fetch_recent_transactions", fake_fetch)
    result = _resolve_transactions(payload)
    assert len(result) == 1


def test_insights_endpoint_requires_payload_when_empty(monkeypatch):
    client = TestClient(app)
    response = client.post("/insights", json={"user_id": None, "transactions": []})
    assert response.status_code == 400