product-classify / tests /test_api.py
Abhishek7356
creating new projects fro product categorise
d12790d
"""
Test script for Product Classification API
Run this to test your API endpoints
"""
import requests
import json
from typing import Dict, List
# API base URL
BASE_URL = "http://localhost:8000"
def test_health():
"""Test health check endpoint"""
print("\n" + "=" * 80)
print("TEST 1: Health Check")
print("=" * 80)
response = requests.get(f"{BASE_URL}/health")
if response.status_code == 200:
data = response.json()
print("βœ… API is healthy!")
print(f" Status: {data['status']}")
print(f" Categories loaded: {data['categories_loaded']:,}")
print(f" Embedding dimension: {data['embedding_dimension']}")
else:
print(f"❌ Health check failed: {response.status_code}")
return response.status_code == 200
def test_single_classification():
"""Test single product classification"""
print("\n" + "=" * 80)
print("TEST 2: Single Product Classification")
print("=" * 80)
# Test product
product = {
"id": "test_001",
"title": "Sony WH-1000XM5 Wireless Headphones",
"product_type": "Headphones",
"vendor": "Sony",
"tags": ["audio", "electronics", "wireless", "bluetooth"],
"description": "Premium noise-canceling over-ear headphones",
}
print(f"\nπŸ“± Test Product: {product['title']}")
response = requests.post(f"{BASE_URL}/classify", json=product)
if response.status_code == 200:
result = response.json()
print(f"\nβœ… Classification successful!")
print(f" Action: {result['action']}")
print(f" Top Category: {result['top_category']}")
print(f" Confidence: {result['top_confidence']}%")
print(f" Processing Time: {result['processing_time_ms']}ms")
print(f"\nπŸ“Š Top 3 Alternative Categories:")
for alt in result["alternatives"][:3]:
print(f" {alt['rank']}. {alt['category_path']}")
print(f" Confidence: {alt['confidence_percentage']}%")
return True
else:
print(f"❌ Classification failed: {response.status_code}")
print(f" Error: {response.text}")
return False
def test_batch_classification():
"""Test batch product classification"""
print("\n" + "=" * 80)
print("TEST 3: Batch Classification")
print("=" * 80)
# Multiple test products
products = [
{
"id": "prod_001",
"title": "Samsung Galaxy S24 Ultra",
"product_type": "Smartphone",
"vendor": "Samsung",
"tags": ["electronics", "phone", "mobile", "android"],
},
{
"id": "prod_002",
"title": "KitchenAid Stand Mixer",
"product_type": "Kitchen Appliance",
"vendor": "KitchenAid",
"tags": ["appliance", "kitchen", "cooking"],
},
{
"id": "prod_003",
"title": "Nike Air Zoom Running Shoes",
"product_type": "Athletic Footwear",
"vendor": "Nike",
"tags": ["shoes", "sports", "running", "athletic"],
},
]
batch_request = {"products": products, "top_k": 3}
print(f"\nπŸ“¦ Testing batch of {len(products)} products...")
response = requests.post(f"{BASE_URL}/classify-batch", json=batch_request)
if response.status_code == 200:
result = response.json()
print(f"\nβœ… Batch classification successful!")
print(f" Total products: {result['total_products']}")
print(f" Processing time: {result['processing_time_ms']:.2f}ms")
print(
f" Time per product: {result['processing_time_ms']/result['total_products']:.2f}ms"
)
print(f"\nπŸ“Š Action Distribution:")
for action, count in result["action_counts"].items():
percentage = (count / result["total_products"]) * 100
print(f" {action}: {count} ({percentage:.1f}%)")
print(f"\n🎯 Individual Results:")
for res in result["results"]:
print(f"\n β€’ {res.get('product_id', 'N/A')}")
print(f" Action: {res['action']}")
print(f" Confidence: {res.get('top_confidence', 0)}%")
if res.get("top_category"):
print(f" Category: {res['top_category'][:60]}...")
return True
else:
print(f"❌ Batch classification failed: {response.status_code}")
print(f" Error: {response.text}")
return False
def test_various_products():
"""Test with various product types"""
print("\n" + "=" * 80)
print("TEST 4: Various Product Types")
print("=" * 80)
test_cases = [
{
"name": "Electronics",
"product": {
"title": "MacBook Pro 16 inch M3",
"product_type": "Laptop Computer",
"vendor": "Apple",
"tags": ["computer", "laptop", "electronics"],
},
},
{
"name": "Books",
"product": {
"title": "The Great Gatsby by F. Scott Fitzgerald",
"product_type": "Book",
"vendor": "Scribner",
"tags": ["books", "fiction", "literature", "classic"],
},
},
{
"name": "Home Appliances",
"product": {
"title": "Dyson V15 Detect Vacuum Cleaner",
"product_type": "Vacuum Cleaner",
"vendor": "Dyson",
"tags": ["appliance", "cleaning", "home", "cordless"],
},
},
{
"name": "Toys",
"product": {
"title": "LEGO Star Wars Millennium Falcon",
"product_type": "Building Toy",
"vendor": "LEGO",
"tags": ["toys", "kids", "lego", "star wars", "building"],
},
},
]
results_summary = []
for test_case in test_cases:
print(f"\nπŸ§ͺ Testing: {test_case['name']}")
print(f" Product: {test_case['product']['title']}")
response = requests.post(f"{BASE_URL}/classify", json=test_case["product"])
if response.status_code == 200:
result = response.json()
confidence = result["top_confidence"]
action = result["action"]
emoji = (
"βœ…"
if action == "AUTO_APPROVE"
else "⚠️" if action == "QUICK_REVIEW" else "❌"
)
print(f" {emoji} {action}: {confidence}%")
results_summary.append(
{
"category": test_case["name"],
"confidence": confidence,
"action": action,
}
)
else:
print(f" ❌ Failed: {response.status_code}")
results_summary.append(
{"category": test_case["name"], "confidence": 0, "action": "ERROR"}
)
# Print summary
print(f"\nπŸ“ˆ SUMMARY:")
print("-" * 80)
avg_confidence = sum(r["confidence"] for r in results_summary) / len(
results_summary
)
auto_approve_count = sum(
1 for r in results_summary if r["action"] == "AUTO_APPROVE"
)
print(f"Average Confidence: {avg_confidence:.2f}%")
print(
f"Auto-Approve Rate: {auto_approve_count}/{len(results_summary)} ({auto_approve_count/len(results_summary)*100:.1f}%)"
)
return True
def run_all_tests():
"""Run all tests"""
print("\n" + "=" * 80)
print("πŸ§ͺ RUNNING ALL API TESTS")
print("=" * 80)
print("\nMake sure API is running: uvicorn src.api:app --reload")
tests = [
("Health Check", test_health),
("Single Classification", test_single_classification),
("Batch Classification", test_batch_classification),
("Various Products", test_various_products),
]
results = []
for test_name, test_func in tests:
try:
result = test_func()
results.append((test_name, result))
except requests.exceptions.ConnectionError:
print(f"\n❌ Connection Error: Is the API running?")
print(" Start it with: uvicorn src.api:app --reload")
return
except Exception as e:
print(f"\n❌ Error in {test_name}: {e}")
results.append((test_name, False))
# Final summary
print("\n" + "=" * 80)
print("πŸ“Š TEST RESULTS SUMMARY")
print("=" * 80)
for test_name, result in results:
status = "βœ… PASS" if result else "❌ FAIL"
print(f"{status} - {test_name}")
passed = sum(1 for _, r in results if r)
total = len(results)
print(f"\n🎯 Overall: {passed}/{total} tests passed ({passed/total*100:.1f}%)")
if passed == total:
print("\nπŸŽ‰ ALL TESTS PASSED! Your API is working perfectly!")
else:
print(f"\n⚠️ Some tests failed. Check the errors above.")
if __name__ == "__main__":
run_all_tests()