Spaces:
Sleeping
Sleeping
File size: 3,346 Bytes
3efedb0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
import unittest
import requests
import json
import os
import sys
import time
import threading
import uvicorn
# Add the src directory to the path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from src.api.main import app
class TestAPI(unittest.TestCase):
@classmethod
def setUpClass(cls):
"""Start the API server in a separate thread"""
cls.api_thread = threading.Thread(
target=uvicorn.run,
args=(app,),
kwargs={"host": "127.0.0.1", "port": 8000, "log_level": "error"},
daemon=True
)
cls.api_thread.start()
time.sleep(1) # Give the server time to start
def test_predict_endpoint(self):
"""Test the predict endpoint"""
# Create sample application data
application = {
"income": 50000,
"credit_score": 720,
"debt_to_income": 25,
"loan_amount": 200000,
"loan_term": 30,
"employment_length": 5,
"home_ownership": "OWN",
"loan_purpose": "HOME"
}
# Make request to predict endpoint
response = requests.post(
"http://127.0.0.1:8000/predict",
json=application
)
# Check response
self.assertEqual(response.status_code, 200)
# Parse response
result = response.json()
# Check that prediction is included
self.assertIn("prediction", result)
self.assertIn(result["prediction"], [0, 1])
# Check that probability is included
self.assertIn("probability", result)
self.assertTrue(0 <= result["probability"] <= 1)
# Check that explanation is included
self.assertIn("explanation", result)
self.assertIn("text", result["explanation"])
def test_what_if_endpoint(self):
"""Test the what-if endpoint"""
# Create sample application data
application = {
"income": 50000,
"credit_score": 720,
"debt_to_income": 25,
"loan_amount": 200000,
"loan_term": 30,
"employment_length": 5,
"home_ownership": "OWN",
"loan_purpose": "HOME"
}
# Make request to what-if endpoint
response = requests.post(
"http://127.0.0.1:8000/what-if",
json={
"application": application,
"feature": "income",
"values": [30000, 40000, 50000, 60000, 70000]
}
)
# Check response
self.assertEqual(response.status_code, 200)
# Parse response
result = response.json()
# Check that results are included
self.assertIn("results", result)
self.assertEqual(len(result["results"]), 5)
# Check that each result has value, prediction, and probability
for item in result["results"]:
self.assertIn("value", item)
self.assertIn("prediction", item)
self.assertIn("probability", item)
if __name__ == "__main__":
unittest.main() |