-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackend_test.py
More file actions
307 lines (248 loc) · 10.5 KB
/
Copy pathbackend_test.py
File metadata and controls
307 lines (248 loc) · 10.5 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
import requests
import sys
import json
import base64
from datetime import datetime
from PIL import Image
import io
class InventoryAPITester:
def __init__(self, base_url="https://inventorylens-1.preview.emergentagent.com"):
self.base_url = base_url
self.api_url = f"{base_url}/api"
self.tests_run = 0
self.tests_passed = 0
self.created_items = []
self.created_categories = []
self.created_alerts = []
def run_test(self, name, method, endpoint, expected_status, data=None, files=None):
"""Run a single API test"""
url = f"{self.api_url}/{endpoint}"
headers = {'Content-Type': 'application/json'} if not files else {}
self.tests_run += 1
print(f"\n🔍 Testing {name}...")
try:
if method == 'GET':
response = requests.get(url, headers=headers)
elif method == 'POST':
if files:
response = requests.post(url, files=files)
else:
response = requests.post(url, json=data, headers=headers)
elif method == 'PUT':
response = requests.put(url, json=data, headers=headers)
elif method == 'DELETE':
response = requests.delete(url, headers=headers)
success = response.status_code == expected_status
if success:
self.tests_passed += 1
print(f"✅ Passed - Status: {response.status_code}")
try:
return success, response.json() if response.text else {}
except:
return success, {}
else:
print(f"❌ Failed - Expected {expected_status}, got {response.status_code}")
print(f"Response: {response.text}")
return False, {}
except Exception as e:
print(f"❌ Failed - Error: {str(e)}")
return False, {}
def create_test_image(self):
"""Create a simple test image for AI identification"""
# Create a simple red apple-like image
img = Image.new('RGB', (200, 200), color='white')
# Draw a simple red circle to simulate an apple
from PIL import ImageDraw
draw = ImageDraw.Draw(img)
draw.ellipse([50, 50, 150, 150], fill='red', outline='darkred')
# Convert to bytes
img_bytes = io.BytesIO()
img.save(img_bytes, format='JPEG')
img_bytes.seek(0)
return img_bytes.getvalue()
def test_categories(self):
"""Test category CRUD operations"""
print("\n=== TESTING CATEGORIES ===")
# Test get categories (should work even if empty)
success, categories = self.run_test("Get Categories", "GET", "categories", 200)
if not success:
return False
# Test create category
category_data = {
"name": f"Test Category {datetime.now().strftime('%H%M%S')}",
"default_threshold": 5
}
success, category = self.run_test("Create Category", "POST", "categories", 200, category_data)
if success and 'id' in category:
self.created_categories.append(category['id'])
print(f"Created category with ID: {category['id']}")
else:
return False
# Test update category
update_data = {"default_threshold": 8}
success, updated_category = self.run_test(
"Update Category", "PUT", f"categories/{category['id']}", 200, update_data
)
if not success:
return False
return True
def test_items(self):
"""Test item CRUD operations"""
print("\n=== TESTING ITEMS ===")
if not self.created_categories:
print("❌ No categories available for item testing")
return False
category_id = self.created_categories[0]
# Test get items (should work even if empty)
success, items = self.run_test("Get Items", "GET", "items", 200)
if not success:
return False
# Test create item
item_data = {
"name": f"Test Apple {datetime.now().strftime('%H%M%S')}",
"category_id": category_id,
"quantity": 10,
"threshold": 3
}
success, item = self.run_test("Create Item", "POST", "items", 200, item_data)
if success and 'id' in item:
self.created_items.append(item['id'])
print(f"Created item with ID: {item['id']}")
else:
return False
# Test get single item
success, single_item = self.run_test("Get Single Item", "GET", f"items/{item['id']}", 200)
if not success:
return False
# Test update item
update_data = {"name": "Updated Test Apple", "threshold": 5}
success, updated_item = self.run_test(
"Update Item", "PUT", f"items/{item['id']}", 200, update_data
)
if not success:
return False
# Test stock adjustment
adjustment_data = {"adjustment": -7} # This should trigger low stock alert
success, adjustment_result = self.run_test(
"Adjust Stock", "POST", f"items/{item['id']}/adjust-stock", 200, adjustment_data
)
if not success:
return False
return True
def test_ai_identification(self):
"""Test AI product identification"""
print("\n=== TESTING AI IDENTIFICATION ===")
try:
# Create test image
test_image = self.create_test_image()
# Prepare file for upload
files = {'file': ('test_apple.jpg', test_image, 'image/jpeg')}
success, result = self.run_test(
"AI Product Identification", "POST", "identify-product", 200, files=files
)
if success and 'product_name' in result and 'category' in result:
print(f"AI identified: {result['product_name']} in category {result['category']}")
return True
else:
print("❌ AI identification failed - missing required fields")
return False
except Exception as e:
print(f"❌ AI identification test failed: {str(e)}")
return False
def test_alerts(self):
"""Test alert operations"""
print("\n=== TESTING ALERTS ===")
# Test get alerts
success, alerts = self.run_test("Get All Alerts", "GET", "alerts", 200)
if not success:
return False
# Test get unread alerts only
success, unread_alerts = self.run_test("Get Unread Alerts", "GET", "alerts?unread_only=true", 200)
if not success:
return False
# If we have alerts from stock adjustment, test mark as read and delete
if alerts:
alert_id = alerts[0]['id']
self.created_alerts.append(alert_id)
# Test mark as read
success, _ = self.run_test("Mark Alert Read", "PUT", f"alerts/{alert_id}/mark-read", 200)
if not success:
return False
# Test delete alert
success, _ = self.run_test("Delete Alert", "DELETE", f"alerts/{alert_id}", 200)
if success:
self.created_alerts.remove(alert_id)
return True
def test_filters_and_queries(self):
"""Test various query parameters and filters"""
print("\n=== TESTING FILTERS AND QUERIES ===")
if not self.created_categories:
print("❌ No categories available for filter testing")
return False
category_id = self.created_categories[0]
# Test items by category
success, filtered_items = self.run_test(
"Get Items by Category", "GET", f"items?category_id={category_id}", 200
)
if not success:
return False
# Test low stock items
success, low_stock_items = self.run_test(
"Get Low Stock Items", "GET", "items?low_stock=true", 200
)
if not success:
return False
return True
def cleanup(self):
"""Clean up created test data"""
print("\n=== CLEANING UP TEST DATA ===")
# Delete created items
for item_id in self.created_items:
self.run_test(f"Delete Item {item_id}", "DELETE", f"items/{item_id}", 200)
# Delete remaining alerts
for alert_id in self.created_alerts:
self.run_test(f"Delete Alert {alert_id}", "DELETE", f"alerts/{alert_id}", 200)
# Note: We don't delete categories as they might be used by other items
def run_all_tests(self):
"""Run all API tests"""
print("🚀 Starting Inventory API Tests...")
print(f"Testing against: {self.base_url}")
try:
# Test categories first (needed for items)
if not self.test_categories():
print("❌ Category tests failed, stopping")
return False
# Test items
if not self.test_items():
print("❌ Item tests failed, stopping")
return False
# Test AI identification
if not self.test_ai_identification():
print("❌ AI identification tests failed, continuing with other tests")
# Test alerts
if not self.test_alerts():
print("❌ Alert tests failed, stopping")
return False
# Test filters and queries
if not self.test_filters_and_queries():
print("❌ Filter tests failed, stopping")
return False
return True
finally:
# Always cleanup
self.cleanup()
def main():
tester = InventoryAPITester()
success = tester.run_all_tests()
# Print final results
print(f"\n📊 Final Results:")
print(f"Tests passed: {tester.tests_passed}/{tester.tests_run}")
print(f"Success rate: {(tester.tests_passed/tester.tests_run)*100:.1f}%")
if success and tester.tests_passed == tester.tests_run:
print("🎉 All tests passed!")
return 0
else:
print("❌ Some tests failed")
return 1
if __name__ == "__main__":
sys.exit(main())