Spaces:
Sleeping
Sleeping
File size: 9,897 Bytes
7466735 |
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 |
"""
Test Database API Integration
Tests the connection to https://aadarshsenapati.in/api/api.php
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from backend.database_api import DatabaseAPI, transform_parking_lots_for_ai
from datetime import datetime, timedelta
import json
def test_database_connection():
"""Test basic database connectivity"""
print("\n" + "=" * 70)
print("DATABASE API CONNECTION TEST")
print("=" * 70)
api = DatabaseAPI()
# Test 1: Get parking lots and slots
print("\n1οΈβ£ Testing: Get Available Parking Slots")
print("-" * 70)
result = api.get_all_available_slots()
if result['status'] == 'success':
slots = result.get('data', [])
total_lots = result.get('total_lots', 0)
print(f"β
SUCCESS: Found {len(slots)} available slots from {total_lots} parking lot(s)")
if slots:
print(f"\nπ Sample Parking Slot:")
sample = slots[0]
print(f" Slot ID: {sample.get('slot_id')}")
print(f" Slot Number: {sample.get('slot_number')}")
print(f" Lot Name: {sample.get('lot_name')}")
print(f" Location: {sample.get('lot_address')}")
print(f" Coordinates: ({sample.get('lot_latitude')}, {sample.get('lot_longitude')})")
print(f" Vehicle Type: {sample.get('vehicle_type')}")
print(f" Price/Hour: βΉ{sample.get('hourly_rate')}")
# Test data transformation
print(f"\nπ Transforming data for AI model...")
transformed = transform_parking_lots_for_ai(slots)
print(f"β
Transformed {len(transformed)} slots")
print(f"\nπ Transformed Sample:")
t_sample = transformed[0]
print(f" Slot ID: {t_sample['slot_id']}")
print(f" DB Slot ID: {t_sample.get('db_slot_id')}")
print(f" Coordinates: ({t_sample['latitude']}, {t_sample['longitude']})")
print(f" Proximity Score: {t_sample['proximity_score']}")
print(f" Popularity Score: {t_sample['popularity_score']}")
print(f" Price Factor: {t_sample['price_factor']}")
print(f" Price/Hour: βΉ{t_sample['price_per_hour']}")
else:
print(f"β FAILED: {result.get('message')}")
return api
def test_user_registration(api):
"""Test user registration"""
print("\n2οΈβ£ Testing: User Registration")
print("-" * 70)
test_user = {
"name": "Test User AI",
"phone": "+919999888877",
"email": "aitest@smartparking.com"
}
result = api.register_user(**test_user)
if result['status'] == 'success':
print(f"β
SUCCESS: {result.get('message')}")
print(f" Name: {test_user['name']}")
print(f" Phone: {test_user['phone']}")
else:
print(f"β FAILED: {result.get('message')}")
return result['status'] == 'success'
def test_booking_flow(api):
"""Test complete booking flow"""
print("\n3οΈβ£ Testing: Booking Flow")
print("-" * 70)
# Get available slots first
slots_result = api.get_all_available_slots()
if slots_result['status'] != 'success' or not slots_result.get('data'):
print("β Cannot test booking: No available slots")
return False
# Use first available slot
slot = slots_result['data'][0]
slot_db_id = slot.get('slot_id') or slot.get('id') or 1
slot_number = slot.get('slot_number', 'Unknown')
lot_name = slot.get('lot_name', 'Unknown')
# Create booking
start_time = datetime.now()
end_time = start_time + timedelta(hours=2)
# Use user_id = 9 (known to exist in database)
# In production, this should be the authenticated user's ID
booking_data = {
"user_id": 9, # Using existing user ID from database
"slot_id": int(slot_db_id),
"start_time": start_time.strftime("%Y-%m-%d %H:%M:%S"),
"end_time": end_time.strftime("%Y-%m-%d %H:%M:%S"),
"total_amount": 120.0
}
print(f"\nπ Creating booking...")
print(f" Lot: {lot_name}")
print(f" Slot: {slot_number} (DB ID: {slot_db_id})")
print(f" Duration: 2 hours")
print(f" Amount: βΉ120")
print(f" User ID: 9 (existing user)")
result = api.book_slot(**booking_data)
if result['status'] == 'success':
booking_uid = result.get('booking_uid')
print(f"β
SUCCESS: Booking created")
print(f" Booking UID: {booking_uid}")
# Test getting booking status
print(f"\nπ Fetching booking status...")
status_result = api.get_booking_status(booking_uid)
if status_result['status'] == 'success':
booking = status_result.get('data', {})
print(f"β
Booking found:")
print(f" Status: {booking.get('status')}")
print(f" Payment Status: {booking.get('payment_status')}")
print(f" Amount: βΉ{booking.get('total_amount')}")
return booking_uid
else:
print(f"β FAILED: {result.get('message')}")
return None
def test_payment_update(api, booking_uid):
"""Test payment status update"""
if not booking_uid:
print("\nβοΈ Skipping payment test (no booking UID)")
return
print("\n4οΈβ£ Testing: Payment Update")
print("-" * 70)
payment_data = {
"booking_uid": booking_uid,
"payment_status": "Paid",
"transaction_id": f"txn_test_{booking_uid}",
"amount": 120.0
}
print(f"π³ Updating payment status to 'Paid'...")
result = api.update_payment(**payment_data)
if result['status'] == 'success':
print(f"β
SUCCESS: {result.get('message')}")
# Verify update
print(f"\nβ Verifying update...")
status_result = api.get_booking_status(booking_uid)
if status_result['status'] == 'success':
booking = status_result.get('data', {})
print(f" Payment Status: {booking.get('payment_status')}")
else:
print(f"β FAILED: {result.get('message')}")
def test_feedback_submission(api, booking_uid):
"""Test feedback submission"""
if not booking_uid:
print("\nβοΈ Skipping feedback test (no booking UID)")
return
print("\n5οΈβ£ Testing: Feedback Submission")
print("-" * 70)
# Get booking ID (not UID) first
status_result = api.get_booking_status(booking_uid)
if status_result['status'] != 'success':
print("β Cannot get booking details for feedback")
return
booking = status_result.get('data', {})
booking_id = booking.get('id')
user_id = booking.get('user_id', 1)
feedback_data = {
"user_id": user_id,
"booking_id": booking_id,
"rating": 5.0,
"comments": "Excellent parking spot! Very convenient location."
}
print(f"β Submitting feedback...")
print(f" Rating: {feedback_data['rating']}/5.0")
print(f" Comment: {feedback_data['comments']}")
result = api.add_feedback(**feedback_data)
if result['status'] == 'success':
print(f"β
SUCCESS: {result.get('message')}")
else:
print(f"β FAILED: {result.get('message')}")
def test_booking_cancellation(api, booking_uid):
"""Test booking cancellation"""
if not booking_uid:
print("\nβοΈ Skipping cancellation test (no booking UID)")
return
print("\n6οΈβ£ Testing: Booking Cancellation")
print("-" * 70)
print(f"β Cancelling booking {booking_uid}...")
result = api.cancel_booking(booking_uid)
if result['status'] == 'success':
print(f"β
SUCCESS: {result.get('message')}")
# Verify cancellation
status_result = api.get_booking_status(booking_uid)
if status_result['status'] == 'success':
booking = status_result.get('data', {})
print(f" Status: {booking.get('status')}")
else:
print(f"β FAILED: {result.get('message')}")
def main():
"""Run all database tests"""
print("\n" + "=" * 70)
print("π SMART PARKING - DATABASE API INTEGRATION TESTS")
print("=" * 70)
print(f"Database URL: https://aadarshsenapati.in/api/api.php")
print(f"Test Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
try:
# Initialize API
api = test_database_connection()
# Test user registration
test_user_registration(api)
# Test booking flow
booking_uid = test_booking_flow(api)
# Test payment update
test_payment_update(api, booking_uid)
# Test feedback
test_feedback_submission(api, booking_uid)
# Don't cancel in tests - keep the data
# test_booking_cancellation(api, booking_uid)
print("\n" + "=" * 70)
print("β
DATABASE API INTEGRATION TESTS COMPLETED")
print("=" * 70)
print("\nπ‘ Next Steps:")
print(" 1. Verify data in database")
print(" 2. Test AI recommendations with real data")
print(" 3. Integrate with payment system")
print(" 4. Deploy to production")
except Exception as e:
print(f"\nβ ERROR: {e}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()
|