-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_backend_api.py
More file actions
255 lines (220 loc) · 9.19 KB
/
test_backend_api.py
File metadata and controls
255 lines (220 loc) · 9.19 KB
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
"""
Test Backend API Endpoints with Intelligent Data Routing
Tests both short-term (Weather API) and long-term (Local Data) predictions
"""
import requests
import json
from datetime import datetime, timedelta
API_BASE_URL = 'http://127.0.0.1:8081'
def test_health_check():
"""Test if server is running"""
print("=" * 60)
print("🔍 Test 1: Health Check")
print("=" * 60)
try:
response = requests.get(f"{API_BASE_URL}/", timeout=5)
print(f"✅ Server is RUNNING")
print(f" Status Code: {response.status_code}")
return True
except requests.exceptions.ConnectionError:
print(f"❌ Server is NOT RUNNING")
print(f" Cannot connect to {API_BASE_URL}")
print(f"\n⚠️ Please start the backend server:")
print(f" Run: START_COMPLETE_SYSTEM.bat")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def test_current_weather():
"""Test current weather endpoint"""
print("\n" + "=" * 60)
print("🌤️ Test 2: Current Weather API")
print("=" * 60)
try:
params = {'lat': 23.2599, 'lon': 77.4126}
response = requests.get(f"{API_BASE_URL}/weather/current", params=params, timeout=10)
if response.status_code == 200:
data = response.json()
print(f"✅ Current Weather API Working!")
print(f"\n📊 Response Data:")
print(f" Temperature: {data.get('temperature', 'N/A')}°C")
print(f" Location: {data.get('location_name', 'N/A')}")
print(f" Humidity: {data.get('humidity', 'N/A')}%")
print(f" Wind Speed: {data.get('wind_speed', 'N/A')} m/s")
print(f" Clouds: {data.get('clouds', 'N/A')}%")
return True
else:
print(f"❌ Request Failed")
print(f" Status Code: {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def test_short_term_prediction():
"""Test prediction endpoint with near-term date (should use Weather API)"""
print("\n" + "=" * 60)
print("🤖 Test 3: Short-term Prediction (0-5 days - Weather API)")
print("=" * 60)
try:
# Use tomorrow's date
tomorrow = (datetime.now() + timedelta(days=1)).strftime('%Y-%m-%d')
payload = {
'latitude': 19.0760,
'longitude': 72.8777,
'date': tomorrow
}
print(f"📤 Testing Mumbai, India for {tomorrow}")
response = requests.post(f"{API_BASE_URL}/predict", json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
print(f"\n✅ Prediction API Working!")
print(f"\n📊 Response Data:")
print(f" Risk Level: {data.get('risk_level', 'N/A')}")
print(f" Data Source: {data.get('data_source', 'N/A')}")
if 'predictions' in data:
print(f"\n🎯 Predictions:")
for key, value in data['predictions'].items():
print(f" {key}: {value:.4f}")
return True
else:
print(f"❌ Request Failed")
print(f" Status Code: {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def test_long_term_prediction():
"""Test prediction endpoint with long-term date (should use Local Data)"""
print("\n" + "=" * 60)
print("🤖 Test 4: Long-term Prediction (6+ months - Local Data)")
print("=" * 60)
try:
# Use date 3 months from now
future_date = (datetime.now() + timedelta(days=90)).strftime('%Y-%m-%d')
payload = {
'latitude': 35.6762,
'longitude': 139.6503,
'date': future_date
}
print(f"📤 Testing Tokyo, Japan for {future_date}")
response = requests.post(f"{API_BASE_URL}/predict", json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
print(f"\n✅ Prediction API Working!")
print(f"\n📊 Response Data:")
print(f" Risk Level: {data.get('risk_level', 'N/A')}")
print(f" Data Source: {data.get('data_source', 'N/A')}")
if 'predictions' in data:
print(f"\n🎯 Predictions:")
for key, value in data['predictions'].items():
print(f" {key}: {value:.4f}")
return True
else:
print(f"❌ Request Failed")
print(f" Status Code: {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def test_forecast():
"""Test 6-month forecast endpoint"""
print("\n" + "=" * 60)
print("� Test 5: 6-Month Forecast")
print("=" * 60)
try:
payload = {
'latitude': 40.7128,
'longitude': -74.0060,
'months': 6
}
print(f"📤 Testing New York, USA for 6-month forecast")
response = requests.post(f"{API_BASE_URL}/forecast", json=payload, timeout=30)
if response.status_code == 200:
data = response.json()
print(f"\n✅ Forecast API Working!")
print(f"\n📊 Response Data:")
print(f" Continent: {data.get('metadata', {}).get('continent', 'N/A')}")
print(f" Hemisphere: {data.get('metadata', {}).get('hemisphere', 'N/A')}")
print(f" Months: {len(data.get('forecasts', []))}")
if data.get('forecasts'):
print(f"\n📅 First Month Forecast:")
first = data['forecasts'][0]
print(f" Month: {first.get('month', 'N/A')}")
print(f" Temp: {first.get('temperature', 'N/A')}°C")
print(f" Data Source: {first.get('data_source', 'N/A')}")
return True
else:
print(f"❌ Request Failed")
print(f" Status Code: {response.status_code}")
print(f" Response: {response.text}")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def test_cors():
"""Test CORS headers"""
print("\n" + "=" * 60)
print("🔒 Test 6: CORS Configuration")
print("=" * 60)
try:
response = requests.options(f"{API_BASE_URL}/weather/current", timeout=5)
headers = response.headers
print(f"✅ CORS Headers:")
print(f" Access-Control-Allow-Origin: {headers.get('Access-Control-Allow-Origin', 'NOT SET')}")
print(f" Access-Control-Allow-Methods: {headers.get('Access-Control-Allow-Methods', 'NOT SET')}")
print(f" Access-Control-Allow-Headers: {headers.get('Access-Control-Allow-Headers', 'NOT SET')}")
if headers.get('Access-Control-Allow-Origin') == '*':
print(f"\n✅ CORS is properly configured for frontend access")
return True
else:
print(f"\n⚠️ CORS may not be properly configured")
return False
except Exception as e:
print(f"❌ Error: {e}")
return False
def main():
print("\n" + "=" * 60)
print("🚀 BACKEND API TEST SUITE - INTELLIGENT DATA ROUTING")
print("=" * 60 + "\n")
results = []
# Test 1: Health Check
if not test_health_check():
print("\n" + "=" * 60)
print("⛔ Cannot proceed without backend server running")
print("=" * 60)
return
results.append(("Health Check", True))
# Test 2: Current Weather
results.append(("Current Weather", test_current_weather()))
# Test 3: Short-term Prediction (Weather API)
results.append(("Short-term Prediction (Weather API)", test_short_term_prediction()))
# Test 4: Long-term Prediction (Local Data)
results.append(("Long-term Prediction (Local Data)", test_long_term_prediction()))
# Test 5: 6-Month Forecast
results.append(("6-Month Forecast", test_forecast()))
# Test 6: CORS
results.append(("CORS Configuration", test_cors()))
# Summary
print("\n" + "=" * 60)
print("📋 TEST SUMMARY")
print("=" * 60)
passed = sum(1 for _, result in results if result)
total = len(results)
for test_name, result in results:
status = "✅ PASSED" if result else "❌ FAILED"
print(f" {test_name}: {status}")
print(f"\n📊 Results: {passed}/{total} tests passed")
if passed == total:
print("\n🎉 All tests passed! Backend is working correctly.")
print("\n📡 Data Routing Verified:")
print(" ✅ Short-term (0-5 days) → Weather API")
print(" ✅ Long-term (6+ months) → Local Climate Data")
print("\n You can now start the frontend with: npm run dev")
else:
print("\n⚠️ Some tests failed. Please check the backend configuration.")
print("=" * 60 + "\n")
if __name__ == "__main__":
main()