-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest_inventory_sync.py
More file actions
182 lines (152 loc) · 7.18 KB
/
Copy pathtest_inventory_sync.py
File metadata and controls
182 lines (152 loc) · 7.18 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
"""
🧪 Test Inventory Sync System
Тестовый скрипт для проверки динамической синхронизации
"""
import asyncio
import httpx
import json
from typing import Optional
BASE_URL = "http://localhost:8000"
class Colors:
GREEN = '\033[92m'
RED = '\033[91m'
YELLOW = '\033[93m'
BLUE = '\033[94m'
END = '\033[0m'
def print_success(msg: str):
print(f"{Colors.GREEN}✅ {msg}{Colors.END}")
def print_error(msg: str):
print(f"{Colors.RED}❌ {msg}{Colors.END}")
def print_info(msg: str):
print(f"{Colors.BLUE}ℹ️ {msg}{Colors.END}")
def print_warning(msg: str):
print(f"{Colors.YELLOW}⚠️ {msg}{Colors.END}")
async def test_inventory_sync():
"""Main test function"""
async with httpx.AsyncClient() as client:
print("\n" + "="*60)
print("🧪 Testing Inventory Sync System")
print("="*60 + "\n")
# Test 1: Check API is running
print("Test 1: Check API Status")
try:
response = await client.get(f"{BASE_URL}/api/inventory/test")
if response.status_code == 200:
print_success("API is running")
else:
print_error(f"API returned status {response.status_code}")
return
except Exception as e:
print_error(f"Cannot connect to API: {e}")
print_warning("Make sure to run: python main.py")
return
# Test 2: Get initial inventory
print("\nTest 2: Get Initial Inventory")
try:
response = await client.get(f"{BASE_URL}/api/inventory/items?user_id=1")
data = response.json()
print_info(f"Current items: {data.get('count', 0)}")
if data.get('items'):
for item in data['items']:
print(f" • {item['name']} - {item['quantity']}")
except Exception as e:
print_error(f"Error: {e}")
# Test 3: Add item to inventory
print("\nTest 3: Add Item to Inventory")
print_info("Adding 'яйцо' (10 шт) to inventory...")
try:
response = await client.post(
f"{BASE_URL}/api/inventory/items/add",
json={
"name": "яйцо",
"quantity": "10 шт",
"category": "молочные продукты",
"user_id": 1
}
)
data = response.json()
if data.get('success'):
print_success(f"Item added: {data['message']}")
sync_result = data.get('data', {}).get('sync_result', {})
if sync_result.get('synced'):
print_info(f"Sync action: {sync_result.get('action')}")
removed_items = sync_result.get('items_removed', [])
if removed_items:
print_success(f"Removed from shopping list: {', '.join(removed_items)}")
if sync_result.get('cart_updated'):
print_success("Cart updated successfully")
print_info(f"Remaining items: {sync_result.get('remaining_items')}")
print_info(f"New total: {sync_result.get('new_total')}₽")
else:
print_error(f"Failed: {data}")
except Exception as e:
print_error(f"Error: {e}")
# Test 4: Check sync status
print("\nTest 4: Check Sync Status")
try:
response = await client.get(f"{BASE_URL}/api/inventory/sync/status?user_id=1")
data = response.json()
if data.get('success'):
status = data['data']
print_info("Current Status:")
print(f"\n📦 Inventory:")
print(f" Items: {status['inventory']['count']}")
if status['inventory']['items']:
for item in status['inventory']['items'][:5]:
print(f" • {item}")
print(f"\n🛒 Shopping List:")
print(f" Items: {status['shopping_list']['count']}")
print(f" Total: {status['shopping_list']['total_cost']}₽")
if status['shopping_list']['items']:
for item in status['shopping_list']['items'][:5]:
print(f" • {item}")
print(f"\n🛍️ Cart:")
print(f" Items: {status['cart']['count']}")
if status['cart']['link']:
print(f" Link: {status['cart']['link']}")
else:
print_warning(" No cart link available")
print_info(" Generate shopping list first: POST /api/shopping/generate")
except Exception as e:
print_error(f"Error: {e}")
# Test 5: Remove item
print("\nTest 5: Remove Item from Inventory")
print_info("Removing 'яйцо' from inventory...")
try:
response = await client.post(
f"{BASE_URL}/api/inventory/items/remove",
json={
"name": "яйцо",
"user_id": 1
}
)
data = response.json()
if data.get('success'):
print_success(f"Item removed: {data['message']}")
sync_result = data.get('data', {}).get('sync_result', {})
if sync_result.get('synced'):
print_info(f"Sync action: {sync_result.get('action')}")
if sync_result.get('message'):
print_warning(sync_result['message'])
else:
print_warning(f"Item not found or already removed")
except Exception as e:
print_error(f"Error: {e}")
print("\n" + "="*60)
print("✨ Test Complete!")
print("="*60 + "\n")
print("📚 Next Steps:")
print("1. Generate shopping list: POST /api/shopping/generate")
print("2. Add items to inventory: POST /api/inventory/items/add")
print("3. Check sync status: GET /api/inventory/sync/status")
print("\n📖 Full docs: INVENTORY_SYNC_GUIDE.md\n")
if __name__ == "__main__":
print("""
╔══════════════════════════════════════════════════════════╗
║ 🔄 Inventory Sync System - Test Suite ║
║ ║
║ Тестирование динамической синхронизации: ║
║ • Холодильник ↔ Список покупок ↔ Корзина ВкусВилл ║
╚══════════════════════════════════════════════════════════╝
""")
asyncio.run(test_inventory_sync())