-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_test.py
More file actions
401 lines (328 loc) Β· 16.2 KB
/
backend_test.py
File metadata and controls
401 lines (328 loc) Β· 16.2 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
#!/usr/bin/env python3
import requests
import sys
import json
import time
from datetime import datetime
from typing import Dict, Any
class NexusBuyAPITester:
def __init__(self, base_url: str = "https://nexus-buy.preview.emergentagent.com"):
self.base_url = base_url.rstrip('/')
self.buyer_token = None
self.seller_token = None
self.buyer_data = None
self.seller_data = None
self.tests_run = 0
self.tests_passed = 0
self.failed_tests = []
def run_test(self, name: str, method: str, endpoint: str, expected_status: int,
data: Dict = None, token: str = None, params: Dict = None) -> tuple:
"""Run a single API test"""
url = f"{self.base_url}/api/{endpoint}" if not endpoint.startswith('/') else f"{self.base_url}{endpoint}"
headers = {'Content-Type': 'application/json'}
if token:
headers['Authorization'] = f'Bearer {token}'
self.tests_run += 1
print(f"\nπ Testing {name}...")
print(f" {method} {url}")
try:
if method == 'GET':
response = requests.get(url, headers=headers, params=params, timeout=10)
elif method == 'POST':
response = requests.post(url, json=data, headers=headers, timeout=10)
elif method == 'PUT':
response = requests.put(url, json=data, headers=headers, timeout=10)
elif method == 'DELETE':
response = requests.delete(url, headers=headers, timeout=10)
success = response.status_code == expected_status
if success:
self.tests_passed += 1
print(f" β
PASSED - Status: {response.status_code}")
try:
response_data = response.json()
print(f" π Response keys: {list(response_data.keys()) if isinstance(response_data, dict) else type(response_data)}")
return True, response_data
except:
return True, {}
else:
print(f" β FAILED - Expected {expected_status}, got {response.status_code}")
try:
error_data = response.json()
print(f" π Error: {error_data}")
except:
print(f" π Raw response: {response.text}")
self.failed_tests.append(f"{name}: Expected {expected_status}, got {response.status_code}")
return False, {}
except requests.exceptions.RequestException as e:
print(f" β NETWORK ERROR: {str(e)}")
self.failed_tests.append(f"{name}: Network error - {str(e)}")
return False, {}
except Exception as e:
print(f" β ERROR: {str(e)}")
self.failed_tests.append(f"{name}: {str(e)}")
return False, {}
def test_auth_flow(self):
"""Test complete authentication flow"""
print("\n" + "="*50)
print("π TESTING AUTHENTICATION")
print("="*50)
# Test buyer registration
buyer_data = {
"name": "Test Buyer",
"email": "buyer@test.com",
"password": "test123",
"role": "buyer"
}
success, response = self.run_test("Buyer Registration", "POST", "auth/register", 200, buyer_data)
if success and response.get('token'):
self.buyer_token = response['token']
self.buyer_data = response.get('user', {})
print(f" π― Buyer ID: {self.buyer_data.get('id', 'N/A')}")
# Test seller registration
seller_data = {
"name": "Test Seller",
"email": "seller@test.com",
"password": "test123",
"role": "seller"
}
success, response = self.run_test("Seller Registration", "POST", "auth/register", 200, seller_data)
if success and response.get('token'):
self.seller_token = response['token']
self.seller_data = response.get('user', {})
print(f" π― Seller ID: {self.seller_data.get('id', 'N/A')}")
# Test buyer login
login_data = {"email": "buyer@test.com", "password": "test123"}
success, response = self.run_test("Buyer Login", "POST", "auth/login", 200, login_data)
if success and response.get('token'):
self.buyer_token = response['token']
self.buyer_data = response.get('user', {})
print(f" π― Buyer ID from login: {self.buyer_data.get('id', 'N/A')}")
# Test seller login
seller_login = {"email": "seller@test.com", "password": "test123"}
success, response = self.run_test("Seller Login", "POST", "auth/login", 200, seller_login)
if success and response.get('token'):
self.seller_token = response['token']
self.seller_data = response.get('user', {})
print(f" π― Seller ID from login: {self.seller_data.get('id', 'N/A')}")
# Test profile retrieval
if self.buyer_token:
self.run_test("Buyer Profile", "GET", "auth/me", 200, token=self.buyer_token)
if self.seller_token:
self.run_test("Seller Profile", "GET", "auth/me", 200, token=self.seller_token)
def test_products_api(self):
"""Test product-related endpoints"""
print("\n" + "="*50)
print("π¦ TESTING PRODUCTS API")
print("="*50)
# Test getting all products
success, products = self.run_test("Get All Products", "GET", "products", 200)
if success and isinstance(products, list):
print(f" π Found {len(products)} products")
if len(products) > 0:
sample_product = products[0]
product_id = sample_product.get('id')
print(f" π― Sample product: {sample_product.get('name', 'N/A')}")
# Test getting single product
if product_id:
self.run_test("Get Single Product", "GET", f"products/{product_id}", 200)
# Test product recommendations
self.run_test("Product Recommendations", "GET", f"recommendations/{product_id}", 200)
# Test categories
self.run_test("Get Categories", "GET", "categories", 200)
# Test product search
self.run_test("Search Products", "GET", "products", 200, params={"search": "pasta"})
# Test category filter
self.run_test("Filter by Category", "GET", "products", 200, params={"category": "Pantry"})
# Test seller product creation (if seller token available)
if self.seller_token:
product_data = {
"name": "Test Product",
"description": "A test product",
"price": 99.99,
"category": "Test Category",
"image_url": "https://via.placeholder.com/400",
"barcode": "1234567890123",
"stock": 50,
"tags": ["test", "sample"]
}
success, new_product = self.run_test("Create Product", "POST", "products", 200, product_data, self.seller_token)
if success and new_product.get('id'):
product_id = new_product['id']
print(f" π― Created product ID: {product_id}")
# Test product update
update_data = {**product_data, "price": 89.99}
self.run_test("Update Product", "PUT", f"products/{product_id}", 200, update_data, self.seller_token)
# Test product delete
self.run_test("Delete Product", "DELETE", f"products/{product_id}", 200, token=self.seller_token)
def test_cart_api(self):
"""Test cart functionality"""
print("\n" + "="*50)
print("π TESTING CART API")
print("="*50)
if not self.buyer_token:
print(" β οΈ Skipping cart tests - no buyer token")
return
# Get products to add to cart
success, products = self.run_test("Get Products for Cart", "GET", "products", 200)
if not success or not products:
print(" β οΈ Skipping cart tests - no products available")
return
product_id = products[0].get('id')
if not product_id:
print(" β οΈ Skipping cart tests - no valid product ID")
return
print(f" π― Using product: {products[0].get('name', 'N/A')}")
# Test empty cart
self.run_test("Get Empty Cart", "GET", "cart", 200, token=self.buyer_token)
# Test add to cart
cart_item = {"product_id": product_id, "quantity": 2}
self.run_test("Add to Cart", "POST", "cart/add", 200, cart_item, self.buyer_token)
# Test get cart with items
success, cart = self.run_test("Get Cart with Items", "GET", "cart", 200, token=self.buyer_token)
if success and cart:
print(f" π Cart has {len(cart)} items")
# Test update cart quantity
update_item = {"product_id": product_id, "quantity": 3}
self.run_test("Update Cart Quantity", "PUT", "cart/update", 200, update_item, self.buyer_token)
# Test remove from cart
self.run_test("Remove from Cart", "DELETE", f"cart/remove/{product_id}", 200, token=self.buyer_token)
# Test clear cart
self.run_test("Clear Cart", "DELETE", "cart/clear", 200, token=self.buyer_token)
def test_ai_features(self):
"""Test AI-related endpoints"""
print("\n" + "="*50)
print("π€ TESTING AI FEATURES")
print("="*50)
if not self.buyer_token:
print(" β οΈ Skipping AI tests - no buyer token")
return
# Test AI chat
chat_data = {"message": "I want to cook pasta for 4 people", "session_id": "test123"}
success, response = self.run_test("AI Chat", "POST", "ai/chat", 200, chat_data, self.buyer_token)
if success:
print(f" π― AI Response: {response.get('response', 'N/A')[:100]}...")
suggestions = response.get('suggestions', [])
print(f" π AI provided {len(suggestions)} suggestions")
# Test intent search
intent_data = {"query": "cold remedy"}
success, response = self.run_test("Intent Search", "POST", "ai/intent-search", 200, intent_data)
if success:
suggestions = response.get('suggestions', [])
print(f" π Intent search found {len(suggestions)} suggestions")
def test_payment_flow(self):
"""Test payment endpoints (mocked)"""
print("\n" + "="*50)
print("π³ TESTING PAYMENT FLOW (MOCKED)")
print("="*50)
if not self.buyer_token:
print(" β οΈ Skipping payment tests - no buyer token")
return
# Test create payment order
payment_data = {"amount": 10000} # Rs. 100.00
success, order = self.run_test("Create Payment Order", "POST", "payments/create-order", 200, payment_data, self.buyer_token)
if success and order.get('id'):
order_id = order['id']
print(f" π― Payment order ID: {order_id}")
# Test verify payment
verify_data = {"order_id": order_id}
self.run_test("Verify Payment", "POST", "payments/verify", 200, verify_data, self.buyer_token)
def test_order_flow(self):
"""Test complete order creation flow"""
print("\n" + "="*50)
print("π TESTING ORDER FLOW")
print("="*50)
if not self.buyer_token:
print(" β οΈ Skipping order tests - no buyer token")
return
# Get a product for order
success, products = self.run_test("Get Products for Order", "GET", "products", 200)
if not success or not products:
print(" β οΈ Skipping order tests - no products available")
return
product = products[0]
# Create order
order_data = {
"items": [{"product_id": product['id'], "name": product['name'], "price": product['price'], "quantity": 2}],
"total": product['price'] * 2,
"delivery_address": "123 Test Street, Test City, 12345"
}
success, order = self.run_test("Create Order", "POST", "orders", 200, order_data, self.buyer_token)
if success:
print(f" π― Order ID: {order.get('id', 'N/A')}")
# Get orders
self.run_test("Get User Orders", "GET", "orders", 200, token=self.buyer_token)
def test_seller_features(self):
"""Test seller-specific features"""
print("\n" + "="*50)
print("πͺ TESTING SELLER FEATURES")
print("="*50)
if not self.seller_token:
print(" β οΈ Skipping seller tests - no seller token")
return
# Test seller analytics
self.run_test("Seller Analytics", "GET", "analytics/seller", 200, token=self.seller_token)
# Test barcode lookup
barcode_data = {"barcode": "8901234567001"}
self.run_test("Barcode Lookup", "POST", "inventory/barcode-lookup", 200, barcode_data, self.seller_token)
# Test admin analytics (general endpoint)
self.run_test("Admin Analytics", "GET", "analytics/overview", 200)
def test_misc_endpoints(self):
"""Test miscellaneous endpoints"""
print("\n" + "="*50)
print("π§ TESTING MISC ENDPOINTS")
print("="*50)
# Test stores
self.run_test("Get Stores", "GET", "stores", 200)
# Test seed endpoint
self.run_test("Seed Data", "POST", "seed", 200)
def run_all_tests(self):
"""Run comprehensive API test suite"""
print("π Starting NexusBuy API Test Suite")
print(f"π Backend URL: {self.base_url}")
print(f"β° Test started at: {datetime.now()}")
try:
self.test_auth_flow()
self.test_products_api()
self.test_cart_api()
self.test_ai_features()
self.test_payment_flow()
self.test_order_flow()
self.test_seller_features()
self.test_misc_endpoints()
except KeyboardInterrupt:
print("\nβ οΈ Tests interrupted by user")
except Exception as e:
print(f"\nπ₯ Unexpected error during testing: {str(e)}")
self.print_summary()
def print_summary(self):
"""Print test results summary"""
print("\n" + "="*60)
print("π TEST RESULTS SUMMARY")
print("="*60)
success_rate = (self.tests_passed / self.tests_run * 100) if self.tests_run > 0 else 0
print(f"β
Tests Passed: {self.tests_passed}/{self.tests_run} ({success_rate:.1f}%)")
if self.failed_tests:
print(f"\nβ Failed Tests ({len(self.failed_tests)}):")
for i, failure in enumerate(self.failed_tests, 1):
print(f" {i}. {failure}")
print(f"\nπ― Authentication Status:")
print(f" Buyer Token: {'β
Valid' if self.buyer_token else 'β Missing'}")
print(f" Seller Token: {'β
Valid' if self.seller_token else 'β Missing'}")
if success_rate >= 80:
print(f"\nπ OVERALL STATUS: β
GOOD (Backend appears functional)")
return 0
elif success_rate >= 50:
print(f"\nβ οΈ OVERALL STATUS: π‘ PARTIAL (Some issues detected)")
return 1
else:
print(f"\nπ₯ OVERALL STATUS: β POOR (Major issues detected)")
return 2
def main():
"""Main function"""
backend_url = "https://nexus-buy.preview.emergentagent.com"
print("NexusBuy API Tester")
print("==================")
tester = NexusBuyAPITester(backend_url)
return tester.run_all_tests()
if __name__ == "__main__":
sys.exit(main())