-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_test.py
More file actions
627 lines (543 loc) · 24 KB
/
backend_test.py
File metadata and controls
627 lines (543 loc) · 24 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
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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
#!/usr/bin/env python3
import requests
import sys
import json
from datetime import datetime
class LezzetAPITester:
def __init__(self, base_url="https://food-delivery-app-152.preview.emergentagent.com/api"):
self.base_url = base_url
self.token = None
self.user_id = None
self.tests_run = 0
self.tests_passed = 0
self.test_results = []
def log_test_result(self, name, success, details=""):
"""Log test result for reporting"""
self.test_results.append({
"name": name,
"success": success,
"details": details,
"timestamp": datetime.now().isoformat()
})
def run_test(self, name, method, endpoint, expected_status, data=None, auth_required=False):
"""Run a single API test"""
url = f"{self.base_url}/{endpoint}"
headers = {'Content-Type': 'application/json'}
if auth_required and self.token:
headers['Authorization'] = f'Bearer {self.token}'
self.tests_run += 1
print(f"\n🔍 Testing {name}...")
try:
if method == 'GET':
response = requests.get(url, headers=headers, timeout=30)
elif method == 'POST':
response = requests.post(url, json=data, headers=headers, timeout=30)
elif method == 'DELETE':
response = requests.delete(url, headers=headers, timeout=30)
success = response.status_code == expected_status
if success:
self.tests_passed += 1
print(f"✅ Passed - Status: {response.status_code}")
try:
response_data = response.json() if response.text else {}
self.log_test_result(name, True, f"Status: {response.status_code}")
return True, response_data
except:
self.log_test_result(name, True, f"Status: {response.status_code} (no JSON)")
return True, {}
else:
print(f"❌ Failed - Expected {expected_status}, got {response.status_code}")
try:
error_details = response.json() if response.text else {"error": "No response body"}
print(f" Response: {error_details}")
self.log_test_result(name, False, f"Expected {expected_status}, got {response.status_code}: {error_details}")
except:
self.log_test_result(name, False, f"Expected {expected_status}, got {response.status_code}")
return False, {}
except requests.exceptions.RequestException as e:
print(f"❌ Failed - Network Error: {str(e)}")
self.log_test_result(name, False, f"Network Error: {str(e)}")
return False, {}
except Exception as e:
print(f"❌ Failed - Error: {str(e)}")
self.log_test_result(name, False, f"Error: {str(e)}")
return False, {}
def test_health_check(self):
"""Test basic API health"""
success, response = self.run_test("API Health Check", "GET", "", 200)
return success
def test_seed_data(self):
"""Seed demo data if needed"""
print("\n📦 Seeding demo data...")
success, response = self.run_test("Seed Demo Data", "POST", "seed", 200)
return success
def test_user_registration(self):
"""Test user registration"""
timestamp = datetime.now().strftime('%H%M%S')
test_user = {
"email": f"test_user_{timestamp}@lezzet.com",
"password": "TestPass123!",
"name": f"Test User {timestamp}",
"phone": f"+90555{timestamp}",
"role": "customer"
}
success, response = self.run_test(
"User Registration",
"POST",
"auth/register",
200,
test_user
)
if success and 'access_token' in response:
self.token = response['access_token']
self.user_id = response['user']['user_id']
print(f" ✅ Token obtained: {self.token[:20]}...")
return True
return False
def test_user_login(self):
"""Test user login with existing credentials"""
if not self.token: # Only test login if we don't have a token from registration
login_data = {
"email": "admin@lezzet.com",
"password": "admin123"
}
success, response = self.run_test(
"User Login",
"POST",
"auth/login",
200,
login_data
)
if success and 'access_token' in response:
self.token = response['access_token']
self.user_id = response['user']['user_id']
print(f" ✅ Login token obtained: {self.token[:20]}...")
return True
return False
return True
def test_get_current_user(self):
"""Test getting current user info"""
if not self.token:
print(" ⚠️ Skipping - No authentication token")
return False
success, response = self.run_test(
"Get Current User",
"GET",
"auth/me",
200,
auth_required=True
)
return success
def test_get_restaurants(self):
"""Test fetching restaurants"""
success, response = self.run_test(
"Get Restaurants",
"GET",
"restaurants",
200
)
if success and isinstance(response, list) and len(response) > 0:
print(f" ✅ Found {len(response)} restaurants")
self.test_restaurant_id = response[0].get('restaurant_id')
return True
elif success and isinstance(response, list) and len(response) == 0:
print(" ⚠️ No restaurants found, may need to seed data")
return True
return success
def test_get_restaurant_detail(self):
"""Test fetching specific restaurant details"""
if not hasattr(self, 'test_restaurant_id') or not self.test_restaurant_id:
# Try to get restaurants first to find an ID
restaurants_success, restaurants = self.run_test("Get Restaurants for Detail Test", "GET", "restaurants", 200)
if not restaurants_success or not restaurants or len(restaurants) == 0:
print(" ⚠️ Skipping - No restaurants available for detail test")
return False
self.test_restaurant_id = restaurants[0].get('restaurant_id')
success, response = self.run_test(
"Get Restaurant Detail",
"GET",
f"restaurants/{self.test_restaurant_id}",
200
)
if success:
print(f" ✅ Restaurant details loaded for: {response.get('name', 'Unknown')}")
return success
def test_favorites_functionality(self):
"""Test adding and removing favorites"""
if not self.token:
print(" ⚠️ Skipping - No authentication token")
return False
if not hasattr(self, 'test_restaurant_id') or not self.test_restaurant_id:
print(" ⚠️ Skipping - No restaurant ID available for favorites test")
return False
# Add to favorites
add_success, _ = self.run_test(
"Add Restaurant to Favorites",
"POST",
f"users/favorites/{self.test_restaurant_id}",
200,
auth_required=True
)
# Get favorites list
get_success, favorites = self.run_test(
"Get User Favorites",
"GET",
"users/favorites",
200,
auth_required=True
)
# Remove from favorites
remove_success, _ = self.run_test(
"Remove Restaurant from Favorites",
"DELETE",
f"users/favorites/{self.test_restaurant_id}",
200,
auth_required=True
)
return add_success and get_success and remove_success
def test_order_creation(self):
"""Test creating an order"""
if not self.token:
print(" ⚠️ Skipping - No authentication token")
return False
if not hasattr(self, 'test_restaurant_id'):
print(" ⚠️ Skipping - No restaurant ID available for order test")
return False
# Get restaurant details to find menu items
success, restaurant = self.run_test(
"Get Restaurant for Order Test",
"GET",
f"restaurants/{self.test_restaurant_id}",
200
)
if not success or not restaurant.get('menu') or len(restaurant['menu']) == 0:
print(" ⚠️ Skipping - No menu items available for order test")
return False
# Create order with first menu item
menu_item = restaurant['menu'][0]
order_data = {
"restaurant_id": self.test_restaurant_id,
"items": [{
"item_id": menu_item['item_id'],
"name": menu_item['name'],
"quantity": 1,
"price": menu_item['price']
}],
"delivery_address": {
"street": "Test Street 123",
"city": "Istanbul",
"district": "Kadikoy"
},
"payment_method": "cash",
"notes": "Test order"
}
success, response = self.run_test(
"Create Order",
"POST",
"orders",
200,
order_data,
auth_required=True
)
if success:
print(f" ✅ Order created with ID: {response.get('order_id', 'Unknown')}")
return success
def test_get_user_orders(self):
"""Test fetching user orders"""
if not self.token:
print(" ⚠️ Skipping - No authentication token")
return False
success, response = self.run_test(
"Get User Orders",
"GET",
"orders",
200,
auth_required=True
)
if success:
order_count = len(response) if isinstance(response, list) else 0
print(f" ✅ Found {order_count} orders for user")
return success
def test_admin_login(self):
"""Test admin login with Muhammed1974 password"""
admin_data = {
"password": "Muhammed1974"
}
success, response = self.run_test(
"Admin Login",
"POST",
"auth/admin/login",
200,
admin_data
)
if success and 'access_token' in response:
self.admin_token = response['access_token']
self.admin_user = response['user']
print(f" ✅ Admin token obtained: {self.admin_token[:20]}...")
print(f" ✅ Admin role: {self.admin_user.get('role', 'Unknown')}")
return True
return False
def test_admin_dashboard(self):
"""Test admin dashboard statistics"""
if not hasattr(self, 'admin_token') or not self.admin_token:
print(" ⚠️ Skipping - No admin token")
return False
success, response = self.run_test(
"Get Admin Dashboard",
"GET",
"superadmin/dashboard",
200,
auth_required=False # We'll manually add auth header
)
# Override the auth for admin token
url = f"{self.base_url}/superadmin/dashboard"
headers = {'Authorization': f'Bearer {self.admin_token}'}
try:
response_req = requests.get(url, headers=headers, timeout=30)
if response_req.status_code == 200:
data = response_req.json()
print(f" ✅ Dashboard loaded with stats:")
stats = data.get('stats', {})
print(f" Total Users: {stats.get('total_users', 0)}")
print(f" Total Restaurants: {stats.get('total_restaurants', 0)}")
print(f" Orders Today: {stats.get('orders_today', 0)}")
print(f" Revenue Today: {stats.get('revenue_today', 0)}")
return True
else:
print(f" ❌ Dashboard failed: {response_req.status_code}")
return False
except Exception as e:
print(f" ❌ Dashboard error: {str(e)}")
return False
def test_admin_restaurant_management(self):
"""Test admin restaurant creation and deletion"""
if not hasattr(self, 'admin_token') or not self.admin_token:
print(" ⚠️ Skipping - No admin token")
return False
# Test creating restaurant
restaurant_data = {
"name": "Test Admin Restaurant",
"name_ar": "مطعم اختبار الادمن",
"description": "Test restaurant created by admin",
"description_ar": "مطعم تجريبي تم إنشاؤه من قبل الإدارة",
"address": "Test Address Damascus",
"phone": "+963911123456",
"email": "test@restaurant.com",
"cuisine_types": ["Syrian", "Traditional"],
"delivery_fee": 15.0,
"min_order": 50.0
}
url = f"{self.base_url}/superadmin/restaurants"
headers = {
'Authorization': f'Bearer {self.admin_token}',
'Content-Type': 'application/json'
}
try:
# Create restaurant
response = requests.post(url, json=restaurant_data, headers=headers, timeout=30)
if response.status_code == 200:
result = response.json()
restaurant_id = result.get('restaurant_id')
print(f" ✅ Restaurant created with ID: {restaurant_id}")
# Test deleting the created restaurant
delete_url = f"{self.base_url}/superadmin/restaurants/{restaurant_id}"
delete_response = requests.delete(delete_url, headers=headers, timeout=30)
if delete_response.status_code == 200:
print(f" ✅ Restaurant deleted successfully")
return True
else:
print(f" ❌ Failed to delete restaurant: {delete_response.status_code}")
return False
else:
print(f" ❌ Restaurant creation failed: {response.status_code}")
try:
error_data = response.json()
print(f" Error: {error_data}")
except:
print(f" Raw response: {response.text}")
return False
except Exception as e:
print(f" ❌ Restaurant management error: {str(e)}")
return False
def test_email_verification_system(self):
"""Test email verification system"""
# Create a user that needs verification
timestamp = datetime.now().strftime('%H%M%S%f')[:10] # More unique timestamp
test_user = {
"email": f"verify_test_{timestamp}@example.com",
"password": "TestPass123!",
"name": f"Verify Test User {timestamp}",
"phone": f"+90555{timestamp}",
"role": "customer"
}
success, response = self.run_test(
"User Registration with Verification",
"POST",
"auth/register",
200,
test_user
)
if success and response.get('requires_verification'):
verification_code = response.get('verification_code')
print(f" ✅ Registration requires verification, code: {verification_code}")
# Test email verification
verify_data = {
"email": test_user["email"],
"code": verification_code
}
verify_success, verify_response = self.run_test(
"Email Verification",
"POST",
"auth/verify-email",
200,
verify_data
)
if verify_success:
print(f" ✅ Email verification successful")
return True
else:
print(f" ❌ Email verification failed")
return False
else:
print(f" ❌ Registration should require verification")
return False
def test_app_settings(self):
"""Test app settings (app_name changing)"""
if not hasattr(self, 'admin_token') or not self.admin_token:
print(" ⚠️ Skipping - No admin token")
return False
headers = {'Authorization': f'Bearer {self.admin_token}'}
# Get current settings
get_url = f"{self.base_url}/superadmin/settings"
try:
get_response = requests.get(get_url, headers=headers, timeout=30)
if get_response.status_code == 200:
current_settings = get_response.json()
original_app_name = current_settings.get('app_name', 'Lezzet')
print(f" ✅ Current app name: {original_app_name}")
# Test changing app name
new_settings = {
"app_name": "مطعم لذيذ", # Arabic name
"default_currency": "SYP",
"default_country": "syria"
}
put_response = requests.put(get_url, json=new_settings, headers=headers, timeout=30)
if put_response.status_code == 200:
print(f" ✅ App settings updated successfully")
# Verify the change
verify_response = requests.get(get_url, headers=headers, timeout=30)
if verify_response.status_code == 200:
updated_settings = verify_response.json()
if updated_settings.get('app_name') == "مطعم لذيذ":
print(f" ✅ App name change verified: {updated_settings.get('app_name')}")
# Restore original name
restore_settings = {"app_name": original_app_name}
requests.put(get_url, json=restore_settings, headers=headers, timeout=30)
return True
return False
else:
print(f" ❌ Settings update failed: {put_response.status_code}")
return False
else:
print(f" ❌ Failed to get settings: {get_response.status_code}")
return False
except Exception as e:
print(f" ❌ Settings test error: {str(e)}")
return False
def test_panel_management(self):
"""Test panel hiding/showing functionality"""
if not hasattr(self, 'admin_token') or not self.admin_token:
print(" ⚠️ Skipping - No admin token")
return False
headers = {'Authorization': f'Bearer {self.admin_token}'}
# Get panels list
panels_url = f"{self.base_url}/superadmin/panels"
try:
get_response = requests.get(panels_url, headers=headers, timeout=30)
if get_response.status_code == 200:
panels = get_response.json()
print(f" ✅ Found {len(panels)} panels")
if panels:
# Test toggling the first panel
first_panel = panels[0]
panel_id = first_panel['id']
original_hidden = first_panel['hidden']
# Toggle panel
toggle_url = f"{self.base_url}/superadmin/panels/{panel_id}/toggle"
toggle_response = requests.put(toggle_url, headers=headers, timeout=30)
if toggle_response.status_code == 200:
print(f" ✅ Panel {panel_id} toggled successfully")
# Verify toggle worked
verify_response = requests.get(panels_url, headers=headers, timeout=30)
if verify_response.status_code == 200:
updated_panels = verify_response.json()
updated_panel = next((p for p in updated_panels if p['id'] == panel_id), None)
if updated_panel and updated_panel['hidden'] != original_hidden:
print(f" ✅ Panel visibility changed: {not original_hidden} -> {updated_panel['hidden']}")
# Toggle back to original state
requests.put(toggle_url, headers=headers, timeout=30)
return True
return False
else:
print(f" ❌ Panel toggle failed: {toggle_response.status_code}")
return False
else:
print(f" ⚠️ No panels found to test")
return True
else:
print(f" ❌ Failed to get panels: {get_response.status_code}")
return False
except Exception as e:
print(f" ❌ Panel management error: {str(e)}")
return False
def run_all_tests(self):
"""Run all tests in sequence"""
print("🚀 Starting Lezzet API Tests...")
print(f"🔗 Base URL: {self.base_url}")
# Test sequence
tests = [
("API Health Check", self.test_health_check),
("Seed Demo Data", self.test_seed_data),
("User Registration", self.test_user_registration),
("Get Current User", self.test_get_current_user),
("Get Restaurants", self.test_get_restaurants),
("Get Restaurant Detail", self.test_get_restaurant_detail),
("Favorites Functionality", self.test_favorites_functionality),
("Create Order", self.test_order_creation),
("Get User Orders", self.test_get_user_orders),
# New admin features tests
("Admin Login", self.test_admin_login),
("Admin Dashboard", self.test_admin_dashboard),
("Admin Restaurant Management", self.test_admin_restaurant_management),
("Email Verification System", self.test_email_verification_system),
("App Settings Management", self.test_app_settings),
("Panel Management", self.test_panel_management),
]
for test_name, test_func in tests:
try:
test_func()
except Exception as e:
print(f"❌ {test_name} failed with exception: {str(e)}")
self.log_test_result(test_name, False, f"Exception: {str(e)}")
# Print final results
success_rate = (self.tests_passed / self.tests_run * 100) if self.tests_run > 0 else 0
print(f"\n📊 Test Results:")
print(f" Total Tests: {self.tests_run}")
print(f" Passed: {self.tests_passed}")
print(f" Failed: {self.tests_run - self.tests_passed}")
print(f" Success Rate: {success_rate:.1f}%")
# Determine overall result
if success_rate >= 80:
print("🎉 Overall Result: PASS")
return 0
elif success_rate >= 50:
print("⚠️ Overall Result: PARTIAL")
return 1
else:
print("❌ Overall Result: FAIL")
return 2
def main():
tester = LezzetAPITester()
return tester.run_all_tests()
if __name__ == "__main__":
sys.exit(main())