-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapiTest.py
More file actions
174 lines (148 loc) Β· 6.58 KB
/
apiTest.py
File metadata and controls
174 lines (148 loc) Β· 6.58 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
#!/usr/bin/env python3
"""
Quick API Test Script for PlacesFinder
A simplified test script for quick verification of API functionality.
Tests the most important endpoints with minimal setup.
Usage:
python quick_test.py
"""
import requests
import json
from datetime import datetime
# Configuration
API_BASE = "http://localhost:5000"
TEST_LOCATION = {
"latitude": 28.6139,
"longitude": 77.2090,
"timezone": "Asia/Kolkata",
"captured_at": datetime.now().isoformat() + "Z"
}
def test_endpoint(method, endpoint, data=None, description=""):
"""Test a single endpoint"""
url = f"{API_BASE}{endpoint}"
print(f"\nπ§ͺ Testing: {description}")
print(f" {method} {endpoint}")
# Determine timeout based on endpoint
timeout = 10 # Default for simple endpoints
if endpoint in ["/api/search", "/api/search/simple"]:
timeout = 120 # 2 minutes for search endpoints
elif endpoint == "/api/rank":
timeout = 60 # 1 minute for ranking
try:
print(f" β±οΈ Timeout: {timeout}s")
if method == "GET":
response = requests.get(url, timeout=timeout)
else:
response = requests.post(url, json=data, timeout=timeout)
result = response.json()
if response.status_code == 200 and result.get("success"):
print(f" β
SUCCESS - {result.get('message', 'OK')}")
return True, result
else:
print(f" β FAILED - {result.get('error', 'Unknown error')}")
print(f" π Response: {response.status_code} - {response.text[:200]}...")
return False, result
except requests.exceptions.Timeout as e:
print(f" β° TIMEOUT - Request took longer than {timeout}s")
print(f" π‘ This might be normal for search endpoints on first run")
return False, None
except requests.exceptions.ConnectionError as e:
print(f" π CONNECTION ERROR - {str(e)}")
return False, None
except Exception as e:
print(f" β ERROR - {str(e)}")
return False, None
def main():
print("π PlacesFinder API Quick Test")
print("=" * 40)
# Check if server is running
try:
response = requests.get(f"{API_BASE}/api/health", timeout=5)
if response.status_code != 200:
print("β Server not responding. Make sure Flask server is running:")
print(" python api_server.py")
return
except:
print("β Cannot connect to server. Make sure Flask server is running:")
print(" python api_server.py")
return
# Check environment variables by testing a simple search first
print("\nπ Checking API configuration...")
try:
# Try a very simple request to see if APIs are configured
simple_payload = {"query": "test", "location": TEST_LOCATION}
response = requests.post(f"{API_BASE}/api/search/simple", json=simple_payload, timeout=10)
if response.status_code == 500:
result = response.json()
if "API" in result.get("error", "").upper():
print("β οΈ API configuration issue detected:")
print(" Make sure your .env file contains:")
print(" - GROQ_API_KEY")
print(" - FOURSQUARE_API_KEY")
print(" - SERPAPI_KEY")
print(" Continuing with extended timeouts...")
except requests.exceptions.Timeout:
print("β οΈ Initial API check timed out - this is normal for first run")
except Exception as e:
print(f"β οΈ API configuration check failed: {str(e)}")
tests_passed = 0
total_tests = 0
# Test 1: Health Check
total_tests += 1
success, _ = test_endpoint("GET", "/api/health", description="Health Check")
if success:
tests_passed += 1
# Test 2: Save Location
total_tests += 1
success, _ = test_endpoint("POST", "/api/location/save", TEST_LOCATION, "Save Location")
if success:
tests_passed += 1
# Test 3: Get Cached Location
total_tests += 1
success, _ = test_endpoint("GET", "/api/location/cache", description="Get Cached Location")
if success:
tests_passed += 1
# Test 4: Simple Search
total_tests += 1
search_payload = {"query": "coffee shops", "location": TEST_LOCATION}
success, search_result = test_endpoint("POST", "/api/search/simple", search_payload, "Simple Search")
if success:
tests_passed += 1
# Show some results
if search_result and search_result.get("data"):
data = search_result["data"]
fs_count = data.get("foursquare", {}).get("count", 0)
gm_count = data.get("google", {}).get("count", 0)
print(f" π Found {fs_count} Foursquare + {gm_count} Google results")
# Test 5: Full Search with Ranking
total_tests += 1
search_payload = {"query": "restaurants near me", "location": TEST_LOCATION}
success, full_result = test_endpoint("POST", "/api/search", search_payload, "Full Search with AI Ranking")
if success:
tests_passed += 1
# Show ranking results
if full_result and full_result.get("data"):
ranked_places = full_result["data"].get("ranked_results", {}).get("ranked_places", [])
print(f" π Ranked {len(ranked_places)} places")
if ranked_places:
top_place = ranked_places[0]
print(f" π₯ Top result: {top_place.get('name', 'Unknown')}")
# Test 6: Standalone Ranking (if we have search data)
if search_result and search_result.get("data"):
total_tests += 1
success, _ = test_endpoint("POST", "/api/rank", search_result["data"], "Standalone Ranking")
if success:
tests_passed += 1
# Summary
print("\n" + "=" * 40)
print(f"π Test Summary: {tests_passed}/{total_tests} passed ({tests_passed/total_tests*100:.0f}%)")
if tests_passed == total_tests:
print("π All tests passed! Your API is working correctly.")
elif tests_passed > 0:
print("β οΈ Some tests failed. Check the output above for details.")
else:
print("β All tests failed. Check your server configuration.")
print("\nπ‘ To run more comprehensive tests, use:")
print(" python test_api_endpoints.py --verbose")
if __name__ == "__main__":
main()