bayesscenparams / backend /tests /test_api.py
Jingrui77's picture
deploy: sync BayesScenParams Agent (2026-05-17T16:01:00Z)
f8a3ca2
Raw
History Blame Contribute Delete
2.6 kB
"""Smoke tests for the FastAPI app."""
from __future__ import annotations
import json
from pathlib import Path
import pytest
from fastapi.testclient import TestClient
from app.main import create_app
SAMPLES_DIR = Path(__file__).resolve().parents[1] / "app" / "data_sources" / "samples"
@pytest.fixture(scope="module")
def client() -> TestClient:
return TestClient(create_app())
def test_health(client: TestClient):
r = client.get("/api/health")
assert r.status_code == 200
body = r.json()
assert body["status"] == "ok"
assert body["service"] == "bayesscenparams-backend"
def test_list_samples(client: TestClient):
r = client.get("/api/data/samples")
assert r.status_code == 200
body = r.json()
ids = {s["id"] for s in body}
assert ids == {"gdp", "climate", "population"}
for s in body:
assert s["n"] > 0
assert s["icon"]
def test_get_sample(client: TestClient):
r = client.get("/api/data/samples/gdp")
assert r.status_code == 200
body = r.json()
assert body["id"] == "gdp"
assert len(body["values"]) > 100
assert isinstance(body["values"][0], float)
def test_bayesian_compute(client: TestClient):
gdp = json.loads((SAMPLES_DIR / "sample-gdp.json").read_text())
payload = {
"data": gdp["values"],
"judgments": [0, 1, 2, 3, 4],
"R": 10.0,
}
r = client.post("/api/bayesian/compute", json=payload)
assert r.status_code == 200
body = r.json()
assert "prior" in body and "likelihood" in body and "posterior" in body
assert len(body["posterior"]["weights"]) == 5
assert abs(sum(body["posterior"]["weights"]) - 1.0) < 1e-9
# likelihood for level 4 is R^2 = 100
assert body["likelihood"]["weights"][4] == pytest.approx(100.0)
def test_bayesian_compute_validates_R():
client = TestClient(create_app())
gdp = json.loads((SAMPLES_DIR / "sample-gdp.json").read_text())
r = client.post(
"/api/bayesian/compute",
json={"data": gdp["values"], "judgments": [0, 1, 2, 3, 4], "R": 0.5},
)
assert r.status_code == 422
def test_sensitivity(client: TestClient):
gdp = json.loads((SAMPLES_DIR / "sample-gdp.json").read_text())
r = client.post(
"/api/bayesian/sensitivity",
json={"data": gdp["values"], "judgments": [0, 1, 2, 3, 4]},
)
assert r.status_code == 200
body = r.json()
assert len(body["points"]) == 5
# Each point's posterior sums to 1
for p in body["points"]:
s = sum(p["result"]["posterior"]["weights"])
assert abs(s - 1.0) < 1e-9