import sys import os import pytest from fastapi.testclient import TestClient # Add project root to sys.path sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from main import app client = TestClient(app) @pytest.fixture(scope="module") def client(): with TestClient(app) as c: yield c def test_read_root(client): response = client.get("/") assert response.status_code == 200 assert response.url.path == "/docs" def test_need_level_guardrail_high(client): """Test rule: Income < 1000 -> High Need""" payload = { "family_size": 4, "income_monthly": 900, "monthly_expenses": 3000, "debts": 0, "number_of_children": 2, "age": 35, "case_type": "Divorced", "housing_type": "Rental", "health_status": "Good", "city": "Cairo", "gender": "Female" } response = client.post("/api/ai/need-level", json=payload) assert response.status_code == 200 data = response.json() assert data["need_level"] == "High" assert data["method"] == "rule_based_guardrail" assert "score" in data assert data["score"] == 100.0 def test_need_level_guardrail_low(client): """Test rule: Income > 15000 & Debts < 1000 -> Low Need""" payload = { "family_size": 2, "income_monthly": 16000, "monthly_expenses": 5000, "debts": 500, "number_of_children": 0, "age": 40, "case_type": "Married", "housing_type": "Owned", "health_status": "Good", "city": "Cairo", "gender": "Male" } response = client.post("/api/ai/need-level", json=payload) assert response.status_code == 200 data = response.json() assert data["need_level"] == "Low" assert data["method"] == "rule_based_guardrail" assert data["score"] == 0.0 def test_assistance_type_medical(client): """Test rule: Health Status = Chronic Disease -> Medical""" payload = { "family_size": 4, "income_monthly": 2000, "monthly_expenses": 3000, "debts": 0, "number_of_children": 2, "age": 35, "case_type": "Divorced", "housing_type": "Rental", "health_status": "Chronic Disease", "city": "Cairo", "gender": "Female" } response = client.post("/api/ai/assistance-type", json=payload) assert response.status_code == 200 data = response.json() assert data["assistance_type"] == "Medical" def test_ml_inference_path(client): """Test case that bypasses guardrails to hit the ML model""" payload = { "family_size": 4, "income_monthly": 5000, # Between 1000 and 15000 "monthly_expenses": 3000, "debts": 0, "number_of_children": 2, "age": 35, "case_type": "Married", "housing_type": "Rental", "health_status": "Good", "city": "Cairo", "gender": "Male" } response = client.post("/api/ai/need-level", json=payload) assert response.status_code == 200 data = response.json() # We should get a valid score and a method indicating ML model or at least not guardrail # Note: method might be "ml_model_rf_v1" or "fallback_mock" depending on if model loaded # but strictly it shouldn't represent an error. assert "score" in data assert data["method"] != "rule_based_guardrail"