nutrivision-ai / tests /test_api.py
NAVANEETH Y
Claude Opus 4.8
Update tests for the real 5-class food set (idli, rice, sambar, egg, dosa)
d8cbd01
Raw History Blame Contribute Delete
2.74 kB
"""Tests for the FastAPI backend (endpoints that do not need the ML stack)."""
import io
from PIL import Image
def _png_bytes(color=(200, 200, 200), size=(64, 64)) -> bytes:
buf = io.BytesIO()
Image.new("RGB", size, color).save(buf, "PNG")
return buf.getvalue()
def test_health(client):
resp = client.get("/health")
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "ok"
assert body["database"] == "sqlite"
def test_list_foods(client):
resp = client.get("/api/v1/foods")
assert resp.status_code == 200
foods = resp.json()
assert len(foods) == 5
assert {f["food_item"] for f in foods} >= {"idli", "rice", "sambar", "egg", "dosa"}
def test_compliance_standards(client):
resp = client.get("/api/v1/compliance-standards")
assert resp.status_code == 200
keys = {s["key"] for s in resp.json()}
assert {"primary", "upper_primary"} <= keys
def test_nutrition_analyze_endpoint(client):
payload = {
"detections": [
{"food_item": "rice", "confidence": 0.9},
{"food_item": "idli", "confidence": 0.9},
{"food_item": "sambar", "confidence": 0.9},
{"food_item": "egg", "confidence": 0.8},
{"food_item": "dosa", "confidence": 0.8},
],
"category": "primary",
}
resp = client.post("/api/v1/nutrition/analyze", json=payload)
assert resp.status_code == 200
body = resp.json()
assert body["compliance"]["status"] == "Compliant"
assert body["meal"]["totals"]["calories"] > 450
def test_nutrition_analyze_all_unknown_returns_422(client):
payload = {"detections": [{"food_item": "pizza", "confidence": 0.9}]}
resp = client.post("/api/v1/nutrition/analyze", json=payload)
assert resp.status_code == 422
def test_empty_history_and_stats(client):
assert client.get("/api/v1/history").json() == []
stats = client.get("/api/v1/stats").json()
assert stats["total_analyses"] == 0
def test_analyze_empty_file_returns_400(client):
resp = client.post(
"/api/v1/analyze",
files={"file": ("empty.png", io.BytesIO(b""), "image/png")},
)
assert resp.status_code == 400
def test_analyze_without_ml_returns_503(client):
"""Without ultralytics installed, /analyze should degrade to 503."""
resp = client.post(
"/api/v1/analyze",
files={"file": ("m.png", io.BytesIO(_png_bytes()), "image/png")},
data={"store": "false"},
)
# 503 when ML stack missing; 200 if a full environment is present.
assert resp.status_code in (503, 200)
def test_report_download_404_for_missing(client):
resp = client.get("/api/v1/reports/999999")
assert resp.status_code == 404