File size: 9,473 Bytes
2996c62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
"""
API Testing Script for DeepSight EWS
Test all endpoints locally or on Hugging Face Spaces
"""

import requests
import json
from typing import Optional

# Configuration
BASE_URL = "http://localhost:7860"  # Change to your Hugging Face Space URL after deployment
# Example: BASE_URL = "https://YOUR_USERNAME-deepsight-ews.hf.space"

class Colors:
    """ANSI color codes for terminal output"""
    GREEN = '\033[92m'
    RED = '\033[91m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    END = '\033[0m'


def print_test(name: str, passed: bool, details: Optional[str] = None):
    """Print test result with color"""
    status = f"{Colors.GREEN}βœ“ PASSED{Colors.END}" if passed else f"{Colors.RED}βœ— FAILED{Colors.END}"
    print(f"\n{Colors.BLUE}[TEST]{Colors.END} {name}")
    print(f"Status: {status}")
    if details:
        print(f"Details: {details}")


def test_health_check():
    """Test 1: Health check endpoint"""
    try:
        response = requests.get(f"{BASE_URL}/health", timeout=10)
        passed = response.status_code == 200
        data = response.json() if passed else None
        
        details = None
        if passed:
            model_loaded = data.get('model', {}).get('loaded', False)
            data_loaded = data.get('data', {}).get('loaded', False)
            details = f"Model loaded: {model_loaded}, Data loaded: {data_loaded}"
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("Health Check", passed, details)
        return passed
    except Exception as e:
        print_test("Health Check", False, f"Error: {str(e)}")
        return False


def test_root_endpoint():
    """Test 2: Root endpoint"""
    try:
        response = requests.get(f"{BASE_URL}/", timeout=10)
        passed = response.status_code == 200
        data = response.json() if passed else None
        
        details = None
        if passed:
            service = data.get('service', 'Unknown')
            status = data.get('status', 'Unknown')
            details = f"Service: {service}, Status: {status}"
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("Root Endpoint", passed, details)
        return passed
    except Exception as e:
        print_test("Root Endpoint", False, f"Error: {str(e)}")
        return False


def test_portfolio_summary():
    """Test 3: Portfolio summary endpoint"""
    try:
        response = requests.get(f"{BASE_URL}/api/portfolio/summary", timeout=10)
        passed = response.status_code == 200
        data = response.json() if passed else None
        
        details = None
        if passed:
            total_loans = data.get('total_active_loans', 0)
            high_risk = data.get('high_risk_alerts', 0)
            health_score = data.get('portfolio_health_score', 0)
            details = f"Total loans: {total_loans}, High risk: {high_risk}, Health: {health_score}"
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("Portfolio Summary", passed, details)
        return passed
    except Exception as e:
        print_test("Portfolio Summary", False, f"Error: {str(e)}")
        return False


def test_high_risk_alerts():
    """Test 4: High-risk alerts endpoint"""
    try:
        response = requests.get(f"{BASE_URL}/api/borrowers/alerts?limit=10", timeout=10)
        passed = response.status_code == 200
        data = response.json() if passed else None
        
        details = None
        if passed:
            num_alerts = len(data) if isinstance(data, list) else 0
            if num_alerts > 0:
                first_alert = data[0]
                pd = first_alert.get('probability_of_default', 0)
                details = f"Number of alerts: {num_alerts}, First PD: {pd:.4f}"
            else:
                details = "No alerts returned"
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("High-Risk Alerts", passed, details)
        return passed
    except Exception as e:
        print_test("High-Risk Alerts", False, f"Error: {str(e)}")
        return False


def test_borrower_explanation():
    """Test 5: Borrower explanation endpoint"""
    try:
        borrower_id = 0  # Test with borrower ID 0
        response = requests.get(f"{BASE_URL}/api/borrowers/{borrower_id}/explain", timeout=10)
        passed = response.status_code == 200
        data = response.json() if passed else None
        
        details = None
        if passed:
            pd = data.get('probability_of_default', 0)
            loan_amnt = data.get('structured_data', {}).get('loan_amnt', 0)
            details = f"Borrower {borrower_id}, PD: {pd:.4f}, Loan: ${loan_amnt}"
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("Borrower Explanation", passed, details)
        return passed
    except Exception as e:
        print_test("Borrower Explanation", False, f"Error: {str(e)}")
        return False


def test_prediction():
    """Test 6: Prediction endpoint"""
    try:
        payload = {
            "loan_amnt": 15000.0,
            "int_rate": 14.5,
            "dti": 22.5,
            "annual_inc": 65000.0,
            "installment": 425.0,
            "fico_score": 680,
            "open_acc": 12,
            "delinq_2yrs": 1
        }
        
        response = requests.post(
            f"{BASE_URL}/api/predict",
            json=payload,
            headers={"Content-Type": "application/json"},
            timeout=10
        )
        
        passed = response.status_code == 200
        data = response.json() if passed else None
        
        details = None
        if passed:
            pd = data.get('probability_of_default', 0)
            risk_category = data.get('risk_category', 'Unknown')
            details = f"PD: {pd:.4f}, Risk: {risk_category}"
        elif response.status_code == 503:
            details = "Model not loaded (503) - this is expected if model file is missing"
            passed = True  # Don't fail the test if model isn't loaded
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("Prediction Endpoint", passed, details)
        return passed
    except Exception as e:
        print_test("Prediction Endpoint", False, f"Error: {str(e)}")
        return False


def test_static_files():
    """Test 7: Static files accessibility"""
    try:
        response = requests.get(f"{BASE_URL}/static/shap_global_summary.png", timeout=10)
        passed = response.status_code == 200
        
        details = None
        if passed:
            content_type = response.headers.get('content-type', '')
            file_size = len(response.content)
            details = f"File size: {file_size} bytes, Type: {content_type}"
        else:
            details = f"Status code: {response.status_code}"
        
        print_test("Static Files", passed, details)
        return passed
    except Exception as e:
        print_test("Static Files", False, f"Error: {str(e)}")
        return False


def test_api_docs():
    """Test 8: API documentation accessibility"""
    try:
        response = requests.get(f"{BASE_URL}/docs", timeout=10)
        passed = response.status_code == 200
        
        details = "Swagger UI accessible" if passed else f"Status code: {response.status_code}"
        print_test("API Documentation", passed, details)
        return passed
    except Exception as e:
        print_test("API Documentation", False, f"Error: {str(e)}")
        return False


def run_all_tests():
    """Run all API tests"""
    print("=" * 60)
    print(f"{Colors.BLUE}DeepSight EWS API Testing{Colors.END}")
    print(f"Base URL: {BASE_URL}")
    print("=" * 60)
    
    tests = [
        test_root_endpoint,
        test_health_check,
        test_portfolio_summary,
        test_high_risk_alerts,
        test_borrower_explanation,
        test_prediction,
        test_static_files,
        test_api_docs,
    ]
    
    results = []
    for test in tests:
        try:
            result = test()
            results.append(result)
        except Exception as e:
            print(f"\n{Colors.RED}Unexpected error in test: {str(e)}{Colors.END}")
            results.append(False)
    
    # Summary
    print("\n" + "=" * 60)
    print(f"{Colors.BLUE}TEST SUMMARY{Colors.END}")
    print("=" * 60)
    
    total = len(results)
    passed = sum(results)
    failed = total - passed
    
    print(f"Total tests: {total}")
    print(f"{Colors.GREEN}Passed: {passed}{Colors.END}")
    if failed > 0:
        print(f"{Colors.RED}Failed: {failed}{Colors.END}")
    
    success_rate = (passed / total) * 100 if total > 0 else 0
    print(f"Success rate: {success_rate:.1f}%")
    
    if success_rate == 100:
        print(f"\n{Colors.GREEN}πŸŽ‰ All tests passed! API is fully functional.{Colors.END}")
    elif success_rate >= 75:
        print(f"\n{Colors.YELLOW}⚠ Most tests passed. Check failed tests above.{Colors.END}")
    else:
        print(f"\n{Colors.RED}❌ Multiple tests failed. Check configuration and logs.{Colors.END}")
    
    print("=" * 60)


if __name__ == "__main__":
    import sys
    
    # Allow custom base URL from command line
    if len(sys.argv) > 1:
        BASE_URL = sys.argv[1].rstrip('/')
        print(f"Using custom base URL: {BASE_URL}\n")
    
    run_all_tests()