api: expand FastAPI surface for scenarios, networth, life-events, goals, simulate
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
Adds the read+write endpoints the frontend needs to drive a
ProjectionLab-style UX on top of the existing engine.
- /networth, /networth/history — NW total + per-account from
account_snapshot (frontend chart)
- /scenarios CRUD + projection — list/get/create/patch/delete user
scenarios; cartesian read-only
- /scenarios/{id}/life-events — life event CRUD nested under scenario
- /life-events/{id} — patch + delete by id
- /scenarios/{id}/goals,
/goals/{id} — retirement goal CRUD
- /simulate, /compare — sync, no-DB-write what-if endpoints
Auth: Bearer-token dependency on writes + simulate when API_BEARER_TOKEN
is set; reads always open (lock down via Authentik-fronted ingress in
prod). Existing /recompute keeps its bearer auth.
CORS middleware reads FRONTEND_ORIGINS (comma-separated) for the dev
SPA. Lifespan now provisions the SQLAlchemy engine + session_factory
on app.state and disposes them on shutdown.
40 new tests covering happy paths and validation. 172 tests total.
mypy strict + ruff clean (B008 ignore added — Depends() in defaults
is the canonical FastAPI pattern, not a bug).
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
31193faf08
commit
ee6ed1d3c4
15 changed files with 1570 additions and 74 deletions
151
tests/test_api_life_events_goals.py
Normal file
151
tests/test_api_life_events_goals.py
Normal file
|
|
@ -0,0 +1,151 @@
|
|||
"""Tests for /life-events and /goals."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
||||
|
||||
from fire_planner.api.dependencies import get_session
|
||||
from fire_planner.app import app
|
||||
from fire_planner.db import Scenario
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(engine: AsyncEngine,
|
||||
session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
async def _override() -> AsyncIterator[AsyncSession]:
|
||||
async with factory() as s:
|
||||
yield s
|
||||
|
||||
app.dependency_overrides[get_session] = _override
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||
yield ac
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
async def _seed_scenario(session: AsyncSession) -> int:
|
||||
scen = Scenario(
|
||||
external_id="user-host",
|
||||
kind="user",
|
||||
name="Host plan",
|
||||
jurisdiction="uk",
|
||||
strategy="trinity",
|
||||
leave_uk_year=0,
|
||||
glide_path="static",
|
||||
spending_gbp=Decimal("60000"),
|
||||
nw_seed_gbp=Decimal("1000000"),
|
||||
savings_per_year_gbp=Decimal("0"),
|
||||
config_json={},
|
||||
)
|
||||
session.add(scen)
|
||||
await session.commit()
|
||||
await session.refresh(scen)
|
||||
return scen.id
|
||||
|
||||
|
||||
# ── life events ──────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def test_create_and_list_life_events(client: AsyncClient, session: AsyncSession) -> None:
|
||||
sid = await _seed_scenario(session)
|
||||
create = await client.post(
|
||||
f"/scenarios/{sid}/life-events",
|
||||
json={
|
||||
"kind": "retirement",
|
||||
"name": "Retire at 50",
|
||||
"year_start": 15,
|
||||
"year_end": 15,
|
||||
},
|
||||
)
|
||||
assert create.status_code == 201, create.text
|
||||
listed = await client.get(f"/scenarios/{sid}/life-events")
|
||||
assert listed.status_code == 200
|
||||
body = listed.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["name"] == "Retire at 50"
|
||||
|
||||
|
||||
async def test_life_event_year_validation(client: AsyncClient, session: AsyncSession) -> None:
|
||||
sid = await _seed_scenario(session)
|
||||
resp = await client.post(
|
||||
f"/scenarios/{sid}/life-events",
|
||||
json={
|
||||
"kind": "expense_range",
|
||||
"name": "Bad range",
|
||||
"year_start": 20,
|
||||
"year_end": 5,
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
async def test_life_event_unknown_scenario(client: AsyncClient) -> None:
|
||||
resp = await client.get("/scenarios/9999/life-events")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
async def test_patch_life_event(client: AsyncClient, session: AsyncSession) -> None:
|
||||
sid = await _seed_scenario(session)
|
||||
create = await client.post(
|
||||
f"/scenarios/{sid}/life-events",
|
||||
json={"kind": "retirement", "name": "Retire", "year_start": 15},
|
||||
)
|
||||
eid = create.json()["id"]
|
||||
resp = await client.patch(f"/life-events/{eid}",
|
||||
json={"year_start": 20, "name": "Retire at 55"})
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["year_start"] == 20
|
||||
assert body["name"] == "Retire at 55"
|
||||
|
||||
|
||||
async def test_delete_life_event(client: AsyncClient, session: AsyncSession) -> None:
|
||||
sid = await _seed_scenario(session)
|
||||
create = await client.post(
|
||||
f"/scenarios/{sid}/life-events",
|
||||
json={"kind": "retirement", "name": "X", "year_start": 5},
|
||||
)
|
||||
eid = create.json()["id"]
|
||||
resp = await client.delete(f"/life-events/{eid}")
|
||||
assert resp.status_code == 204
|
||||
listed = await client.get(f"/scenarios/{sid}/life-events")
|
||||
assert listed.json() == []
|
||||
|
||||
|
||||
# ── goals ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
async def test_create_and_list_goals(client: AsyncClient, session: AsyncSession) -> None:
|
||||
sid = await _seed_scenario(session)
|
||||
create = await client.post(
|
||||
f"/scenarios/{sid}/goals",
|
||||
json={
|
||||
"kind": "target_nw",
|
||||
"name": "≥ £2M at 50",
|
||||
"target_amount_gbp": "2000000",
|
||||
"target_year": 15,
|
||||
"comparator": ">=",
|
||||
"success_threshold": "0.90",
|
||||
},
|
||||
)
|
||||
assert create.status_code == 201, create.text
|
||||
listed = await client.get(f"/scenarios/{sid}/goals")
|
||||
assert len(listed.json()) == 1
|
||||
assert Decimal(listed.json()[0]["target_amount_gbp"]) == Decimal("2000000")
|
||||
|
||||
|
||||
async def test_delete_goal(client: AsyncClient, session: AsyncSession) -> None:
|
||||
sid = await _seed_scenario(session)
|
||||
create = await client.post(
|
||||
f"/scenarios/{sid}/goals",
|
||||
json={"kind": "never_run_out", "name": "Last to 95", "target_year": 65},
|
||||
)
|
||||
gid = create.json()["id"]
|
||||
resp = await client.delete(f"/goals/{gid}")
|
||||
assert resp.status_code == 204
|
||||
122
tests/test_api_networth.py
Normal file
122
tests/test_api_networth.py
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
"""Tests for /networth and /networth/history."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
||||
|
||||
from fire_planner.api.dependencies import get_session
|
||||
from fire_planner.app import app
|
||||
from fire_planner.db import AccountSnapshot
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(engine: AsyncEngine,
|
||||
session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
async def _override() -> AsyncIterator[AsyncSession]:
|
||||
async with factory() as s:
|
||||
yield s
|
||||
|
||||
app.dependency_overrides[get_session] = _override
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||
yield ac
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
async def _seed_snapshots(session: AsyncSession) -> None:
|
||||
rows = [
|
||||
AccountSnapshot(
|
||||
external_id="wealthfolio:isa:2026-04-23",
|
||||
snapshot_date=date(2026, 4, 23),
|
||||
account_id="isa",
|
||||
account_name="ISA",
|
||||
account_type="ISA",
|
||||
currency="GBP",
|
||||
market_value=Decimal("280000"),
|
||||
market_value_gbp=Decimal("280000"),
|
||||
),
|
||||
AccountSnapshot(
|
||||
external_id="wealthfolio:schwab:2026-04-23",
|
||||
snapshot_date=date(2026, 4, 23),
|
||||
account_id="schwab",
|
||||
account_name="Schwab",
|
||||
account_type="BROKERAGE",
|
||||
currency="USD",
|
||||
market_value=Decimal("780000"),
|
||||
market_value_gbp=Decimal("615000"),
|
||||
),
|
||||
AccountSnapshot(
|
||||
external_id="wealthfolio:isa:2026-04-25",
|
||||
snapshot_date=date(2026, 4, 25),
|
||||
account_id="isa",
|
||||
account_name="ISA",
|
||||
account_type="ISA",
|
||||
currency="GBP",
|
||||
market_value=Decimal("300000"),
|
||||
market_value_gbp=Decimal("300000"),
|
||||
),
|
||||
AccountSnapshot(
|
||||
external_id="wealthfolio:schwab:2026-04-25",
|
||||
snapshot_date=date(2026, 4, 25),
|
||||
account_id="schwab",
|
||||
account_name="Schwab",
|
||||
account_type="BROKERAGE",
|
||||
currency="USD",
|
||||
market_value=Decimal("800000"),
|
||||
market_value_gbp=Decimal("640000"),
|
||||
),
|
||||
]
|
||||
for r in rows:
|
||||
session.add(r)
|
||||
await session.commit()
|
||||
|
||||
|
||||
async def test_get_networth_returns_latest(client: AsyncClient, session: AsyncSession) -> None:
|
||||
await _seed_snapshots(session)
|
||||
resp = await client.get("/networth")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["snapshot_date"] == "2026-04-25"
|
||||
assert Decimal(body["total_gbp"]) == Decimal("940000")
|
||||
by_id = {a["account_id"]: a for a in body["accounts"]}
|
||||
assert Decimal(by_id["isa"]["market_value_gbp"]) == Decimal("300000")
|
||||
assert Decimal(by_id["schwab"]["market_value_gbp"]) == Decimal("640000")
|
||||
|
||||
|
||||
async def test_get_networth_empty_when_no_snapshots(client: AsyncClient) -> None:
|
||||
resp = await client.get("/networth")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["accounts"] == []
|
||||
assert Decimal(body["total_gbp"]) == Decimal("0")
|
||||
|
||||
|
||||
async def test_networth_history_returns_per_date(client: AsyncClient,
|
||||
session: AsyncSession) -> None:
|
||||
await _seed_snapshots(session)
|
||||
resp = await client.get("/networth/history")
|
||||
assert resp.status_code == 200
|
||||
points = resp.json()["points"]
|
||||
assert len(points) == 2
|
||||
by_date = {p["snapshot_date"]: p for p in points}
|
||||
assert Decimal(by_date["2026-04-23"]["total_gbp"]) == Decimal("895000")
|
||||
assert Decimal(by_date["2026-04-25"]["total_gbp"]) == Decimal("940000")
|
||||
assert Decimal(by_date["2026-04-25"]["by_account"]["ISA"]) == Decimal("300000")
|
||||
|
||||
|
||||
async def test_networth_history_respects_days_filter(
|
||||
client: AsyncClient,
|
||||
session: AsyncSession,
|
||||
) -> None:
|
||||
await _seed_snapshots(session)
|
||||
resp = await client.get("/networth/history?days=1")
|
||||
assert resp.status_code == 200
|
||||
# days=1 ⇒ only the latest 1 distinct date
|
||||
assert len(resp.json()["points"]) == 1
|
||||
232
tests/test_api_scenarios.py
Normal file
232
tests/test_api_scenarios.py
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
"""Tests for /scenarios CRUD + projection."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from datetime import UTC, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
||||
|
||||
from fire_planner.api.dependencies import get_session
|
||||
from fire_planner.app import app
|
||||
from fire_planner.db import McRun, ProjectionYearly, Scenario
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(engine: AsyncEngine,
|
||||
session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
async def _override() -> AsyncIterator[AsyncSession]:
|
||||
async with factory() as s:
|
||||
yield s
|
||||
|
||||
app.dependency_overrides[get_session] = _override
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||
yield ac
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
async def _seed(session: AsyncSession) -> Scenario:
|
||||
scen = Scenario(
|
||||
external_id="cyprus-vpw-leave-y3-glide-rising",
|
||||
kind="cartesian",
|
||||
jurisdiction="cyprus",
|
||||
strategy="vpw",
|
||||
leave_uk_year=3,
|
||||
glide_path="rising",
|
||||
spending_gbp=Decimal("60000"),
|
||||
nw_seed_gbp=Decimal("1500000"),
|
||||
savings_per_year_gbp=Decimal("0"),
|
||||
config_json={"horizon_years": 60},
|
||||
)
|
||||
session.add(scen)
|
||||
await session.commit()
|
||||
await session.refresh(scen)
|
||||
return scen
|
||||
|
||||
|
||||
async def test_list_scenarios_empty(client: AsyncClient) -> None:
|
||||
resp = await client.get("/scenarios")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
async def test_list_and_filter_by_kind(client: AsyncClient, session: AsyncSession) -> None:
|
||||
base = await _seed(session)
|
||||
user = Scenario(
|
||||
external_id="user-abc",
|
||||
kind="user",
|
||||
name="My plan",
|
||||
parent_scenario_id=base.id,
|
||||
jurisdiction="cyprus",
|
||||
strategy="vpw",
|
||||
leave_uk_year=3,
|
||||
glide_path="rising",
|
||||
spending_gbp=Decimal("80000"),
|
||||
nw_seed_gbp=Decimal("1500000"),
|
||||
savings_per_year_gbp=Decimal("0"),
|
||||
config_json={},
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
|
||||
all_resp = await client.get("/scenarios")
|
||||
assert len(all_resp.json()) == 2
|
||||
|
||||
user_resp = await client.get("/scenarios?kind=user")
|
||||
assert len(user_resp.json()) == 1
|
||||
assert user_resp.json()[0]["name"] == "My plan"
|
||||
|
||||
|
||||
async def test_get_scenario(client: AsyncClient, session: AsyncSession) -> None:
|
||||
scen = await _seed(session)
|
||||
resp = await client.get(f"/scenarios/{scen.id}")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json()["jurisdiction"] == "cyprus"
|
||||
|
||||
|
||||
async def test_get_scenario_404(client: AsyncClient) -> None:
|
||||
resp = await client.get("/scenarios/9999")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
async def test_create_user_scenario(client: AsyncClient) -> None:
|
||||
resp = await client.post(
|
||||
"/scenarios",
|
||||
json={
|
||||
"name": "Aggressive FIRE",
|
||||
"description": "Cyprus, lower spend",
|
||||
"jurisdiction": "cyprus",
|
||||
"strategy": "vpw",
|
||||
"leave_uk_year": 2,
|
||||
"glide_path": "rising",
|
||||
"spending_gbp": "50000",
|
||||
"horizon_years": 60,
|
||||
"nw_seed_gbp": "1500000",
|
||||
"savings_per_year_gbp": "0",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 201, resp.text
|
||||
body = resp.json()
|
||||
assert body["kind"] == "user"
|
||||
assert body["name"] == "Aggressive FIRE"
|
||||
assert body["external_id"].startswith("user-")
|
||||
|
||||
|
||||
async def test_create_with_invalid_parent_id(client: AsyncClient) -> None:
|
||||
resp = await client.post(
|
||||
"/scenarios",
|
||||
json={
|
||||
"name": "X",
|
||||
"parent_scenario_id": 9999,
|
||||
"jurisdiction": "uk",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1000000",
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
async def test_patch_user_scenario(client: AsyncClient) -> None:
|
||||
create = await client.post("/scenarios",
|
||||
json={
|
||||
"name": "Plan A",
|
||||
"jurisdiction": "uk",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1000000",
|
||||
})
|
||||
sid = create.json()["id"]
|
||||
resp = await client.patch(f"/scenarios/{sid}", json={"name": "Plan A v2", "leave_uk_year": 2})
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["name"] == "Plan A v2"
|
||||
assert body["leave_uk_year"] == 2
|
||||
|
||||
|
||||
async def test_patch_cartesian_blocked(client: AsyncClient, session: AsyncSession) -> None:
|
||||
cart = await _seed(session)
|
||||
resp = await client.patch(f"/scenarios/{cart.id}", json={"name": "Renamed"})
|
||||
assert resp.status_code == 400
|
||||
assert "cartesian" in resp.json()["detail"]
|
||||
|
||||
|
||||
async def test_delete_user_scenario(client: AsyncClient) -> None:
|
||||
create = await client.post("/scenarios",
|
||||
json={
|
||||
"name": "Throwaway",
|
||||
"jurisdiction": "uk",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1000000",
|
||||
})
|
||||
sid = create.json()["id"]
|
||||
resp = await client.delete(f"/scenarios/{sid}")
|
||||
assert resp.status_code == 204
|
||||
assert (await client.get(f"/scenarios/{sid}")).status_code == 404
|
||||
|
||||
|
||||
async def test_delete_cartesian_blocked(client: AsyncClient, session: AsyncSession) -> None:
|
||||
cart = await _seed(session)
|
||||
resp = await client.delete(f"/scenarios/{cart.id}")
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
async def test_projection_404_when_no_run(client: AsyncClient, session: AsyncSession) -> None:
|
||||
scen = await _seed(session)
|
||||
resp = await client.get(f"/scenarios/{scen.id}/projection")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
async def test_projection_returns_yearly_series(client: AsyncClient,
|
||||
session: AsyncSession) -> None:
|
||||
scen = await _seed(session)
|
||||
run = McRun(
|
||||
scenario_id=scen.id,
|
||||
run_at=datetime(2026, 5, 1, tzinfo=UTC),
|
||||
n_paths=1000,
|
||||
seed=42,
|
||||
success_rate=Decimal("0.9050"),
|
||||
p10_ending_gbp=Decimal("100000"),
|
||||
p50_ending_gbp=Decimal("3000000"),
|
||||
p90_ending_gbp=Decimal("9000000"),
|
||||
median_lifetime_tax_gbp=Decimal("750000"),
|
||||
elapsed_seconds=Decimal("12.500"),
|
||||
)
|
||||
session.add(run)
|
||||
await session.commit()
|
||||
await session.refresh(run)
|
||||
for y in range(5):
|
||||
session.add(
|
||||
ProjectionYearly(
|
||||
mc_run_id=run.id,
|
||||
year_idx=y,
|
||||
p10_portfolio_gbp=Decimal("900000"),
|
||||
p25_portfolio_gbp=Decimal("950000"),
|
||||
p50_portfolio_gbp=Decimal("1000000"),
|
||||
p75_portfolio_gbp=Decimal("1100000"),
|
||||
p90_portfolio_gbp=Decimal("1200000"),
|
||||
p50_withdrawal_gbp=Decimal("60000"),
|
||||
p50_tax_gbp=Decimal("8000"),
|
||||
survival_rate=Decimal("1.0"),
|
||||
))
|
||||
await session.commit()
|
||||
|
||||
resp = await client.get(f"/scenarios/{scen.id}/projection")
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["scenario_id"] == scen.id
|
||||
assert body["n_paths"] == 1000
|
||||
assert len(body["yearly"]) == 5
|
||||
assert Decimal(body["yearly"][0]["p50_portfolio_gbp"]) == Decimal("1000000")
|
||||
131
tests/test_api_simulate.py
Normal file
131
tests/test_api_simulate.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
"""Smoke-tests for /simulate and /compare.
|
||||
|
||||
Uses very small n_paths (100) to keep tests fast — accuracy isn't the
|
||||
point, the point is the endpoint produces a valid response shape.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import AsyncIterator
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest_asyncio
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
|
||||
|
||||
from fire_planner.api.dependencies import get_session
|
||||
from fire_planner.app import app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def client(engine: AsyncEngine,
|
||||
session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
factory = async_sessionmaker(engine, expire_on_commit=False)
|
||||
|
||||
async def _override() -> AsyncIterator[AsyncSession]:
|
||||
async with factory() as s:
|
||||
yield s
|
||||
|
||||
app.dependency_overrides[get_session] = _override
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test", timeout=30) as ac:
|
||||
yield ac
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
async def test_simulate_runs_and_returns_yearly_fan(client: AsyncClient) -> None:
|
||||
resp = await client.post(
|
||||
"/simulate",
|
||||
json={
|
||||
"jurisdiction": "uk",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static_60_40",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1500000",
|
||||
"horizon_years": 30,
|
||||
"n_paths": 100,
|
||||
"seed": 42,
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
body = resp.json()
|
||||
assert "success_rate" in body
|
||||
assert len(body["yearly"]) == 30
|
||||
yp = body["yearly"][0]
|
||||
# Quantiles must be monotone non-decreasing
|
||||
p10, p25, p50, p75, p90 = (
|
||||
Decimal(yp[k])
|
||||
for k in ("p10_portfolio_gbp", "p25_portfolio_gbp", "p50_portfolio_gbp",
|
||||
"p75_portfolio_gbp", "p90_portfolio_gbp"))
|
||||
assert p10 <= p25 <= p50 <= p75 <= p90
|
||||
|
||||
|
||||
async def test_simulate_validates_unknown_jurisdiction(client: AsyncClient) -> None:
|
||||
resp = await client.post(
|
||||
"/simulate",
|
||||
json={
|
||||
"jurisdiction": "atlantis",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static_60_40",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1000000",
|
||||
"horizon_years": 10,
|
||||
"n_paths": 100,
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 400
|
||||
|
||||
|
||||
async def test_compare_runs_two_scenarios(client: AsyncClient) -> None:
|
||||
resp = await client.post(
|
||||
"/compare",
|
||||
json={
|
||||
"scenarios": [
|
||||
{
|
||||
"jurisdiction": "uk",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static_60_40",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1500000",
|
||||
"horizon_years": 20,
|
||||
"n_paths": 100,
|
||||
"seed": 42,
|
||||
},
|
||||
{
|
||||
"jurisdiction": "cyprus",
|
||||
"strategy": "guyton_klinger",
|
||||
"leave_uk_year": 2,
|
||||
"glide_path": "rising",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1500000",
|
||||
"horizon_years": 20,
|
||||
"n_paths": 100,
|
||||
"seed": 42,
|
||||
},
|
||||
]
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
results = resp.json()["results"]
|
||||
assert len(results) == 2
|
||||
assert all(len(r["yearly"]) == 20 for r in results)
|
||||
|
||||
|
||||
async def test_compare_rejects_single_scenario(client: AsyncClient) -> None:
|
||||
resp = await client.post(
|
||||
"/compare",
|
||||
json={
|
||||
"scenarios": [{
|
||||
"jurisdiction": "uk",
|
||||
"strategy": "trinity",
|
||||
"leave_uk_year": 0,
|
||||
"glide_path": "static_60_40",
|
||||
"spending_gbp": "60000",
|
||||
"nw_seed_gbp": "1500000",
|
||||
"n_paths": 100,
|
||||
}]
|
||||
},
|
||||
)
|
||||
assert resp.status_code == 422 # pydantic validation
|
||||
Loading…
Add table
Add a link
Reference in a new issue