-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api_documentation.py
More file actions
293 lines (237 loc) · 10.6 KB
/
test_api_documentation.py
File metadata and controls
293 lines (237 loc) · 10.6 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
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
289
290
291
292
293
#!/usr/bin/env python3
"""
API Endpoint Testing and Documentation Generator
Executes all API endpoints with sample inputs and captures responses for documentation
"""
import json
import sys
import os
from datetime import date, timedelta
from typing import Dict, Any, List
# Add backend to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'backend'))
from fastapi.testclient import TestClient
from app.main import app
def format_json(data: Any) -> str:
"""Format JSON data for documentation"""
return json.dumps(data, indent=2, ensure_ascii=False)
def capture_endpoint_test(client: TestClient, method: str, endpoint: str,
payload: Dict = None, description: str = "") -> Dict[str, Any]:
"""Capture endpoint test with request and response"""
print(f"\n{'='*80}")
print(f"Testing: {method.upper()} {endpoint}")
print(f"Description: {description}")
print(f"{'='*80}")
# Make request
if method.upper() == "GET":
response = client.get(endpoint)
elif method.upper() == "POST":
response = client.post(endpoint, json=payload)
else:
raise ValueError(f"Unsupported method: {method}")
# Capture request details
request_info = {
"method": method.upper(),
"endpoint": endpoint,
"payload": payload if payload else None
}
# Capture response details
response_info = {
"status_code": response.status_code,
"headers": dict(response.headers),
"body": response.json() if response.headers.get("content-type", "").startswith("application/json") else response.text
}
# Print results
print(f"\n📝 REQUEST:")
print(f"Method: {request_info['method']}")
print(f"Endpoint: {request_info['endpoint']}")
if request_info['payload']:
print(f"Payload:\n{format_json(request_info['payload'])}")
print(f"\n📋 RESPONSE:")
print(f"Status Code: {response_info['status_code']}")
print(f"Content-Type: {response_info['headers'].get('content-type', 'N/A')}")
print(f"Response Body:\n{format_json(response_info['body'])}")
return {
"description": description,
"request": request_info,
"response": response_info
}
def run_comprehensive_api_tests():
"""Run comprehensive API tests and capture documentation"""
print("🚀 Starting Comprehensive API Endpoint Testing")
print("Capturing sample inputs and responses for documentation\n")
# Initialize test client
client = TestClient(app)
# Storage for all test results
test_results = []
# ==================================================================
# HEALTH AND BASIC ENDPOINTS
# ==================================================================
test_results.append(capture_endpoint_test(
client, "GET", "/",
description="Root endpoint - API welcome message and basic information"
))
test_results.append(capture_endpoint_test(
client, "GET", "/docs",
description="API documentation endpoint - OpenAPI/Swagger documentation"
))
# ==================================================================
# INDICATOR ENDPOINTS
# ==================================================================
test_results.append(capture_endpoint_test(
client, "GET", "/v1/indicators/paris",
description="Get current crowd intelligence indicator for Paris with all factors"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/indicators/tokyo?include_satellite_cv=true",
description="Get indicator for Tokyo with satellite computer vision analysis included"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/indicators/london?include_weather=true&include_events=true",
description="Get London indicator with weather and events factors included"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/indicators/invalid_location_123",
description="Error case: Get indicator for invalid location (should return 404)"
))
# ==================================================================
# PREDICTION ENDPOINTS
# ==================================================================
future_date = (date.today() + timedelta(days=30)).strftime("%Y-%m-%d")
prediction_payload = {
"prediction_date": future_date,
"travel_stage": "pre_travel",
"include_events": True,
"include_weather": True,
"include_seasonality": True
}
test_results.append(capture_endpoint_test(
client, "POST", "/v1/indicators/predict/paris",
payload=prediction_payload,
description="Predict future overcrowding for Paris with all factors included"
))
test_results.append(capture_endpoint_test(
client, "GET", f"/v1/indicators/london?prediction_date={future_date}",
description="Get future prediction for London using GET method with date parameter"
))
# Error cases for predictions
past_date = (date.today() - timedelta(days=30)).strftime("%Y-%m-%d")
past_prediction_payload = {
"prediction_date": past_date,
"travel_stage": "pre_travel"
}
test_results.append(capture_endpoint_test(
client, "POST", "/v1/indicators/predict/london",
payload=past_prediction_payload,
description="Error case: Prediction with past date (should return 400)"
))
invalid_stage_payload = {
"prediction_date": future_date,
"travel_stage": "invalid_stage"
}
test_results.append(capture_endpoint_test(
client, "POST", "/v1/indicators/predict/paris",
payload=invalid_stage_payload,
description="Error case: Prediction with invalid travel stage (should return 422)"
))
# ==================================================================
# MOBILE CONGESTION ENDPOINTS
# ==================================================================
test_results.append(capture_endpoint_test(
client, "GET", "/v1/api/mobile-congestion/tokyo",
description="Get mobile network congestion data for Tokyo"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/api/mobile-congestion/paris?radius_km=5.0&include_historical=true",
description="Get mobile congestion for Paris with 5km radius and historical data"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/api/mobile-congestion/london/crowd-estimate",
description="Get crowd density estimate from mobile data for London"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/api/mobile-congestion/paris/historical",
description="Get historical mobile congestion patterns for Paris"
))
test_results.append(capture_endpoint_test(
client, "GET", "/v1/api/mobile-congestion/coverage/towers?lat=48.8566&lon=2.3522",
description="Get cell tower coverage analysis for Paris coordinates"
))
# ==================================================================
# DESTINATION ENDPOINTS
# ==================================================================
test_results.append(capture_endpoint_test(
client, "GET", "/v1/destinations/popular",
description="Get list of popular tourist destinations supported by the API"
))
# ==================================================================
# TRAVEL BOOKING ENDPOINTS
# ==================================================================
test_results.append(capture_endpoint_test(
client, "GET", "/v1/travel-booking/paris",
description="Get travel booking pressure and insights for Paris"
))
future_check_date = (date.today() + timedelta(days=60)).strftime("%Y-%m-%d")
test_results.append(capture_endpoint_test(
client, "GET", f"/v1/travel-booking/london?check_date={future_check_date}",
description="Get travel booking data for London with specific future date"
))
# ==================================================================
# ERROR HANDLING ENDPOINTS
# ==================================================================
test_results.append(capture_endpoint_test(
client, "GET", "/v1/invalid/endpoint",
description="Error case: Invalid endpoint (should return 404)"
))
# Malformed JSON test
print(f"\n{'='*80}")
print(f"Testing: POST /v1/indicators/predict/paris")
print(f"Description: Error case: Malformed JSON payload (should return 422)")
print(f"{'='*80}")
response = client.post(
"/v1/indicators/predict/paris",
data="invalid json",
headers={"Content-Type": "application/json"}
)
print(f"\n📝 REQUEST:")
print(f"Method: POST")
print(f"Endpoint: /v1/indicators/predict/paris")
print(f"Payload: invalid json (malformed)")
print(f"Headers: Content-Type: application/json")
print(f"\n📋 RESPONSE:")
print(f"Status Code: {response.status_code}")
print(f"Content-Type: {response.headers.get('content-type', 'N/A')}")
print(f"Response Body:\n{format_json(response.json())}")
test_results.append({
"description": "Error case: Malformed JSON payload (should return 422)",
"request": {
"method": "POST",
"endpoint": "/v1/indicators/predict/paris",
"payload": "invalid json (malformed)",
"headers": {"Content-Type": "application/json"}
},
"response": {
"status_code": response.status_code,
"headers": dict(response.headers),
"body": response.json()
}
})
# Missing required fields test
test_results.append(capture_endpoint_test(
client, "POST", "/v1/indicators/predict/paris",
payload={},
description="Error case: Missing required fields in payload (should return 422)"
))
print(f"\n{'='*80}")
print(f"✅ COMPREHENSIVE API TESTING COMPLETED")
print(f"Total endpoints tested: {len(test_results)}")
print(f"{'='*80}")
return test_results
if __name__ == "__main__":
# Run the tests and capture results
results = run_comprehensive_api_tests()
# Save results to JSON file for further processing
with open("api_test_results.json", "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
print(f"\n📄 Test results saved to: api_test_results.json")
print(f"🎯 Ready for documentation generation!")