Initial commit - PromptTech

This commit is contained in:
2026-01-27 18:07:00 -06:00
commit 3959a223bf
262 changed files with 128736 additions and 0 deletions

0
tests/__init__.py Normal file
View File

343
tests/admin_test.py Normal file
View File

@@ -0,0 +1,343 @@
import requests
import sys
import json
from datetime import datetime
class AdminAPITester:
def __init__(self, base_url="https://dev-foundry.preview.emergentagent.com/api"):
self.base_url = base_url
self.admin_token = None
self.user_token = None
self.tests_run = 0
self.tests_passed = 0
self.test_results = []
self.created_product_id = None
self.created_service_id = None
self.created_order_id = None
def log_test(self, name, success, details=""):
"""Log test result"""
self.tests_run += 1
if success:
self.tests_passed += 1
result = {
"test": name,
"success": success,
"details": details,
"timestamp": datetime.now().isoformat()
}
self.test_results.append(result)
status = "✅ PASS" if success else "❌ FAIL"
print(f"{status} - {name}")
if details:
print(f" Details: {details}")
def run_test(self, name, method, endpoint, expected_status, data=None, headers=None, use_admin=True):
"""Run a single API test"""
url = f"{self.base_url}/{endpoint}"
test_headers = {'Content-Type': 'application/json'}
token = self.admin_token if use_admin else self.user_token
if token:
test_headers['Authorization'] = f'Bearer {token}'
if headers:
test_headers.update(headers)
try:
if method == 'GET':
response = requests.get(url, headers=test_headers, timeout=15)
elif method == 'POST':
response = requests.post(url, json=data, headers=test_headers, timeout=15)
elif method == 'PUT':
response = requests.put(url, json=data, headers=test_headers, timeout=15)
elif method == 'DELETE':
response = requests.delete(url, headers=test_headers, timeout=15)
success = response.status_code == expected_status
details = f"Status: {response.status_code}, Expected: {expected_status}"
if not success:
try:
error_data = response.json()
details += f", Response: {error_data}"
except:
details += f", Response: {response.text[:200]}"
self.log_test(name, success, details)
if success:
try:
return response.json()
except:
return {"status": "success"}
return None
except Exception as e:
self.log_test(name, False, f"Error: {str(e)}")
return None
def test_admin_login(self):
"""Test admin login"""
login_data = {
"email": "admin@techzone.com",
"password": "admin123"
}
response = self.run_test("Admin Login", "POST", "auth/login", 200, login_data, use_admin=False)
if response and 'access_token' in response:
self.admin_token = response['access_token']
return True
return False
def test_user_registration_and_login(self):
"""Test regular user registration for order testing"""
test_user_data = {
"name": f"Test User {datetime.now().strftime('%H%M%S')}",
"email": f"testuser_{datetime.now().strftime('%H%M%S')}@example.com",
"password": "testpass123"
}
response = self.run_test("User Registration for Orders", "POST", "auth/register", 200, test_user_data, use_admin=False)
if response and 'access_token' in response:
self.user_token = response['access_token']
return True
return False
def test_admin_dashboard(self):
"""Test admin dashboard stats"""
return self.run_test("Admin Dashboard Stats", "GET", "admin/dashboard", 200)
def test_admin_products_crud(self):
"""Test admin product CRUD operations"""
# Get existing products
self.run_test("Admin Get Products", "GET", "admin/products", 200)
# Create new product
product_data = {
"name": "Test Product Admin",
"description": "Test product created by admin API test",
"price": 99.99,
"category": "accessories",
"image_url": "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?w=800",
"stock": 50,
"brand": "TestBrand"
}
create_response = self.run_test("Admin Create Product", "POST", "admin/products", 200, product_data)
if create_response and 'id' in create_response:
self.created_product_id = create_response['id']
# Update the product
update_data = {
"name": "Updated Test Product",
"price": 149.99,
"stock": 25
}
self.run_test("Admin Update Product", "PUT", f"admin/products/{self.created_product_id}", 200, update_data)
# Delete the product (soft delete)
self.run_test("Admin Delete Product", "DELETE", f"admin/products/{self.created_product_id}", 200)
return True
return False
def test_admin_services_crud(self):
"""Test admin service CRUD operations"""
# Get existing services
self.run_test("Admin Get Services", "GET", "admin/services", 200)
# Create new service
service_data = {
"name": "Test Service Admin",
"description": "Test service created by admin API test",
"price": 79.99,
"duration": "1 hour",
"image_url": "https://images.unsplash.com/photo-1581092918056-0c4c3acd3789?w=800",
"category": "repair"
}
create_response = self.run_test("Admin Create Service", "POST", "admin/services", 200, service_data)
if create_response and 'id' in create_response:
self.created_service_id = create_response['id']
# Update the service
update_data = {
"name": "Updated Test Service",
"price": 99.99,
"duration": "2 hours"
}
self.run_test("Admin Update Service", "PUT", f"admin/services/{self.created_service_id}", 200, update_data)
# Delete the service (soft delete)
self.run_test("Admin Delete Service", "DELETE", f"admin/services/{self.created_service_id}", 200)
return True
return False
def test_create_order_for_admin_testing(self):
"""Create an order using regular user to test admin order management"""
if not self.user_token:
return False
# Get products first
products_response = self.run_test("Get Products for Order", "GET", "products", 200, use_admin=False)
if not products_response or len(products_response) == 0:
return False
product_id = products_response[0]['id']
# Add to cart
add_cart_data = {"product_id": product_id, "quantity": 1}
self.run_test("Add to Cart for Order", "POST", "cart/add", 200, add_cart_data, use_admin=False)
# Create order
order_data = {
"shipping_address": {
"street": "123 Test St",
"city": "Test City",
"state": "TS",
"zip": "12345",
"country": "USA"
},
"notes": "Test order for admin testing"
}
order_response = self.run_test("Create Order for Admin Testing", "POST", "orders", 200, order_data, use_admin=False)
if order_response and 'order_id' in order_response:
self.created_order_id = order_response['order_id']
return True
return False
def test_admin_orders_management(self):
"""Test admin order management"""
# Get all orders
orders_response = self.run_test("Admin Get Orders", "GET", "admin/orders", 200)
if self.created_order_id:
# Update order status
status_update = {
"status": "processing",
"notes": "Order is being processed",
"tracking_number": "TEST123456"
}
self.run_test("Admin Update Order Status", "PUT", f"admin/orders/{self.created_order_id}/status", 200, status_update)
# Test order filtering
self.run_test("Admin Get Orders by Status", "GET", "admin/orders?status=pending", 200)
return True
def test_admin_inventory_management(self):
"""Test admin inventory management"""
# Get inventory
inventory_response = self.run_test("Admin Get Inventory", "GET", "admin/inventory", 200)
if inventory_response and len(inventory_response) > 0:
product_id = inventory_response[0]['id']
# Adjust inventory
adjust_data = {
"quantity_change": 10,
"notes": "Test inventory adjustment"
}
self.run_test("Admin Adjust Inventory", "POST", f"admin/inventory/{product_id}/adjust", 200, adjust_data)
# Get inventory logs
self.run_test("Admin Get Inventory Logs", "GET", f"admin/inventory/{product_id}/logs", 200)
return True
def test_admin_bookings_management(self):
"""Test admin bookings management"""
# Get bookings
bookings_response = self.run_test("Admin Get Bookings", "GET", "admin/bookings", 200)
# Test booking status filter
self.run_test("Admin Get Pending Bookings", "GET", "admin/bookings?status=pending", 200)
return True
def test_admin_users_management(self):
"""Test admin users management"""
return self.run_test("Admin Get Users", "GET", "admin/users", 200)
def test_admin_reports(self):
"""Test admin reports functionality"""
# Test sales reports
self.run_test("Admin Sales Report Daily", "GET", "admin/reports/sales?period=daily", 200)
self.run_test("Admin Sales Report Weekly", "GET", "admin/reports/sales?period=weekly", 200)
self.run_test("Admin Sales Report Monthly", "GET", "admin/reports/sales?period=monthly", 200)
return True
def test_admin_export_reports(self):
"""Test admin report exports"""
# Test CSV exports
csv_response = self.run_test("Admin Export CSV Sales", "GET", "admin/reports/export/csv?report_type=sales&period=monthly", 200)
csv_inventory = self.run_test("Admin Export CSV Inventory", "GET", "admin/reports/export/csv?report_type=inventory", 200)
csv_orders = self.run_test("Admin Export CSV Orders", "GET", "admin/reports/export/csv?report_type=orders", 200)
# Test PDF exports
pdf_response = self.run_test("Admin Export PDF Sales", "GET", "admin/reports/export/pdf?report_type=sales&period=monthly", 200)
pdf_inventory = self.run_test("Admin Export PDF Inventory", "GET", "admin/reports/export/pdf?report_type=inventory", 200)
return True
def run_all_admin_tests(self):
"""Run all admin API tests"""
print("🔐 Starting TechZone Admin API Tests...")
print(f"📍 Testing against: {self.base_url}")
print("=" * 60)
# Test admin authentication
if not self.test_admin_login():
print("❌ Admin login failed - cannot continue with admin tests")
return False
# Test user registration for order testing
self.test_user_registration_and_login()
# Test admin dashboard
self.test_admin_dashboard()
# Test admin CRUD operations
self.test_admin_products_crud()
self.test_admin_services_crud()
# Create order for admin testing
self.test_create_order_for_admin_testing()
# Test admin management features
self.test_admin_orders_management()
self.test_admin_inventory_management()
self.test_admin_bookings_management()
self.test_admin_users_management()
# Test admin reports
self.test_admin_reports()
self.test_admin_export_reports()
# Print summary
print("=" * 60)
print(f"📊 Admin tests completed: {self.tests_passed}/{self.tests_run}")
success_rate = (self.tests_passed / self.tests_run * 100) if self.tests_run > 0 else 0
print(f"📈 Success rate: {success_rate:.1f}%")
if self.tests_passed < self.tests_run:
print("\n❌ Failed tests:")
for result in self.test_results:
if not result['success']:
print(f" - {result['test']}: {result['details']}")
return self.tests_passed == self.tests_run
def main():
tester = AdminAPITester()
success = tester.run_all_admin_tests()
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())

284
tests/backend_test.py Normal file
View File

@@ -0,0 +1,284 @@
import requests
import sys
import json
from datetime import datetime
class TechZoneAPITester:
def __init__(self, base_url="https://dev-foundry.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(self, name, success, details=""):
"""Log test result"""
self.tests_run += 1
if success:
self.tests_passed += 1
result = {
"test": name,
"success": success,
"details": details,
"timestamp": datetime.now().isoformat()
}
self.test_results.append(result)
status = "✅ PASS" if success else "❌ FAIL"
print(f"{status} - {name}")
if details:
print(f" Details: {details}")
def run_test(self, name, method, endpoint, expected_status, data=None, headers=None):
"""Run a single API test"""
url = f"{self.base_url}/{endpoint}"
test_headers = {'Content-Type': 'application/json'}
if self.token:
test_headers['Authorization'] = f'Bearer {self.token}'
if headers:
test_headers.update(headers)
try:
if method == 'GET':
response = requests.get(url, headers=test_headers, timeout=10)
elif method == 'POST':
response = requests.post(url, json=data, headers=test_headers, timeout=10)
elif method == 'PUT':
response = requests.put(url, json=data, headers=test_headers, timeout=10)
elif method == 'DELETE':
response = requests.delete(url, headers=test_headers, timeout=10)
success = response.status_code == expected_status
details = f"Status: {response.status_code}, Expected: {expected_status}"
if not success:
try:
error_data = response.json()
details += f", Response: {error_data}"
except:
details += f", Response: {response.text[:200]}"
self.log_test(name, success, details)
if success:
try:
return response.json()
except:
return {"status": "success"}
return None
except Exception as e:
self.log_test(name, False, f"Error: {str(e)}")
return None
def test_root_endpoint(self):
"""Test root API endpoint"""
return self.run_test("Root API", "GET", "", 200)
def test_seed_data(self):
"""Test seeding data"""
return self.run_test("Seed Data", "POST", "seed", 200)
def test_user_registration(self):
"""Test user registration"""
test_user_data = {
"name": f"Test User {datetime.now().strftime('%H%M%S')}",
"email": f"test_{datetime.now().strftime('%H%M%S')}@example.com",
"password": "testpass123"
}
response = self.run_test("User Registration", "POST", "auth/register", 200, test_user_data)
if response and 'access_token' in response:
self.token = response['access_token']
self.user_id = response['user']['id']
return True
return False
def test_user_login(self):
"""Test user login with admin credentials"""
login_data = {
"email": "admin@techzone.com",
"password": "admin123"
}
response = self.run_test("User Login (Admin)", "POST", "auth/login", 200, login_data)
if response and 'access_token' in response:
self.token = response['access_token']
self.user_id = response['user']['id']
return True
return False
def test_get_current_user(self):
"""Test getting current user info"""
return self.run_test("Get Current User", "GET", "auth/me", 200)
def test_get_products(self):
"""Test getting all products"""
response = self.run_test("Get All Products", "GET", "products", 200)
return response is not None
def test_get_products_with_filters(self):
"""Test getting products with filters"""
# Test category filter
self.run_test("Get Products by Category", "GET", "products?category=phones", 200)
# Test search filter
self.run_test("Get Products by Search", "GET", "products?search=iPhone", 200)
# Test price filter
self.run_test("Get Products by Price", "GET", "products?min_price=100&max_price=1000", 200)
def test_get_product_detail(self):
"""Test getting product details"""
# First get products to get an ID
products_response = self.run_test("Get Products for Detail Test", "GET", "products", 200)
if products_response and len(products_response) > 0:
product_id = products_response[0]['id']
return self.run_test("Get Product Detail", "GET", f"products/{product_id}", 200)
return False
def test_get_categories(self):
"""Test getting product categories"""
return self.run_test("Get Product Categories", "GET", "products/categories/list", 200)
def test_get_services(self):
"""Test getting all services"""
response = self.run_test("Get All Services", "GET", "services", 200)
return response is not None
def test_get_services_with_filter(self):
"""Test getting services with category filter"""
self.run_test("Get Services by Category", "GET", "services?category=repair", 200)
def test_get_service_detail(self):
"""Test getting service details"""
# First get services to get an ID
services_response = self.run_test("Get Services for Detail Test", "GET", "services", 200)
if services_response and len(services_response) > 0:
service_id = services_response[0]['id']
return self.run_test("Get Service Detail", "GET", f"services/{service_id}", 200)
return False
def test_cart_operations(self):
"""Test cart operations (requires authentication)"""
if not self.token:
self.log_test("Cart Operations", False, "No authentication token")
return False
# Get a product ID first
products_response = self.run_test("Get Products for Cart Test", "GET", "products", 200)
if not products_response or len(products_response) == 0:
self.log_test("Cart Operations", False, "No products available")
return False
product_id = products_response[0]['id']
# Test adding to cart
add_cart_data = {"product_id": product_id, "quantity": 2}
self.run_test("Add to Cart", "POST", "cart/add", 200, add_cart_data)
# Test getting cart
cart_response = self.run_test("Get Cart", "GET", "cart", 200)
# Test clearing cart
self.run_test("Clear Cart", "DELETE", "cart", 200)
return True
def test_contact_form(self):
"""Test contact form submission"""
contact_data = {
"name": "Test User",
"email": "test@example.com",
"subject": "Test Subject",
"message": "This is a test message from automated testing."
}
return self.run_test("Contact Form Submission", "POST", "contact", 200, contact_data)
def test_service_booking(self):
"""Test service booking"""
# First get a service ID
services_response = self.run_test("Get Services for Booking Test", "GET", "services", 200)
if not services_response or len(services_response) == 0:
self.log_test("Service Booking", False, "No services available")
return False
service_id = services_response[0]['id']
booking_data = {
"service_id": service_id,
"name": "Test Customer",
"email": "customer@example.com",
"phone": "+1234567890",
"preferred_date": "2024-12-25",
"notes": "Test booking from automated testing"
}
return self.run_test("Service Booking", "POST", "services/book", 200, booking_data)
def run_all_tests(self):
"""Run all API tests"""
print("🚀 Starting TechZone API Tests...")
print(f"📍 Testing against: {self.base_url}")
print("=" * 50)
# Test basic endpoints
self.test_root_endpoint()
self.test_seed_data()
# Test authentication
auth_success = self.test_user_registration()
if not auth_success:
# Try admin login if registration fails
auth_success = self.test_user_login()
if auth_success:
self.test_get_current_user()
# Test products
self.test_get_products()
self.test_get_products_with_filters()
self.test_get_product_detail()
self.test_get_categories()
# Test services
self.test_get_services()
self.test_get_services_with_filter()
self.test_get_service_detail()
# Test cart (requires auth)
if self.token:
self.test_cart_operations()
# Test contact form
self.test_contact_form()
# Test service booking
self.test_service_booking()
# Print summary
print("=" * 50)
print(f"📊 Tests completed: {self.tests_passed}/{self.tests_run}")
success_rate = (self.tests_passed / self.tests_run * 100) if self.tests_run > 0 else 0
print(f"📈 Success rate: {success_rate:.1f}%")
if self.tests_passed < self.tests_run:
print("\n❌ Failed tests:")
for result in self.test_results:
if not result['success']:
print(f" - {result['test']}: {result['details']}")
return self.tests_passed == self.tests_run
def main():
tester = TechZoneAPITester()
success = tester.run_all_tests()
return 0 if success else 1
if __name__ == "__main__":
sys.exit(main())

148
tests/test_api.html Normal file
View File

@@ -0,0 +1,148 @@
<!DOCTYPE html>
<html>
<head>
<title>Services API Direct Test</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1200px;
margin: 50px auto;
padding: 20px;
background: #f5f5f5;
}
.container {
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
h1 {
color: #333;
}
.status {
padding: 15px;
margin: 15px 0;
border-radius: 4px;
}
.success {
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
.error {
background: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.service-card {
border: 1px solid #ddd;
padding: 15px;
margin: 10px 0;
border-radius: 4px;
background: #fafafa;
}
button {
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background: #0056b3;
}
pre {
background: #f4f4f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
}
</style>
</head>
<body>
<div class="container">
<h1>🔧 Services API Direct Test</h1>
<p>This page directly tests if the backend services API is working.</p>
<button onclick="testAPI()">Test API Now</button>
<button onclick="location.href='http://localhost:5300/services'">
Go to Services Page
</button>
<div id="result"></div>
</div>
<script>
async function testAPI() {
const resultDiv = document.getElementById("result");
resultDiv.innerHTML = '<div class="status">Testing API...</div>';
try {
// Test 1: Backend Health
const healthResponse = await fetch(
"http://localhost:8181/api/health"
);
const healthData = await healthResponse.json();
// Test 2: Services API
const servicesResponse = await fetch(
"http://localhost:8181/api/services"
);
const servicesData = await servicesResponse.json();
// Display results
let html = `
<div class="status success">
<strong>✅ Backend API Working!</strong><br>
Health: ${healthData.status}<br>
Database: ${healthData.database}<br>
Services Found: ${servicesData.length}
</div>
<h3>Services Data:</h3>
`;
servicesData.forEach((service) => {
html += `
<div class="service-card">
<strong>${service.name}</strong> - $${
service.price
}<br>
<small>Category: ${service.category} | Duration: ${
service.duration
}</small><br>
<small style="color: #666;">${service.description.substring(
0,
100
)}</small>
</div>
`;
});
html += `
<h3>Raw Response:</h3>
<pre>${JSON.stringify(servicesData[0], null, 2)}</pre>
`;
resultDiv.innerHTML = html;
} catch (error) {
resultDiv.innerHTML = `
<div class="status error">
<strong>❌ Error:</strong><br>
${error.message}<br><br>
<strong>Possible causes:</strong><br>
- Backend not running on port 8181<br>
- CORS not configured<br>
- Network connectivity issue
</div>
`;
}
}
// Auto-test on load
window.onload = () => testAPI();
</script>
</body>
</html>