initial commit
This commit is contained in:
@@ -0,0 +1,199 @@
|
||||
from io import BytesIO
|
||||
import openpyxl
|
||||
import pytest
|
||||
|
||||
from app.models import Category, Department
|
||||
from app.seed.seed import seed_database
|
||||
|
||||
|
||||
@pytest.fixture(scope="module", autouse=True)
|
||||
def seeded_ai6_db(db, tmp_path_factory):
|
||||
upload_dir = tmp_path_factory.mktemp("ai6_test_uploads")
|
||||
seed_database(db, upload_dir=upload_dir)
|
||||
return upload_dir
|
||||
|
||||
|
||||
def _auth_headers(client, email: str) -> dict[str, str]:
|
||||
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
|
||||
assert res.status_code == 200, res.text
|
||||
return {"Authorization": f"Bearer {res.json()['access_token']}"}
|
||||
|
||||
|
||||
AI_GET_ENDPOINTS = [
|
||||
"/api/ai/status",
|
||||
"/api/ai/summary",
|
||||
"/api/ai/comparison",
|
||||
"/api/ai/depreciation",
|
||||
"/api/ai/efficiency",
|
||||
"/api/ai/breakdown-frequency",
|
||||
"/api/ai/suggestions",
|
||||
]
|
||||
|
||||
AI_EXPORT_SECTIONS = [
|
||||
"summary",
|
||||
"comparison",
|
||||
"depreciation",
|
||||
"efficiency",
|
||||
"breakdown-frequency",
|
||||
]
|
||||
|
||||
|
||||
def test_ai6_role_matrix_department_user_403_and_viewers_200(client):
|
||||
dept_hdr = _auth_headers(client, "dept@poona.demo")
|
||||
|
||||
# department_user must get 403 on EVERY /api/ai/* route
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=dept_hdr)
|
||||
assert r.status_code == 403, f"Expected 403 for department_user on {url}, got {r.status_code}"
|
||||
|
||||
for sec in AI_EXPORT_SECTIONS:
|
||||
r = client.get(f"/api/ai/{sec}/export?format=xlsx", headers=dept_hdr)
|
||||
assert r.status_code == 403
|
||||
r_csv = client.get(f"/api/ai/{sec}/export?format=csv", headers=dept_hdr)
|
||||
assert r_csv.status_code == 403
|
||||
|
||||
r_regen_dept = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "summary", "filters": {"period": "12m"}},
|
||||
headers=dept_hdr,
|
||||
)
|
||||
assert r_regen_dept.status_code == 403
|
||||
|
||||
# management, coordinator, biomedical get 200 on all GETs, 403 on regenerate
|
||||
for email in (
|
||||
"mgmt@poona.demo",
|
||||
"coord@poona.demo",
|
||||
"bio@poona.demo",
|
||||
):
|
||||
hdr = _auth_headers(client, email)
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=hdr)
|
||||
assert r.status_code == 200, f"Expected 200 for {email} on {url}, got {r.status_code}: {r.text}"
|
||||
r_regen = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "comparison", "filters": {"period": "12m"}},
|
||||
headers=hdr,
|
||||
)
|
||||
assert r_regen.status_code == 403, f"Expected 403 for {email} on regenerate"
|
||||
|
||||
# system_admin gets 200 on all GETs AND 200 on regenerate
|
||||
admin_hdr = _auth_headers(client, "admin@poona.demo")
|
||||
for url in AI_GET_ENDPOINTS:
|
||||
r = client.get(url, headers=admin_hdr)
|
||||
assert r.status_code == 200, f"Expected 200 for admin on {url}: {r.text}"
|
||||
|
||||
r_regen_admin = client.post(
|
||||
"/api/ai/narrative/regenerate",
|
||||
json={"section": "comparison", "filters": {"period": "12m"}},
|
||||
headers=admin_hdr,
|
||||
)
|
||||
assert r_regen_admin.status_code == 200, r_regen_admin.text
|
||||
regen_body = r_regen_admin.json()
|
||||
assert regen_body["section"] == "comparison"
|
||||
assert regen_body["narrative"]["source"] == "rule_based"
|
||||
assert regen_body["narrative"]["headline"]
|
||||
|
||||
|
||||
def test_ai6_scoping_department_category_and_custom_period(client, db):
|
||||
mgmt_hdr = _auth_headers(client, "mgmt@poona.demo")
|
||||
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||
cat = db.query(Category).first()
|
||||
assert icu is not None and cat is not None
|
||||
|
||||
r_dept = client.get(f"/api/ai/depreciation?period=6m&department_id={icu.id}", headers=mgmt_hdr)
|
||||
assert r_dept.status_code == 200, r_dept.text
|
||||
dep_body = r_dept.json()
|
||||
assert len(dep_body["rows"]) > 0
|
||||
assert all(row["department_name"] == icu.name for row in dep_body["rows"])
|
||||
|
||||
r_cat = client.get(f"/api/ai/breakdown-frequency?period=3m&category_id={cat.id}", headers=mgmt_hdr)
|
||||
assert r_cat.status_code == 200, r_cat.text
|
||||
bf_body = r_cat.json()
|
||||
assert all(row["category_name"] == cat.name for row in bf_body["rows"])
|
||||
|
||||
# Valid custom period
|
||||
r_custom = client.get(
|
||||
"/api/ai/efficiency?period=custom&date_from=2025-01-01&date_to=2025-12-31",
|
||||
headers=mgmt_hdr,
|
||||
)
|
||||
assert r_custom.status_code == 200, r_custom.text
|
||||
assert r_custom.json()["period_start"] == "2025-01-01"
|
||||
assert r_custom.json()["period_end"] == "2025-12-31"
|
||||
|
||||
# Inverted custom period -> 422
|
||||
r_bad = client.get(
|
||||
"/api/ai/efficiency?period=custom&date_from=2026-06-01&date_to=2026-01-01",
|
||||
headers=mgmt_hdr,
|
||||
)
|
||||
assert r_bad.status_code == 422
|
||||
|
||||
|
||||
def test_ai6_default_none_provider_shapes_and_real_seeded_data(client, monkeypatch):
|
||||
from app.core.config import settings
|
||||
monkeypatch.setattr(settings, "AI_PROVIDER", "none")
|
||||
admin_hdr = _auth_headers(client, "admin@poona.demo")
|
||||
|
||||
status_res = client.get("/api/ai/status", headers=admin_hdr)
|
||||
assert status_res.status_code == 200
|
||||
st = status_res.json()
|
||||
assert st["provider"] == "none"
|
||||
assert st["enabled"] is False
|
||||
assert st["reachable"] is False
|
||||
|
||||
summary = client.get("/api/ai/summary?period=12m", headers=admin_hdr).json()
|
||||
assert set(summary["sections"].keys()) == {
|
||||
"comparison",
|
||||
"depreciation",
|
||||
"efficiency",
|
||||
"breakdown_frequency",
|
||||
}
|
||||
assert summary["narrative"]["source"] == "rule_based"
|
||||
assert len(summary["suggestions"]) > 0
|
||||
|
||||
for ep in ("comparison", "depreciation", "efficiency", "breakdown-frequency"):
|
||||
body = client.get(f"/api/ai/{ep}?period=12m", headers=admin_hdr).json()
|
||||
for key in ("metrics", "rows", "chart_data", "narrative", "how_calculated"):
|
||||
assert key in body, f"Missing '{key}' in /api/ai/{ep}"
|
||||
assert body["narrative"]["source"] == "rule_based"
|
||||
assert len(body["metrics"]) > 0
|
||||
assert len(body["rows"]) > 0
|
||||
|
||||
cmp_body = client.get("/api/ai/comparison?period=12m", headers=admin_hdr).json()
|
||||
assert len(cmp_body["rows"]) == 10
|
||||
|
||||
sugs = client.get("/api/ai/suggestions?period=12m", headers=admin_hdr).json()["suggestions"]
|
||||
s1 = [s for s in sugs if s["rule"] == "S1"]
|
||||
s4 = [s for s in sugs if s["rule"] == "S4"]
|
||||
assert len(s1) >= 3
|
||||
assert len(s4) >= 2
|
||||
|
||||
|
||||
def test_ai6_exports_xlsx_three_sheets_and_csv(client):
|
||||
biomed_hdr = _auth_headers(client, "bio@poona.demo")
|
||||
|
||||
for sec in AI_EXPORT_SECTIONS:
|
||||
r_xlsx = client.get(f"/api/ai/{sec}/export?format=xlsx&period=12m", headers=biomed_hdr)
|
||||
assert r_xlsx.status_code == 200, f"XLSX export failed for {sec}: {r_xlsx.text}"
|
||||
assert "spreadsheetml" in r_xlsx.headers["content-type"]
|
||||
|
||||
wb = openpyxl.load_workbook(BytesIO(r_xlsx.content))
|
||||
assert len(wb.sheetnames) == 3, f"Expected 3 sheets for {sec}, got {wb.sheetnames}"
|
||||
assert wb.sheetnames[1] == "Evidence"
|
||||
assert wb.sheetnames[2] == "How calculated"
|
||||
assert len(wb.sheetnames[0]) <= 31
|
||||
|
||||
# Verify each sheet has header row (row 5) and at least one data row (row 6)
|
||||
for ws_name in wb.sheetnames:
|
||||
ws = wb[ws_name]
|
||||
assert ws.cell(row=5, column=1).value is not None, f"Missing header on {sec}/{ws_name}"
|
||||
assert ws.cell(row=6, column=1).value is not None, f"Missing data row on {sec}/{ws_name}"
|
||||
|
||||
r_csv = client.get(f"/api/ai/{sec}/export?format=csv&period=12m", headers=biomed_hdr)
|
||||
assert r_csv.status_code == 200, f"CSV export failed for {sec}: {r_csv.text}"
|
||||
assert "text/csv" in r_csv.headers["content-type"]
|
||||
assert len(r_csv.text.splitlines()) >= 5
|
||||
|
||||
# Unknown export section -> 404
|
||||
r_404 = client.get("/api/ai/nonexistent/export?format=xlsx", headers=biomed_hdr)
|
||||
assert r_404.status_code == 404
|
||||
|
||||
Reference in New Issue
Block a user