Spaces:
Sleeping
Sleeping
File size: 9,979 Bytes
6c31d92 2fad98d 6c31d92 2fad98d 6c31d92 2fad98d 6c31d92 2fad98d 6c31d92 2fad98d 6c31d92 2fad98d 6c31d92 | 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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 | """
Test script for Trips API endpoints.
Tests trip start functionality with JWT authentication.
"""
import requests
import time
from generate_test_token import generate_test_token
# Configuration
BASE_URL = "http://localhost:8003"
TRIPS_ENDPOINT = f"{BASE_URL}/tracker/trips"
# Test data
TEST_MERCHANT_ID = "550e8400-e29b-41d4-a716-446655440000"
TEST_USER_ID = "660e8400-e29b-41d4-a716-446655440001"
# Bangkok coordinates
TEST_LOCATION = {
"latitude": 13.7563,
"longitude": 100.5018
}
def test_start_trip():
"""Test starting a new trip"""
print("\n" + "="*60)
print("TEST: Start Trip")
print("="*60)
# Generate JWT token
token = generate_test_token(
user_id=TEST_USER_ID,
merchant_id=TEST_MERCHANT_ID
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Prepare request
current_time = int(time.time() * 1000)
payload = {
"startedAt": current_time,
"startLocation": TEST_LOCATION
}
print(f"\nπ Starting trip at: {TEST_LOCATION}")
print(f"β° Timestamp: {current_time}")
# Make request
response = requests.post(
f"{TRIPS_ENDPOINT}/start",
json=payload,
headers=headers
)
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 201:
print("\nβ
Trip started successfully!")
trip_id = response.json().get("tripId")
print(f"π Trip ID: {trip_id}")
return trip_id, current_time
elif response.status_code == 409:
print("\nβ οΈ Active trip already exists")
return None, None
else:
print(f"\nβ Failed to start trip")
return None, None
def test_start_trip_duplicate():
"""Test starting a trip when one is already active"""
print("\n" + "="*60)
print("TEST: Start Trip (Duplicate - Should Fail)")
print("="*60)
# Generate JWT token
token = generate_test_token(
user_id=TEST_USER_ID,
merchant_id=TEST_MERCHANT_ID
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Prepare request
current_time = int(time.time() * 1000)
payload = {
"startedAt": current_time,
"startLocation": TEST_LOCATION
}
print(f"\nπ Attempting to start another trip...")
# Make request
response = requests.post(
f"{TRIPS_ENDPOINT}/start",
json=payload,
headers=headers
)
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 409:
print("\nβ
Correctly rejected duplicate trip!")
else:
print(f"\nβ οΈ Unexpected response")
def test_start_trip_invalid_location():
"""Test starting a trip with invalid coordinates"""
print("\n" + "="*60)
print("TEST: Start Trip (Invalid Location - Should Fail)")
print("="*60)
# Generate JWT token
token = generate_test_token(
user_id=TEST_USER_ID,
merchant_id=TEST_MERCHANT_ID
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Invalid latitude (> 90)
current_time = int(time.time() * 1000)
payload = {
"startedAt": current_time,
"startLocation": {
"latitude": 95.0, # Invalid
"longitude": 100.5018
}
}
print(f"\nπ Attempting with invalid latitude: 95.0")
# Make request
response = requests.post(
f"{TRIPS_ENDPOINT}/start",
json=payload,
headers=headers
)
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 422:
print("\nβ
Correctly rejected invalid coordinates!")
else:
print(f"\nβ οΈ Unexpected response")
def test_start_trip_no_auth():
"""Test starting a trip without authentication"""
print("\n" + "="*60)
print("TEST: Start Trip (No Auth - Should Fail)")
print("="*60)
# No authorization header
headers = {
"Content-Type": "application/json"
}
current_time = int(time.time() * 1000)
payload = {
"startedAt": current_time,
"startLocation": TEST_LOCATION
}
print(f"\nπ Attempting without JWT token...")
# Make request
response = requests.post(
f"{TRIPS_ENDPOINT}/start",
json=payload,
headers=headers
)
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 401:
print("\nβ
Correctly rejected unauthorized request!")
else:
print(f"\nβ οΈ Unexpected response")
def test_stop_trip(trip_id, start_time):
"""Test stopping an active trip"""
print("\n" + "="*60)
print("TEST: Stop Trip")
print("="*60)
if not trip_id:
print("\nβ οΈ No active trip to stop")
return False
# Generate JWT token
token = generate_test_token(
user_id=TEST_USER_ID,
merchant_id=TEST_MERCHANT_ID
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
# Prepare request (simulate 15km trip over 30 minutes)
current_time = int(time.time() * 1000)
payload = {
"tripId": trip_id,
"stoppedAt": current_time,
"distanceMeters": 15000, # 15km
"endLocation": {
"latitude": 13.7600, # Slightly different location
"longitude": 100.5100
}
}
print(f"\nπ Trip ID: {trip_id}")
print(f"π End location: {payload['endLocation']}")
print(f"π Distance: {payload['distanceMeters']} meters")
print(f"β° Stop timestamp: {current_time}")
# Make request
response = requests.post(
f"{TRIPS_ENDPOINT}/stop",
json=payload,
headers=headers
)
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 200:
print("\nβ
Trip stopped successfully!")
result = response.json()
print(f"π Distance: {result.get('distanceMeters')} meters")
print(f"β±οΈ Duration: {result.get('durationMinutes')} minutes")
return True
else:
print(f"\nβ Failed to stop trip")
return False
def test_stop_trip_duplicate(trip_id):
"""Test stopping an already stopped trip"""
print("\n" + "="*60)
print("TEST: Stop Trip (Duplicate - Should Fail)")
print("="*60)
if not trip_id:
print("\nβ οΈ No trip ID provided")
return
# Generate JWT token
token = generate_test_token(
user_id=TEST_USER_ID,
merchant_id=TEST_MERCHANT_ID
)
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
current_time = int(time.time() * 1000)
payload = {
"tripId": trip_id,
"stoppedAt": current_time,
"distanceMeters": 15000,
"endLocation": {
"latitude": 13.7600,
"longitude": 100.5100
}
}
print(f"\nπ Attempting to stop already stopped trip: {trip_id}")
# Make request
response = requests.post(
f"{TRIPS_ENDPOINT}/stop",
json=payload,
headers=headers
)
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 400:
print("\nβ
Correctly rejected duplicate stop!")
else:
print(f"\nβ οΈ Unexpected response")
def test_health_check():
"""Test trip service health check"""
print("\n" + "="*60)
print("TEST: Health Check")
print("="*60)
response = requests.get(f"{TRIPS_ENDPOINT}/health")
print(f"\nπ Status Code: {response.status_code}")
print(f"π Response: {response.json()}")
if response.status_code == 200:
print("\nβ
Service is healthy!")
else:
print(f"\nβ Service health check failed")
def main():
"""Run all tests"""
print("\n" + "="*60)
print("π TRIPS API TEST SUITE")
print("="*60)
print(f"Base URL: {BASE_URL}")
print(f"Merchant ID: {TEST_MERCHANT_ID}")
print(f"User ID: {TEST_USER_ID}")
try:
# Test 1: Health check
test_health_check()
# Test 2: Start trip (should succeed)
trip_id, start_time = test_start_trip()
# Test 3: Try to start another trip (should fail with 409)
if trip_id:
test_start_trip_duplicate()
# Test 4: Invalid location (should fail with 422)
test_start_trip_invalid_location()
# Test 5: No authentication (should fail with 401)
test_start_trip_no_auth()
# Test 6: Stop trip (should succeed)
if trip_id:
# Wait 2 seconds to ensure duration > 0
print("\nβ³ Waiting 2 seconds before stopping trip...")
time.sleep(2)
stopped = test_stop_trip(trip_id, start_time)
# Test 7: Try to stop again (should fail with 400)
if stopped:
test_stop_trip_duplicate(trip_id)
print("\n" + "="*60)
print("β
ALL TESTS COMPLETED")
print("="*60)
except requests.exceptions.ConnectionError:
print("\nβ ERROR: Could not connect to server")
print(f"Make sure the server is running at {BASE_URL}")
except Exception as e:
print(f"\nβ ERROR: {str(e)}")
if __name__ == "__main__":
main()
|