marketplace refactoring

This commit is contained in:
2025-10-04 13:38:10 +02:00
parent 32be301d83
commit c971674ec2
68 changed files with 1102 additions and 1128 deletions

Binary file not shown.

View File

@@ -8,8 +8,8 @@ from sqlalchemy.pool import StaticPool
from app.core.database import Base, get_db
from main import app
# Import all models to ensure they're registered with Base metadata
from models.database.marketplace import MarketplaceImportJob
from models.database.product import Product
from models.database.marketplace_import_job import MarketplaceImportJob
from models.database.marketplace_product import MarketplaceProduct
from models.database.shop import Shop, ShopProduct
from models.database.stock import Stock
from models.database.user import User
@@ -87,8 +87,8 @@ def cleanup():
# Import fixtures from fixture modules
pytest_plugins = [
"tests.fixtures.auth_fixtures",
"tests.fixtures.product_fixtures",
"tests.fixtures.marketplace_product_fixtures",
"tests.fixtures.shop_fixtures",
"tests.fixtures.marketplace_fixtures",
"tests.fixtures.marketplace_import_job_fixtures",
"tests.fixtures.testing_fixtures",
]

View File

@@ -1,11 +1,11 @@
# tests/fixtures/marketplace_fixtures.py
# tests/fixtures/marketplace_import_job_fixtures.py
import pytest
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
@pytest.fixture
def test_marketplace_job(db, test_shop, test_user):
def test_marketplace_import_job(db, test_shop, test_user):
"""Create a test marketplace import job"""
job = MarketplaceImportJob(
marketplace="amazon",
@@ -26,7 +26,7 @@ def test_marketplace_job(db, test_shop, test_user):
return job
def create_test_import_job(db, shop_id, user_id, **kwargs):
def create_test_marketplace_import_job(db, shop_id, user_id, **kwargs):
"""Helper function to create MarketplaceImportJob with defaults"""
defaults = {
"marketplace": "test",

View File

@@ -1,17 +1,17 @@
# tests/fixtures/product_fixtures.py
# tests/fixtures/marketplace_product_fixtures.py
import uuid
import pytest
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
@pytest.fixture
def test_product(db):
def test_marketplace_product(db):
"""Create a test product"""
product = Product(
product_id="TEST001",
title="Test Product",
marketplace_product = MarketplaceProduct(
marketplace_product_id="TEST001",
title="Test MarketplaceProduct",
description="A test product",
price="10.99",
currency="EUR",
@@ -21,19 +21,19 @@ def test_product(db):
marketplace="Letzshop",
shop_name="TestShop",
)
db.add(product)
db.add(marketplace_product)
db.commit()
db.refresh(product)
return product
db.refresh(marketplace_product)
return marketplace_product
@pytest.fixture
def unique_product(db):
"""Create a unique product for tests that need isolated product data"""
unique_id = str(uuid.uuid4())[:8]
product = Product(
product_id=f"UNIQUE_{unique_id}",
title=f"Unique Product {unique_id}",
marketplace_product = MarketplaceProduct(
marketplace_product_id=f"UNIQUE_{unique_id}",
title=f"Unique MarketplaceProduct {unique_id}",
description=f"A unique test product {unique_id}",
price="19.99",
currency="EUR",
@@ -44,22 +44,22 @@ def unique_product(db):
shop_name=f"UniqueShop_{unique_id}",
google_product_category=f"UniqueCategory_{unique_id}",
)
db.add(product)
db.add(marketplace_product)
db.commit()
db.refresh(product)
return product
db.refresh(marketplace_product)
return marketplace_product
@pytest.fixture
def multiple_products(db):
"""Create multiple products for testing statistics and pagination"""
unique_id = str(uuid.uuid4())[:8]
products = []
marketplace_products = []
for i in range(5):
product = Product(
product_id=f"MULTI_{unique_id}_{i}",
title=f"Multi Product {i} {unique_id}",
marketplace_product = MarketplaceProduct(
marketplace_product_id=f"MULTI_{unique_id}_{i}",
title=f"Multi MarketplaceProduct {i} {unique_id}",
description=f"Multi test product {i}",
price=f"{10 + i}.99",
currency="EUR",
@@ -69,23 +69,23 @@ def multiple_products(db):
google_product_category=f"MultiCategory_{i % 2}", # Create 2 different categories
gtin=f"1234567890{i}{unique_id[:2]}",
)
products.append(product)
marketplace_products.append(marketplace_product)
db.add_all(products)
db.add_all(marketplace_products)
db.commit()
for product in products:
for product in marketplace_products:
db.refresh(product)
return products
return marketplace_products
def create_unique_product_factory():
def create_unique_marketplace_product_factory():
"""Factory function to create unique products in tests"""
def _create_product(db, **kwargs):
def _marketplace_create_product(db, **kwargs):
unique_id = str(uuid.uuid4())[:8]
defaults = {
"product_id": f"FACTORY_{unique_id}",
"title": f"Factory Product {unique_id}",
"marketplace_product_id": f"FACTORY_{unique_id}",
"title": f"Factory MarketplaceProduct {unique_id}",
"price": "15.99",
"currency": "EUR",
"marketplace": "TestMarket",
@@ -93,31 +93,31 @@ def create_unique_product_factory():
}
defaults.update(kwargs)
product = Product(**defaults)
db.add(product)
marketplace_product = MarketplaceProduct(**defaults)
db.add(marketplace_product)
db.commit()
db.refresh(product)
return product
db.refresh(marketplace_product)
return marketplace_product
return _create_product
return _marketplace_create_product
@pytest.fixture
def product_factory():
def marketplace_product_factory():
"""Fixture that provides a product factory function"""
return create_unique_product_factory()
return create_unique_marketplace_product_factory()
@pytest.fixture
def test_product_with_stock(db, test_product, test_stock):
"""Product with associated stock record."""
def test_marketplace_product_with_stock(db, test_marketplace_product, test_stock):
"""MarketplaceProduct with associated stock record."""
# Ensure they're linked by GTIN
if test_product.gtin != test_stock.gtin:
test_stock.gtin = test_product.gtin
if test_marketplace_product.gtin != test_stock.gtin:
test_stock.gtin = test_marketplace_product.gtin
db.commit()
db.refresh(test_stock)
return {
'product': test_product,
'marketplace_product': test_marketplace_product,
'stock': test_stock
}

View File

@@ -80,7 +80,7 @@ def verified_shop(db, other_user):
def shop_product(db, test_shop, unique_product):
"""Create a shop product relationship"""
shop_product = ShopProduct(
shop_id=test_shop.id, product_id=unique_product.id, is_active=True
shop_id=test_shop.id, marketplace_product_id=unique_product.id, is_active=True
)
# Add optional fields if they exist in your model
if hasattr(ShopProduct, "shop_price"):
@@ -97,11 +97,11 @@ def shop_product(db, test_shop, unique_product):
@pytest.fixture
def test_stock(db, test_product, test_shop):
def test_stock(db, test_marketplace_product, test_shop):
"""Create test stock entry"""
unique_id = str(uuid.uuid4())[:8].upper() # Short unique identifier
stock = Stock(
gtin=test_product.gtin, # Use gtin instead of product_id
gtin=test_marketplace_product.gtin, # Use gtin instead of marketplace_product_id
location=f"WAREHOUSE_A_{unique_id}",
quantity=10,
reserved_quantity=0,

View File

@@ -137,7 +137,7 @@ class TestAdminAPI:
assert data["error_code"] == "SHOP_NOT_FOUND"
def test_get_marketplace_import_jobs_admin(
self, client, admin_headers, test_marketplace_job
self, client, admin_headers, test_marketplace_import_job
):
"""Test admin getting marketplace import jobs"""
response = client.get(
@@ -148,17 +148,17 @@ class TestAdminAPI:
data = response.json()
assert len(data) >= 1
# Check that test_marketplace_job is in the response
# Check that test_marketplace_import_job is in the response
job_ids = [job["job_id"] for job in data if "job_id" in job]
assert test_marketplace_job.id in job_ids
assert test_marketplace_import_job.id in job_ids
def test_get_marketplace_import_jobs_with_filters(
self, client, admin_headers, test_marketplace_job
self, client, admin_headers, test_marketplace_import_job
):
"""Test admin getting marketplace import jobs with filters"""
response = client.get(
"/api/v1/admin/marketplace-import-jobs",
params={"marketplace": test_marketplace_job.marketplace},
params={"marketplace": test_marketplace_import_job.marketplace},
headers=admin_headers,
)
@@ -166,7 +166,7 @@ class TestAdminAPI:
data = response.json()
assert len(data) >= 1
assert all(
job["marketplace"] == test_marketplace_job.marketplace for job in data
job["marketplace"] == test_marketplace_import_job.marketplace for job in data
)
def test_get_marketplace_import_jobs_non_admin(self, client, auth_headers):

View File

@@ -1,12 +1,13 @@
# tests/integration/api/v1/test_filtering.py
import pytest
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.products
@pytest.mark.marketplace
class TestFiltering:
def test_product_brand_filter_success(self, client, auth_headers, db):
@@ -16,27 +17,27 @@ class TestFiltering:
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(product_id=f"BRAND1_{unique_suffix}", title="Product 1", brand="BrandA"),
Product(product_id=f"BRAND2_{unique_suffix}", title="Product 2", brand="BrandB"),
Product(product_id=f"BRAND3_{unique_suffix}", title="Product 3", brand="BrandA"),
MarketplaceProduct(marketplace_product_id=f"BRAND1_{unique_suffix}", title="MarketplaceProduct 1", brand="BrandA"),
MarketplaceProduct(marketplace_product_id=f"BRAND2_{unique_suffix}", title="MarketplaceProduct 2", brand="BrandB"),
MarketplaceProduct(marketplace_product_id=f"BRAND3_{unique_suffix}", title="MarketplaceProduct 3", brand="BrandA"),
]
db.add_all(products)
db.commit()
# Filter by BrandA
response = client.get("/api/v1/product?brand=BrandA", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?brand=BrandA", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 2 # At least our test products
# Verify all returned products have BrandA
for product in data["products"]:
if product["product_id"].endswith(unique_suffix):
if product["marketplace_product_id"].endswith(unique_suffix):
assert product["brand"] == "BrandA"
# Filter by BrandB
response = client.get("/api/v1/product?brand=BrandB", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?brand=BrandB", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 1 # At least our test product
@@ -47,21 +48,21 @@ class TestFiltering:
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(product_id=f"MKT1_{unique_suffix}", title="Product 1", marketplace="Amazon"),
Product(product_id=f"MKT2_{unique_suffix}", title="Product 2", marketplace="eBay"),
Product(product_id=f"MKT3_{unique_suffix}", title="Product 3", marketplace="Amazon"),
MarketplaceProduct(marketplace_product_id=f"MKT1_{unique_suffix}", title="MarketplaceProduct 1", marketplace="Amazon"),
MarketplaceProduct(marketplace_product_id=f"MKT2_{unique_suffix}", title="MarketplaceProduct 2", marketplace="eBay"),
MarketplaceProduct(marketplace_product_id=f"MKT3_{unique_suffix}", title="MarketplaceProduct 3", marketplace="Amazon"),
]
db.add_all(products)
db.commit()
response = client.get("/api/v1/product?marketplace=Amazon", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?marketplace=Amazon", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 2 # At least our test products
# Verify all returned products have Amazon marketplace
amazon_products = [p for p in data["products"] if p["product_id"].endswith(unique_suffix)]
amazon_products = [p for p in data["products"] if p["marketplace_product_id"].endswith(unique_suffix)]
for product in amazon_products:
assert product["marketplace"] == "Amazon"
@@ -71,18 +72,18 @@ class TestFiltering:
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(
product_id=f"SEARCH1_{unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"SEARCH1_{unique_suffix}",
title=f"Apple iPhone {unique_suffix}",
description="Smartphone"
),
Product(
product_id=f"SEARCH2_{unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"SEARCH2_{unique_suffix}",
title=f"Samsung Galaxy {unique_suffix}",
description="Android phone",
),
Product(
product_id=f"SEARCH3_{unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"SEARCH3_{unique_suffix}",
title=f"iPad Tablet {unique_suffix}",
description="Apple tablet"
),
@@ -92,13 +93,13 @@ class TestFiltering:
db.commit()
# Search for "Apple"
response = client.get(f"/api/v1/product?search=Apple", headers=auth_headers)
response = client.get(f"/api/v1/marketplace/product?search=Apple", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 2 # iPhone and iPad
# Search for "phone"
response = client.get(f"/api/v1/product?search=phone", headers=auth_headers)
response = client.get(f"/api/v1/marketplace/product?search=phone", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 2 # iPhone and Galaxy
@@ -109,20 +110,20 @@ class TestFiltering:
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(
product_id=f"COMBO1_{unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"COMBO1_{unique_suffix}",
title=f"Apple iPhone {unique_suffix}",
brand="Apple",
marketplace="Amazon",
),
Product(
product_id=f"COMBO2_{unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"COMBO2_{unique_suffix}",
title=f"Apple iPad {unique_suffix}",
brand="Apple",
marketplace="eBay",
),
Product(
product_id=f"COMBO3_{unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"COMBO3_{unique_suffix}",
title=f"Samsung Phone {unique_suffix}",
brand="Samsung",
marketplace="Amazon",
@@ -134,14 +135,14 @@ class TestFiltering:
# Filter by brand AND marketplace
response = client.get(
"/api/v1/product?brand=Apple&marketplace=Amazon", headers=auth_headers
"/api/v1/marketplace/product?brand=Apple&marketplace=Amazon", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 1 # At least iPhone matches both
# Find our specific test product
matching_products = [p for p in data["products"] if p["product_id"].endswith(unique_suffix)]
matching_products = [p for p in data["products"] if p["marketplace_product_id"].endswith(unique_suffix)]
for product in matching_products:
assert product["brand"] == "Apple"
assert product["marketplace"] == "Amazon"
@@ -149,7 +150,7 @@ class TestFiltering:
def test_filter_with_no_results(self, client, auth_headers):
"""Test filtering with criteria that returns no results"""
response = client.get(
"/api/v1/product?brand=NonexistentBrand123456", headers=auth_headers
"/api/v1/marketplace/product?brand=NonexistentBrand123456", headers=auth_headers
)
assert response.status_code == 200
@@ -162,9 +163,9 @@ class TestFiltering:
import uuid
unique_suffix = str(uuid.uuid4())[:8]
product = Product(
product_id=f"CASE_{unique_suffix}",
title="Test Product",
product = MarketplaceProduct(
marketplace_product_id=f"CASE_{unique_suffix}",
title="Test MarketplaceProduct",
brand="TestBrand",
marketplace="TestMarket",
)
@@ -173,7 +174,7 @@ class TestFiltering:
# Test different case variations
for brand_filter in ["TestBrand", "testbrand", "TESTBRAND"]:
response = client.get(f"/api/v1/product?brand={brand_filter}", headers=auth_headers)
response = client.get(f"/api/v1/marketplace/product?brand={brand_filter}", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 1
@@ -182,9 +183,9 @@ class TestFiltering:
"""Test behavior with invalid filter parameters"""
# Test with very long filter values
long_brand = "A" * 1000
response = client.get(f"/api/v1/product?brand={long_brand}", headers=auth_headers)
response = client.get(f"/api/v1/marketplace/product?brand={long_brand}", headers=auth_headers)
assert response.status_code == 200 # Should handle gracefully
# Test with special characters
response = client.get("/api/v1/product?brand=<script>alert('test')</script>", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?brand=<script>alert('test')</script>", headers=auth_headers)
assert response.status_code == 200 # Should handle gracefully

View File

@@ -1,4 +1,4 @@
# tests/integration/api/v1/test_marketplace_endpoints.py
# tests/integration/api/v1/test_marketplace_import_job_endpoints.py
from unittest.mock import AsyncMock, patch
import pytest
@@ -7,7 +7,7 @@ import pytest
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.marketplace
class TestMarketplaceAPI:
class TestMarketplaceImportJobAPI:
def test_import_from_marketplace(self, client, auth_headers, test_shop, test_user):
"""Test marketplace import endpoint - just test job creation"""
# Ensure user owns the shop
@@ -102,18 +102,18 @@ class TestMarketplaceAPI:
assert data["marketplace"] == "AdminMarket"
assert data["shop_code"] == test_shop.shop_code
def test_get_marketplace_import_status(self, client, auth_headers, test_marketplace_job):
def test_get_marketplace_import_status(self, client, auth_headers, test_marketplace_import_job):
"""Test getting marketplace import status"""
response = client.get(
f"/api/v1/marketplace/import-status/{test_marketplace_job.id}",
f"/api/v1/marketplace/import-status/{test_marketplace_import_job.id}",
headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert data["job_id"] == test_marketplace_job.id
assert data["status"] == test_marketplace_job.status
assert data["marketplace"] == test_marketplace_job.marketplace
assert data["job_id"] == test_marketplace_import_job.id
assert data["status"] == test_marketplace_import_job.status
assert data["marketplace"] == test_marketplace_import_job.marketplace
def test_get_marketplace_import_status_not_found(self, client, auth_headers):
"""Test getting status of non-existent import job"""
@@ -127,13 +127,13 @@ class TestMarketplaceAPI:
assert data["error_code"] == "IMPORT_JOB_NOT_FOUND"
assert "99999" in data["message"]
def test_get_marketplace_import_status_unauthorized(self, client, auth_headers, test_marketplace_job, other_user):
def test_get_marketplace_import_status_unauthorized(self, client, auth_headers, test_marketplace_import_job, other_user):
"""Test getting status of unauthorized import job"""
# Change job owner to other user
test_marketplace_job.user_id = other_user.id
test_marketplace_import_job.user_id = other_user.id
response = client.get(
f"/api/v1/marketplace/import-status/{test_marketplace_job.id}",
f"/api/v1/marketplace/import-status/{test_marketplace_import_job.id}",
headers=auth_headers
)
@@ -141,7 +141,7 @@ class TestMarketplaceAPI:
data = response.json()
assert data["error_code"] == "IMPORT_JOB_NOT_OWNED"
def test_get_marketplace_import_jobs(self, client, auth_headers, test_marketplace_job):
def test_get_marketplace_import_jobs(self, client, auth_headers, test_marketplace_import_job):
"""Test getting marketplace import jobs"""
response = client.get("/api/v1/marketplace/import-jobs", headers=auth_headers)
@@ -152,12 +152,12 @@ class TestMarketplaceAPI:
# Find our test job in the results
job_ids = [job["job_id"] for job in data]
assert test_marketplace_job.id in job_ids
assert test_marketplace_import_job.id in job_ids
def test_get_marketplace_import_jobs_with_filters(self, client, auth_headers, test_marketplace_job):
def test_get_marketplace_import_jobs_with_filters(self, client, auth_headers, test_marketplace_import_job):
"""Test getting import jobs with filters"""
response = client.get(
f"/api/v1/marketplace/import-jobs?marketplace={test_marketplace_job.marketplace}",
f"/api/v1/marketplace/import-jobs?marketplace={test_marketplace_import_job.marketplace}",
headers=auth_headers
)
@@ -167,7 +167,7 @@ class TestMarketplaceAPI:
assert len(data) >= 1
for job in data:
assert test_marketplace_job.marketplace.lower() in job["marketplace"].lower()
assert test_marketplace_import_job.marketplace.lower() in job["marketplace"].lower()
def test_get_marketplace_import_jobs_pagination(self, client, auth_headers):
"""Test import jobs pagination"""
@@ -181,7 +181,7 @@ class TestMarketplaceAPI:
assert isinstance(data, list)
assert len(data) <= 5
def test_get_marketplace_import_stats(self, client, auth_headers, test_marketplace_job):
def test_get_marketplace_import_stats(self, client, auth_headers, test_marketplace_import_job):
"""Test getting marketplace import statistics"""
response = client.get("/api/v1/marketplace/marketplace-import-stats", headers=auth_headers)
@@ -198,7 +198,7 @@ class TestMarketplaceAPI:
def test_cancel_marketplace_import_job(self, client, auth_headers, test_user, test_shop, db):
"""Test cancelling a marketplace import job"""
# Create a pending job that can be cancelled
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
import uuid
unique_id = str(uuid.uuid4())[:8]
@@ -240,14 +240,14 @@ class TestMarketplaceAPI:
data = response.json()
assert data["error_code"] == "IMPORT_JOB_NOT_FOUND"
def test_cancel_marketplace_import_job_cannot_cancel(self, client, auth_headers, test_marketplace_job, db):
def test_cancel_marketplace_import_job_cannot_cancel(self, client, auth_headers, test_marketplace_import_job, db):
"""Test cancelling a job that cannot be cancelled"""
# Set job to completed status
test_marketplace_job.status = "completed"
test_marketplace_import_job.status = "completed"
db.commit()
response = client.put(
f"/api/v1/marketplace/import-jobs/{test_marketplace_job.id}/cancel",
f"/api/v1/marketplace/import-jobs/{test_marketplace_import_job.id}/cancel",
headers=auth_headers
)
@@ -259,7 +259,7 @@ class TestMarketplaceAPI:
def test_delete_marketplace_import_job(self, client, auth_headers, test_user, test_shop, db):
"""Test deleting a marketplace import job"""
# Create a completed job that can be deleted
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
import uuid
unique_id = str(uuid.uuid4())[:8]
@@ -302,7 +302,7 @@ class TestMarketplaceAPI:
def test_delete_marketplace_import_job_cannot_delete(self, client, auth_headers, test_user, test_shop, db):
"""Test deleting a job that cannot be deleted"""
# Create a pending job that cannot be deleted
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
import uuid
unique_id = str(uuid.uuid4())[:8]
@@ -352,7 +352,7 @@ class TestMarketplaceAPI:
data = response.json()
assert data["error_code"] == "INVALID_TOKEN"
def test_admin_can_access_all_jobs(self, client, admin_headers, test_marketplace_job):
def test_admin_can_access_all_jobs(self, client, admin_headers, test_marketplace_import_job):
"""Test that admin can access all import jobs"""
response = client.get("/api/v1/marketplace/import-jobs", headers=admin_headers)
@@ -361,23 +361,23 @@ class TestMarketplaceAPI:
assert isinstance(data, list)
# Admin should see all jobs, including the test job
job_ids = [job["job_id"] for job in data]
assert test_marketplace_job.id in job_ids
assert test_marketplace_import_job.id in job_ids
def test_admin_can_view_any_job_status(self, client, admin_headers, test_marketplace_job):
def test_admin_can_view_any_job_status(self, client, admin_headers, test_marketplace_import_job):
"""Test that admin can view any job status"""
response = client.get(
f"/api/v1/marketplace/import-status/{test_marketplace_job.id}",
f"/api/v1/marketplace/import-status/{test_marketplace_import_job.id}",
headers=admin_headers
)
assert response.status_code == 200
data = response.json()
assert data["job_id"] == test_marketplace_job.id
assert data["job_id"] == test_marketplace_import_job.id
def test_admin_can_cancel_any_job(self, client, admin_headers, test_user, test_shop, db):
"""Test that admin can cancel any job"""
# Create a pending job owned by different user
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
import uuid
unique_id = str(uuid.uuid4())[:8]

View File

@@ -5,7 +5,7 @@ import uuid
import pytest
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
@pytest.mark.integration
@@ -13,9 +13,9 @@ from models.database.product import Product
@pytest.mark.performance # for the performance test
class TestExportFunctionality:
def test_csv_export_basic_success(self, client, auth_headers, test_product):
def test_csv_export_basic_success(self, client, auth_headers, test_marketplace_product):
"""Test basic CSV export functionality successfully"""
response = client.get("/api/v1/product/export-csv", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/export-csv", headers=auth_headers)
assert response.status_code == 200
assert response.headers["content-type"] == "text/csv; charset=utf-8"
@@ -26,13 +26,13 @@ class TestExportFunctionality:
# Check header row
header = next(csv_reader)
expected_fields = ["product_id", "title", "description", "price", "marketplace"]
expected_fields = ["marketplace_product_id", "title", "description", "price", "marketplace"]
for field in expected_fields:
assert field in header
# Verify test product appears in export
csv_lines = csv_content.split('\n')
test_product_found = any(test_product.product_id in line for line in csv_lines)
test_product_found = any(test_marketplace_product.marketplace_product_id in line for line in csv_lines)
assert test_product_found, "Test product should appear in CSV export"
def test_csv_export_with_marketplace_filter_success(self, client, auth_headers, db):
@@ -40,14 +40,14 @@ class TestExportFunctionality:
# Create products in different marketplaces with unique IDs
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(
product_id=f"EXP1_{unique_suffix}",
title=f"Amazon Product {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"EXP1_{unique_suffix}",
title=f"Amazon MarketplaceProduct {unique_suffix}",
marketplace="Amazon"
),
Product(
product_id=f"EXP2_{unique_suffix}",
title=f"eBay Product {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"EXP2_{unique_suffix}",
title=f"eBay MarketplaceProduct {unique_suffix}",
marketplace="eBay"
),
]
@@ -56,7 +56,7 @@ class TestExportFunctionality:
db.commit()
response = client.get(
"/api/v1/product/export-csv?marketplace=Amazon", headers=auth_headers
"/api/v1/marketplace/product/export-csv?marketplace=Amazon", headers=auth_headers
)
assert response.status_code == 200
assert response.headers["content-type"] == "text/csv; charset=utf-8"
@@ -69,14 +69,14 @@ class TestExportFunctionality:
"""Test CSV export with shop name filtering successfully"""
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(
product_id=f"SHOP1_{unique_suffix}",
title=f"Shop1 Product {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"SHOP1_{unique_suffix}",
title=f"Shop1 MarketplaceProduct {unique_suffix}",
shop_name="TestShop1"
),
Product(
product_id=f"SHOP2_{unique_suffix}",
title=f"Shop2 Product {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"SHOP2_{unique_suffix}",
title=f"Shop2 MarketplaceProduct {unique_suffix}",
shop_name="TestShop2"
),
]
@@ -85,7 +85,7 @@ class TestExportFunctionality:
db.commit()
response = client.get(
"/api/v1/product/export-csv?shop_name=TestShop1", headers=auth_headers
"/api/v1/marketplace/product?shop_name=TestShop1", headers=auth_headers
)
assert response.status_code == 200
@@ -97,21 +97,21 @@ class TestExportFunctionality:
"""Test CSV export with combined marketplace and shop filters successfully"""
unique_suffix = str(uuid.uuid4())[:8]
products = [
Product(
product_id=f"COMBO1_{unique_suffix}",
title=f"Combo Product 1 {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"COMBO1_{unique_suffix}",
title=f"Combo MarketplaceProduct 1 {unique_suffix}",
marketplace="Amazon",
shop_name="TestShop"
),
Product(
product_id=f"COMBO2_{unique_suffix}",
title=f"Combo Product 2 {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"COMBO2_{unique_suffix}",
title=f"Combo MarketplaceProduct 2 {unique_suffix}",
marketplace="eBay",
shop_name="TestShop"
),
Product(
product_id=f"COMBO3_{unique_suffix}",
title=f"Combo Product 3 {unique_suffix}",
MarketplaceProduct(
marketplace_product_id=f"COMBO3_{unique_suffix}",
title=f"Combo MarketplaceProduct 3 {unique_suffix}",
marketplace="Amazon",
shop_name="OtherShop"
),
@@ -121,7 +121,7 @@ class TestExportFunctionality:
db.commit()
response = client.get(
"/api/v1/product/export-csv?marketplace=Amazon&shop_name=TestShop",
"/api/v1/marketplace/product?marketplace=Amazon&shop_name=TestShop",
headers=auth_headers
)
assert response.status_code == 200
@@ -134,7 +134,7 @@ class TestExportFunctionality:
def test_csv_export_no_results(self, client, auth_headers):
"""Test CSV export with filters that return no results"""
response = client.get(
"/api/v1/product/export-csv?marketplace=NonexistentMarketplace12345",
"/api/v1/marketplace/product/export-csv?marketplace=NonexistentMarketplace12345",
headers=auth_headers
)
@@ -146,7 +146,7 @@ class TestExportFunctionality:
# Should have header row even with no data
assert len(csv_lines) >= 1
# First line should be headers
assert "product_id" in csv_lines[0]
assert "marketplace_product_id" in csv_lines[0]
def test_csv_export_performance_large_dataset(self, client, auth_headers, db):
"""Test CSV export performance with many products"""
@@ -156,9 +156,9 @@ class TestExportFunctionality:
products = []
batch_size = 100 # Reduced from 1000 for faster test execution
for i in range(batch_size):
product = Product(
product_id=f"PERF{i:04d}_{unique_suffix}",
title=f"Performance Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"PERF{i:04d}_{unique_suffix}",
title=f"Performance MarketplaceProduct {i}",
marketplace="Performance",
description=f"Performance test product {i}",
price="10.99"
@@ -174,7 +174,7 @@ class TestExportFunctionality:
import time
start_time = time.time()
response = client.get("/api/v1/product/export-csv", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/export-csv", headers=auth_headers)
end_time = time.time()
execution_time = end_time - start_time
@@ -186,20 +186,20 @@ class TestExportFunctionality:
# Verify content contains our test data
csv_content = response.content.decode("utf-8")
assert f"PERF0000_{unique_suffix}" in csv_content
assert "Performance Product" in csv_content
assert "Performance MarketplaceProduct" in csv_content
def test_csv_export_without_auth_returns_invalid_token(self, client):
"""Test that CSV export requires authentication returns InvalidTokenException"""
response = client.get("/api/v1/product/export-csv")
response = client.get("/api/v1/marketplace/product")
assert response.status_code == 401
data = response.json()
assert data["error_code"] == "INVALID_TOKEN"
assert data["status_code"] == 401
def test_csv_export_streaming_response_format(self, client, auth_headers, test_product):
def test_csv_export_streaming_response_format(self, client, auth_headers, test_marketplace_product):
"""Test that CSV export returns proper streaming response with correct headers"""
response = client.get("/api/v1/product/export-csv", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/export-csv", headers=auth_headers)
assert response.status_code == 200
assert response.headers["content-type"] == "text/csv; charset=utf-8"
@@ -215,9 +215,9 @@ class TestExportFunctionality:
unique_suffix = str(uuid.uuid4())[:8]
# Create product with special characters that might break CSV
product = Product(
product_id=f"SPECIAL_{unique_suffix}",
title=f'Product with quotes and commas {unique_suffix}', # Simplified to avoid CSV escaping issues
product = MarketplaceProduct(
marketplace_product_id=f"SPECIAL_{unique_suffix}",
title=f'MarketplaceProduct with quotes and commas {unique_suffix}', # Simplified to avoid CSV escaping issues
description=f"Description with special chars {unique_suffix}",
marketplace="Test Market",
price="19.99"
@@ -226,14 +226,14 @@ class TestExportFunctionality:
db.add(product)
db.commit()
response = client.get("/api/v1/product/export-csv", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/export-csv", headers=auth_headers)
assert response.status_code == 200
csv_content = response.content.decode("utf-8")
# Verify our test product appears in the CSV content
assert f"SPECIAL_{unique_suffix}" in csv_content
assert f"Product with quotes and commas {unique_suffix}" in csv_content
assert f"MarketplaceProduct with quotes and commas {unique_suffix}" in csv_content
assert "Test Market" in csv_content
assert "19.99" in csv_content
@@ -243,7 +243,7 @@ class TestExportFunctionality:
header = next(csv_reader)
# Verify header contains expected fields
expected_fields = ["product_id", "title", "marketplace", "price"]
expected_fields = ["marketplace_product_id", "title", "marketplace", "price"]
for field in expected_fields:
assert field in header
@@ -274,7 +274,7 @@ class TestExportFunctionality:
# This would require access to your service instance to mock properly
# For now, we test that the endpoint structure supports error handling
response = client.get("/api/v1/product/export-csv", headers=auth_headers)
response = client.get("/api/v1/marketplace/product", headers=auth_headers)
# Should either succeed or return proper error response
assert response.status_code in [200, 400, 500]
@@ -293,7 +293,7 @@ class TestExportFunctionality:
def test_csv_export_filename_generation(self, client, auth_headers):
"""Test CSV export generates appropriate filenames based on filters"""
# Test basic export filename
response = client.get("/api/v1/product/export-csv", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/export-csv", headers=auth_headers)
assert response.status_code == 200
content_disposition = response.headers.get("content-disposition", "")
@@ -301,7 +301,7 @@ class TestExportFunctionality:
# Test with marketplace filter
response = client.get(
"/api/v1/product/export-csv?marketplace=Amazon",
"/api/v1/marketplace/product/export-csv?marketplace=Amazon",
headers=auth_headers
)
assert response.status_code == 200

View File

@@ -1,49 +1,49 @@
# tests/integration/api/v1/test_product_endpoints.py
# tests/integration/api/v1/test_marketplace_products_endpoints.py
import pytest
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.products
class TestProductsAPI:
class TestMarketplaceProductsAPI:
def test_get_products_empty(self, client, auth_headers):
"""Test getting products when none exist"""
response = client.get("/api/v1/product", headers=auth_headers)
response = client.get("/api/v1/marketplace/product", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["products"] == []
assert data["total"] == 0
def test_get_products_with_data(self, client, auth_headers, test_product):
def test_get_products_with_data(self, client, auth_headers, test_marketplace_product):
"""Test getting products with data"""
response = client.get("/api/v1/product", headers=auth_headers)
response = client.get("/api/v1/marketplace/product", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert len(data["products"]) >= 1
assert data["total"] >= 1
# Find our test product
test_product_found = any(p["product_id"] == test_product.product_id for p in data["products"])
test_product_found = any(p["marketplace_product_id"] == test_marketplace_product.marketplace_product_id for p in data["products"])
assert test_product_found
def test_get_products_with_filters(self, client, auth_headers, test_product):
def test_get_products_with_filters(self, client, auth_headers, test_marketplace_product):
"""Test filtering products"""
# Test brand filter
response = client.get(f"/api/v1/product?brand={test_product.brand}", headers=auth_headers)
response = client.get(f"/api/v1/marketplace/product?brand={test_marketplace_product.brand}", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 1
# Test marketplace filter
response = client.get(f"/api/v1/product?marketplace={test_product.marketplace}", headers=auth_headers)
response = client.get(f"/api/v1/marketplace/product?marketplace={test_marketplace_product.marketplace}", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 1
# Test search
response = client.get("/api/v1/product?search=Test", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?search=Test", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert data["total"] >= 1
@@ -51,8 +51,8 @@ class TestProductsAPI:
def test_create_product_success(self, client, auth_headers):
"""Test creating a new product successfully"""
product_data = {
"product_id": "NEW001",
"title": "New Product",
"marketplace_product_id": "NEW001",
"title": "New MarketplaceProduct",
"description": "A new product",
"price": "15.99",
"brand": "NewBrand",
@@ -62,19 +62,19 @@ class TestProductsAPI:
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 200
data = response.json()
assert data["product_id"] == "NEW001"
assert data["title"] == "New Product"
assert data["marketplace_product_id"] == "NEW001"
assert data["title"] == "New MarketplaceProduct"
assert data["marketplace"] == "Amazon"
def test_create_product_duplicate_id_returns_conflict(self, client, auth_headers, test_product):
"""Test creating product with duplicate ID returns ProductAlreadyExistsException"""
def test_create_product_duplicate_id_returns_conflict(self, client, auth_headers, test_marketplace_product):
"""Test creating product with duplicate ID returns MarketplaceProductAlreadyExistsException"""
product_data = {
"product_id": test_product.product_id,
"marketplace_product_id": test_marketplace_product.marketplace_product_id,
"title": "Different Title",
"description": "A new product",
"price": "15.99",
@@ -85,65 +85,65 @@ class TestProductsAPI:
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 409
data = response.json()
assert data["error_code"] == "PRODUCT_ALREADY_EXISTS"
assert data["status_code"] == 409
assert test_product.product_id in data["message"]
assert data["details"]["product_id"] == test_product.product_id
assert test_marketplace_product.marketplace_product_id in data["message"]
assert data["details"]["marketplace_product_id"] == test_marketplace_product.marketplace_product_id
def test_create_product_missing_title_validation_error(self, client, auth_headers):
"""Test creating product without title returns ValidationException"""
product_data = {
"product_id": "VALID001",
"marketplace_product_id": "VALID001",
"title": "", # Empty title
"price": "15.99",
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 422 # Pydantic validation error
data = response.json()
assert data["error_code"] == "PRODUCT_VALIDATION_FAILED"
assert data["status_code"] == 422
assert "Product title is required" in data["message"]
assert "MarketplaceProduct title is required" in data["message"]
assert data["details"]["field"] == "title"
def test_create_product_missing_product_id_validation_error(self, client, auth_headers):
"""Test creating product without product_id returns ValidationException"""
"""Test creating product without marketplace_product_id returns ValidationException"""
product_data = {
"product_id": "", # Empty product ID
"marketplace_product_id": "", # Empty product ID
"title": "Valid Title",
"price": "15.99",
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 422
data = response.json()
assert data["error_code"] == "PRODUCT_VALIDATION_FAILED"
assert data["status_code"] == 422
assert "Product ID is required" in data["message"]
assert data["details"]["field"] == "product_id"
assert "MarketplaceProduct ID is required" in data["message"]
assert data["details"]["field"] == "marketplace_product_id"
def test_create_product_invalid_gtin_data_error(self, client, auth_headers):
"""Test creating product with invalid GTIN returns InvalidProductDataException"""
"""Test creating product with invalid GTIN returns InvalidMarketplaceProductDataException"""
product_data = {
"product_id": "GTIN001",
"title": "GTIN Test Product",
"marketplace_product_id": "GTIN001",
"title": "GTIN Test MarketplaceProduct",
"price": "15.99",
"gtin": "invalid_gtin",
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 422
@@ -154,15 +154,15 @@ class TestProductsAPI:
assert data["details"]["field"] == "gtin"
def test_create_product_invalid_price_data_error(self, client, auth_headers):
"""Test creating product with invalid price returns InvalidProductDataException"""
"""Test creating product with invalid price returns InvalidMarketplaceProductDataException"""
product_data = {
"product_id": "PRICE001",
"title": "Price Test Product",
"marketplace_product_id": "PRICE001",
"title": "Price Test MarketplaceProduct",
"price": "invalid_price",
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 422
@@ -181,7 +181,7 @@ class TestProductsAPI:
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 422
@@ -191,50 +191,50 @@ class TestProductsAPI:
assert "Request validation failed" in data["message"]
assert "validation_errors" in data["details"]
def test_get_product_by_id_success(self, client, auth_headers, test_product):
def test_get_product_by_id_success(self, client, auth_headers, test_marketplace_product):
"""Test getting specific product successfully"""
response = client.get(
f"/api/v1/product/{test_product.product_id}", headers=auth_headers
f"/api/v1/marketplace/product/{test_marketplace_product.marketplace_product_id}", headers=auth_headers
)
assert response.status_code == 200
data = response.json()
assert data["product"]["product_id"] == test_product.product_id
assert data["product"]["title"] == test_product.title
assert data["product"]["marketplace_product_id"] == test_marketplace_product.marketplace_product_id
assert data["product"]["title"] == test_marketplace_product.title
def test_get_nonexistent_product_returns_not_found(self, client, auth_headers):
"""Test getting nonexistent product returns ProductNotFoundException"""
response = client.get("/api/v1/product/NONEXISTENT", headers=auth_headers)
"""Test getting nonexistent product returns MarketplaceProductNotFoundException"""
response = client.get("/api/v1/marketplace/product/NONEXISTENT", headers=auth_headers)
assert response.status_code == 404
data = response.json()
assert data["error_code"] == "PRODUCT_NOT_FOUND"
assert data["status_code"] == 404
assert "NONEXISTENT" in data["message"]
assert data["details"]["resource_type"] == "Product"
assert data["details"]["resource_type"] == "MarketplaceProduct"
assert data["details"]["identifier"] == "NONEXISTENT"
def test_update_product_success(self, client, auth_headers, test_product):
def test_update_product_success(self, client, auth_headers, test_marketplace_product):
"""Test updating product successfully"""
update_data = {"title": "Updated Product Title", "price": "25.99"}
update_data = {"title": "Updated MarketplaceProduct Title", "price": "25.99"}
response = client.put(
f"/api/v1/product/{test_product.product_id}",
f"/api/v1/marketplace/product/{test_marketplace_product.marketplace_product_id}",
headers=auth_headers,
json=update_data,
)
assert response.status_code == 200
data = response.json()
assert data["title"] == "Updated Product Title"
assert data["title"] == "Updated MarketplaceProduct Title"
assert data["price"] == "25.99"
def test_update_nonexistent_product_returns_not_found(self, client, auth_headers):
"""Test updating nonexistent product returns ProductNotFoundException"""
update_data = {"title": "Updated Product Title"}
"""Test updating nonexistent product returns MarketplaceProductNotFoundException"""
update_data = {"title": "Updated MarketplaceProduct Title"}
response = client.put(
"/api/v1/product/NONEXISTENT",
"/api/v1/marketplace/product/NONEXISTENT",
headers=auth_headers,
json=update_data,
)
@@ -244,15 +244,15 @@ class TestProductsAPI:
assert data["error_code"] == "PRODUCT_NOT_FOUND"
assert data["status_code"] == 404
assert "NONEXISTENT" in data["message"]
assert data["details"]["resource_type"] == "Product"
assert data["details"]["resource_type"] == "MarketplaceProduct"
assert data["details"]["identifier"] == "NONEXISTENT"
def test_update_product_empty_title_validation_error(self, client, auth_headers, test_product):
"""Test updating product with empty title returns ProductValidationException"""
def test_update_product_empty_title_validation_error(self, client, auth_headers, test_marketplace_product):
"""Test updating product with empty title returns MarketplaceProductValidationException"""
update_data = {"title": ""}
response = client.put(
f"/api/v1/product/{test_product.product_id}",
f"/api/v1/marketplace/product/{test_marketplace_product.marketplace_product_id}",
headers=auth_headers,
json=update_data,
)
@@ -261,15 +261,15 @@ class TestProductsAPI:
data = response.json()
assert data["error_code"] == "PRODUCT_VALIDATION_FAILED"
assert data["status_code"] == 422
assert "Product title cannot be empty" in data["message"]
assert "MarketplaceProduct title cannot be empty" in data["message"]
assert data["details"]["field"] == "title"
def test_update_product_invalid_gtin_data_error(self, client, auth_headers, test_product):
"""Test updating product with invalid GTIN returns InvalidProductDataException"""
def test_update_product_invalid_gtin_data_error(self, client, auth_headers, test_marketplace_product):
"""Test updating product with invalid GTIN returns InvalidMarketplaceProductDataException"""
update_data = {"gtin": "invalid_gtin"}
response = client.put(
f"/api/v1/product/{test_product.product_id}",
f"/api/v1/marketplace/product/{test_marketplace_product.marketplace_product_id}",
headers=auth_headers,
json=update_data,
)
@@ -281,12 +281,12 @@ class TestProductsAPI:
assert "Invalid GTIN format" in data["message"]
assert data["details"]["field"] == "gtin"
def test_update_product_invalid_price_data_error(self, client, auth_headers, test_product):
"""Test updating product with invalid price returns InvalidProductDataException"""
def test_update_product_invalid_price_data_error(self, client, auth_headers, test_marketplace_product):
"""Test updating product with invalid price returns InvalidMarketplaceProductDataException"""
update_data = {"price": "invalid_price"}
response = client.put(
f"/api/v1/product/{test_product.product_id}",
f"/api/v1/marketplace/product/{test_marketplace_product.marketplace_product_id}",
headers=auth_headers,
json=update_data,
)
@@ -298,30 +298,30 @@ class TestProductsAPI:
assert "Invalid price format" in data["message"]
assert data["details"]["field"] == "price"
def test_delete_product_success(self, client, auth_headers, test_product):
def test_delete_product_success(self, client, auth_headers, test_marketplace_product):
"""Test deleting product successfully"""
response = client.delete(
f"/api/v1/product/{test_product.product_id}", headers=auth_headers
f"/api/v1/marketplace/product/{test_marketplace_product.marketplace_product_id}", headers=auth_headers
)
assert response.status_code == 200
assert "deleted successfully" in response.json()["message"]
def test_delete_nonexistent_product_returns_not_found(self, client, auth_headers):
"""Test deleting nonexistent product returns ProductNotFoundException"""
response = client.delete("/api/v1/product/NONEXISTENT", headers=auth_headers)
"""Test deleting nonexistent product returns MarketplaceProductNotFoundException"""
response = client.delete("/api/v1/marketplace/product/NONEXISTENT", headers=auth_headers)
assert response.status_code == 404
data = response.json()
assert data["error_code"] == "PRODUCT_NOT_FOUND"
assert data["status_code"] == 404
assert "NONEXISTENT" in data["message"]
assert data["details"]["resource_type"] == "Product"
assert data["details"]["resource_type"] == "MarketplaceProduct"
assert data["details"]["identifier"] == "NONEXISTENT"
def test_get_product_without_auth_returns_invalid_token(self, client):
"""Test that product endpoints require authentication returns InvalidTokenException"""
response = client.get("/api/v1/product")
response = client.get("/api/v1/marketplace/product")
assert response.status_code == 401
data = response.json()
@@ -331,7 +331,7 @@ class TestProductsAPI:
def test_exception_structure_consistency(self, client, auth_headers):
"""Test that all exceptions follow the consistent LetzShopException structure"""
# Test with a known error case
response = client.get("/api/v1/product/NONEXISTENT", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/NONEXISTENT", headers=auth_headers)
assert response.status_code == 404
data = response.json()

View File

@@ -1,7 +1,7 @@
# tests/integration/api/v1/test_pagination.py
import pytest
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
from models.database.shop import Shop
@pytest.mark.integration
@@ -18,9 +18,9 @@ class TestPagination:
# Create multiple products
products = []
for i in range(25):
product = Product(
product_id=f"PAGE{i:03d}_{unique_suffix}",
title=f"Pagination Test Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"PAGE{i:03d}_{unique_suffix}",
title=f"Pagination Test MarketplaceProduct {i}",
marketplace="PaginationTest",
)
products.append(product)
@@ -29,7 +29,7 @@ class TestPagination:
db.commit()
# Test first page
response = client.get("/api/v1/product?limit=10&skip=0", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=10&skip=0", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert len(data["products"]) == 10
@@ -38,21 +38,21 @@ class TestPagination:
assert data["limit"] == 10
# Test second page
response = client.get("/api/v1/product?limit=10&skip=10", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=10&skip=10", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert len(data["products"]) == 10
assert data["skip"] == 10
# Test last page (should have remaining products)
response = client.get("/api/v1/product?limit=10&skip=20", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=10&skip=20", headers=auth_headers)
assert response.status_code == 200
data = response.json()
assert len(data["products"]) >= 5 # At least 5 remaining from our test set
def test_pagination_boundary_negative_skip_validation_error(self, client, auth_headers):
"""Test negative skip parameter returns ValidationException"""
response = client.get("/api/v1/product?skip=-1", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=-1", headers=auth_headers)
assert response.status_code == 422
data = response.json()
@@ -63,7 +63,7 @@ class TestPagination:
def test_pagination_boundary_zero_limit_validation_error(self, client, auth_headers):
"""Test zero limit parameter returns ValidationException"""
response = client.get("/api/v1/product?limit=0", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=0", headers=auth_headers)
assert response.status_code == 422
data = response.json()
@@ -73,7 +73,7 @@ class TestPagination:
def test_pagination_boundary_excessive_limit_validation_error(self, client, auth_headers):
"""Test excessive limit parameter returns ValidationException"""
response = client.get("/api/v1/product?limit=10000", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=10000", headers=auth_headers)
assert response.status_code == 422
data = response.json()
@@ -84,7 +84,7 @@ class TestPagination:
def test_pagination_beyond_available_records(self, client, auth_headers, db):
"""Test pagination beyond available records returns empty results"""
# Test skip beyond available records
response = client.get("/api/v1/product?skip=10000&limit=10", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=10000&limit=10", headers=auth_headers)
assert response.status_code == 200
data = response.json()
@@ -101,9 +101,9 @@ class TestPagination:
# Create products with same brand for filtering
products = []
for i in range(15):
product = Product(
product_id=f"FILTPAGE{i:03d}_{unique_suffix}",
title=f"Filter Page Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"FILTPAGE{i:03d}_{unique_suffix}",
title=f"Filter Page MarketplaceProduct {i}",
brand="FilterBrand",
marketplace="FilterMarket",
)
@@ -114,7 +114,7 @@ class TestPagination:
# Test first page with filter
response = client.get(
"/api/v1/product?brand=FilterBrand&limit=5&skip=0",
"/api/v1/marketplace/product?brand=FilterBrand&limit=5&skip=0",
headers=auth_headers
)
@@ -124,13 +124,13 @@ class TestPagination:
assert data["total"] >= 15 # At least our test products
# Verify all products have the filtered brand
test_products = [p for p in data["products"] if p["product_id"].endswith(unique_suffix)]
test_products = [p for p in data["products"] if p["marketplace_product_id"].endswith(unique_suffix)]
for product in test_products:
assert product["brand"] == "FilterBrand"
# Test second page with same filter
response = client.get(
"/api/v1/product?brand=FilterBrand&limit=5&skip=5",
"/api/v1/marketplace/product?brand=FilterBrand&limit=5&skip=5",
headers=auth_headers
)
@@ -141,7 +141,7 @@ class TestPagination:
def test_pagination_default_values(self, client, auth_headers):
"""Test pagination with default values"""
response = client.get("/api/v1/product", headers=auth_headers)
response = client.get("/api/v1/marketplace/product", headers=auth_headers)
assert response.status_code == 200
data = response.json()
@@ -157,9 +157,9 @@ class TestPagination:
# Create products with predictable ordering
products = []
for i in range(10):
product = Product(
product_id=f"CONSIST{i:03d}_{unique_suffix}",
title=f"Consistent Product {i:03d}",
product = MarketplaceProduct(
marketplace_product_id=f"CONSIST{i:03d}_{unique_suffix}",
title=f"Consistent MarketplaceProduct {i:03d}",
marketplace="ConsistentMarket",
)
products.append(product)
@@ -168,14 +168,14 @@ class TestPagination:
db.commit()
# Get first page
response1 = client.get("/api/v1/product?limit=5&skip=0", headers=auth_headers)
response1 = client.get("/api/v1/marketplace/product?limit=5&skip=0", headers=auth_headers)
assert response1.status_code == 200
first_page_ids = [p["product_id"] for p in response1.json()["products"]]
first_page_ids = [p["marketplace_product_id"] for p in response1.json()["products"]]
# Get second page
response2 = client.get("/api/v1/product?limit=5&skip=5", headers=auth_headers)
response2 = client.get("/api/v1/marketplace/product?limit=5&skip=5", headers=auth_headers)
assert response2.status_code == 200
second_page_ids = [p["product_id"] for p in response2.json()["products"]]
second_page_ids = [p["marketplace_product_id"] for p in response2.json()["products"]]
# Verify no overlap between pages
overlap = set(first_page_ids) & set(second_page_ids)
@@ -249,7 +249,7 @@ class TestPagination:
import time
start_time = time.time()
response = client.get("/api/v1/product?skip=1000&limit=10", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=1000&limit=10", headers=auth_headers)
end_time = time.time()
assert response.status_code == 200
@@ -262,26 +262,26 @@ class TestPagination:
def test_pagination_with_invalid_parameters_types(self, client, auth_headers):
"""Test pagination with invalid parameter types returns ValidationException"""
# Test non-numeric skip
response = client.get("/api/v1/product?skip=invalid", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=invalid", headers=auth_headers)
assert response.status_code == 422
data = response.json()
assert data["error_code"] == "VALIDATION_ERROR"
# Test non-numeric limit
response = client.get("/api/v1/product?limit=invalid", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=invalid", headers=auth_headers)
assert response.status_code == 422
data = response.json()
assert data["error_code"] == "VALIDATION_ERROR"
# Test float values (should be converted or rejected)
response = client.get("/api/v1/product?skip=10.5&limit=5.5", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=10.5&limit=5.5", headers=auth_headers)
assert response.status_code in [200, 422] # Depends on implementation
def test_empty_dataset_pagination(self, client, auth_headers):
"""Test pagination behavior with empty dataset"""
# Use a filter that should return no results
response = client.get(
"/api/v1/product?brand=NonexistentBrand999&limit=10&skip=0",
"/api/v1/marketplace/product?brand=NonexistentBrand999&limit=10&skip=0",
headers=auth_headers
)
@@ -294,7 +294,7 @@ class TestPagination:
def test_exception_structure_in_pagination_errors(self, client, auth_headers):
"""Test that pagination validation errors follow consistent exception structure"""
response = client.get("/api/v1/product?skip=-1", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=-1", headers=auth_headers)
assert response.status_code == 422
data = response.json()

View File

@@ -184,7 +184,7 @@ class TestShopsAPI:
def test_add_product_to_shop_success(self, client, auth_headers, test_shop, unique_product):
"""Test adding product to shop successfully"""
shop_product_data = {
"product_id": unique_product.product_id, # Use string product_id, not database id
"marketplace_product_id": unique_product.marketplace_product_id, # Use string marketplace_product_id, not database id
"shop_price": 29.99,
"is_active": True,
"is_featured": False,
@@ -205,18 +205,18 @@ class TestShopsAPI:
assert data["is_active"] is True
assert data["is_featured"] is False
# Product details are nested in the 'product' field
# MarketplaceProduct details are nested in the 'product' field
assert "product" in data
assert data["product"]["product_id"] == unique_product.product_id
assert data["product"]["marketplace_product_id"] == unique_product.marketplace_product_id
assert data["product"]["id"] == unique_product.id
def test_add_product_to_shop_already_exists_conflict(self, client, auth_headers, test_shop, shop_product):
"""Test adding product that already exists in shop returns ShopProductAlreadyExistsException"""
# shop_product fixture already creates a relationship, get the product_id string
# shop_product fixture already creates a relationship, get the marketplace_product_id string
existing_product = shop_product.product
shop_product_data = {
"product_id": existing_product.product_id, # Use string product_id
"marketplace_product_id": existing_product.marketplace_product_id, # Use string marketplace_product_id
"shop_price": 29.99,
}
@@ -231,12 +231,12 @@ class TestShopsAPI:
assert data["error_code"] == "SHOP_PRODUCT_ALREADY_EXISTS"
assert data["status_code"] == 409
assert test_shop.shop_code in data["message"]
assert existing_product.product_id in data["message"]
assert existing_product.marketplace_product_id in data["message"]
def test_add_nonexistent_product_to_shop_not_found(self, client, auth_headers, test_shop):
"""Test adding nonexistent product to shop returns ProductNotFoundException"""
"""Test adding nonexistent product to shop returns MarketplaceProductNotFoundException"""
shop_product_data = {
"product_id": "NONEXISTENT_PRODUCT", # Use string product_id that doesn't exist
"marketplace_product_id": "NONEXISTENT_PRODUCT", # Use string marketplace_product_id that doesn't exist
"shop_price": 29.99,
}
@@ -321,7 +321,7 @@ class TestShopsAPI:
# Test adding products (might require verification)
product_data = {
"product_id": 1,
"marketplace_product_id": 1,
"shop_price": 29.99,
}

View File

@@ -1,9 +1,11 @@
# tests/integration/api/v1/test_stats_endpoints.py
import pytest
@pytest.mark.integration
@pytest.mark.api
@pytest.mark.stats
class TestStatsAPI:
def test_get_basic_stats(self, client, auth_headers, test_product):
def test_get_basic_stats(self, client, auth_headers, test_marketplace_product):
"""Test getting basic statistics"""
response = client.get("/api/v1/stats", headers=auth_headers)
@@ -16,7 +18,7 @@ class TestStatsAPI:
assert "unique_shops" in data
assert data["total_products"] >= 1
def test_get_marketplace_stats(self, client, auth_headers, test_product):
def test_get_marketplace_stats(self, client, auth_headers, test_marketplace_product):
"""Test getting marketplace statistics"""
response = client.get("/api/v1/stats/marketplace", headers=auth_headers)

View File

@@ -12,7 +12,7 @@ class TestAuthentication:
"/api/v1/admin/users",
"/api/v1/admin/shops",
"/api/v1/marketplace/import-jobs",
"/api/v1/product",
"/api/v1/marketplace/product",
"/api/v1/shop",
"/api/v1/stats",
"/api/v1/stock",
@@ -26,7 +26,7 @@ class TestAuthentication:
"""Test protected endpoints with invalid token"""
headers = {"Authorization": "Bearer invalid_token_here"}
response = client.get("/api/v1/product", headers=headers)
response = client.get("/api/v1/marketplace/product", headers=headers)
assert response.status_code == 401 # Token is not valid
def test_debug_direct_bearer(self, client):
@@ -49,7 +49,7 @@ class TestAuthentication:
# Test 2: Try a regular endpoint that uses get_current_user
response2 = client.get(
"/api/v1/product"
"/api/v1/marketplace/product"
) # or any endpoint with get_current_user
print(f"Regular endpoint - Status: {response2.status_code}")
try:
@@ -64,12 +64,12 @@ class TestAuthentication:
if hasattr(route, "path") and hasattr(route, "methods"):
print(f"{list(route.methods)} {route.path}")
print("\n=== Testing Product Endpoint Variations ===")
print("\n=== Testing MarketplaceProduct Endpoint Variations ===")
variations = [
"/api/v1/product", # Your current attempt
"/api/v1/product/", # With trailing slash
"/api/v1/product/list", # With list endpoint
"/api/v1/product/all", # With all endpoint
"/api/v1/marketplace/product", # Your current attempt
"/api/v1/marketplace/product/", # With trailing slash
"/api/v1/marketplace/product/list", # With list endpoint
"/api/v1/marketplace/product/all", # With all endpoint
]
for path in variations:

View File

@@ -27,7 +27,7 @@ class TestAuthorization:
def test_regular_endpoints_with_user_access(self, client, auth_headers):
"""Test that regular users can access non-admin endpoints"""
user_endpoints = [
"/api/v1/product",
"/api/v1/marketplace/product",
"/api/v1/stats",
"/api/v1/stock",
]

View File

@@ -11,7 +11,7 @@ class TestInputValidation:
malicious_search = "'; DROP TABLE products; --"
response = client.get(
f"/api/v1/product?search={malicious_search}", headers=auth_headers
f"/api/v1/marketplace/product?search={malicious_search}", headers=auth_headers
)
# Should not crash and should return normal response
@@ -25,12 +25,12 @@ class TestInputValidation:
# xss_payload = "<script>alert('xss')</script>"
#
# product_data = {
# "product_id": "XSS_TEST",
# "marketplace_product_id": "XSS_TEST",
# "title": xss_payload,
# "description": xss_payload,
# }
#
# response = client.post("/api/v1/product", headers=auth_headers, json=product_data)
# response = client.post("/api/v1/marketplace/product", headers=auth_headers, json=product_data)
#
# assert response.status_code == 200
# data = response.json()
@@ -40,24 +40,24 @@ class TestInputValidation:
def test_parameter_validation(self, client, auth_headers):
"""Test parameter validation for API endpoints"""
# Test invalid pagination parameters
response = client.get("/api/v1/product?limit=-1", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=-1", headers=auth_headers)
assert response.status_code == 422 # Validation error
response = client.get("/api/v1/product?skip=-1", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?skip=-1", headers=auth_headers)
assert response.status_code == 422 # Validation error
def test_json_validation(self, client, auth_headers):
"""Test JSON validation for POST requests"""
# Test invalid JSON structure
response = client.post(
"/api/v1/product", headers=auth_headers, content="invalid json content"
"/api/v1/marketplace/product", headers=auth_headers, content="invalid json content"
)
assert response.status_code == 422 # JSON decode error
# Test missing required fields
response = client.post(
"/api/v1/product",
"/api/v1/marketplace/product",
headers=auth_headers,
json={"title": "Test Product"}, # Missing required product_id
json={"title": "Test MarketplaceProduct"}, # Missing required marketplace_product_id
)
assert response.status_code == 422 # Validation error

View File

@@ -5,7 +5,7 @@ from unittest.mock import AsyncMock, patch
import pytest
from app.tasks.background_tasks import process_marketplace_import
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
@pytest.mark.integration

View File

@@ -10,8 +10,8 @@ class TestIntegrationFlows:
"""Test complete product creation and management workflow"""
# 1. Create a product
product_data = {
"product_id": "FLOW001",
"title": "Integration Test Product",
"marketplace_product_id": "FLOW001",
"title": "Integration Test MarketplaceProduct",
"description": "Testing full workflow",
"price": "29.99",
"brand": "FlowBrand",
@@ -21,7 +21,7 @@ class TestIntegrationFlows:
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 200
product = response.json()
@@ -38,16 +38,16 @@ class TestIntegrationFlows:
# 3. Get product with stock info
response = client.get(
f"/api/v1/product/{product['product_id']}", headers=auth_headers
f"/api/v1/marketplace/product/{product['marketplace_product_id']}", headers=auth_headers
)
assert response.status_code == 200
product_detail = response.json()
assert product_detail["stock_info"]["total_quantity"] == 50
# 4. Update product
update_data = {"title": "Updated Integration Test Product"}
update_data = {"title": "Updated Integration Test MarketplaceProduct"}
response = client.put(
f"/api/v1/product/{product['product_id']}",
f"/api/v1/marketplace/product/{product['marketplace_product_id']}",
headers=auth_headers,
json=update_data,
)
@@ -55,7 +55,7 @@ class TestIntegrationFlows:
# 5. Search for product
response = client.get(
"/api/v1/product?search=Updated Integration", headers=auth_headers
"/api/v1/marketplace/product?search=Updated Integration", headers=auth_headers
)
assert response.status_code == 200
assert response.json()["total"] == 1
@@ -75,14 +75,14 @@ class TestIntegrationFlows:
# 2. Create a product
product_data = {
"product_id": "SHOPFLOW001",
"title": "Shop Flow Product",
"marketplace_product_id": "SHOPFLOW001",
"title": "Shop Flow MarketplaceProduct",
"price": "15.99",
"marketplace": "ShopFlow",
}
response = client.post(
"/api/v1/product", headers=auth_headers, json=product_data
"/api/v1/marketplace/product", headers=auth_headers, json=product_data
)
assert response.status_code == 200
product = response.json()

View File

@@ -3,7 +3,7 @@ import time
import pytest
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
@pytest.mark.performance
@@ -15,9 +15,9 @@ class TestPerformance:
# Create multiple products
products = []
for i in range(100):
product = Product(
product_id=f"PERF{i:03d}",
title=f"Performance Test Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"PERF{i:03d}",
title=f"Performance Test MarketplaceProduct {i}",
price=f"{i}.99",
marketplace="Performance",
)
@@ -28,7 +28,7 @@ class TestPerformance:
# Time the request
start_time = time.time()
response = client.get("/api/v1/product?limit=100", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?limit=100", headers=auth_headers)
end_time = time.time()
assert response.status_code == 200
@@ -40,9 +40,9 @@ class TestPerformance:
# Create products with searchable content
products = []
for i in range(50):
product = Product(
product_id=f"SEARCH{i:03d}",
title=f"Searchable Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"SEARCH{i:03d}",
title=f"Searchable MarketplaceProduct {i}",
description=f"This is a searchable product number {i}",
brand="SearchBrand",
marketplace="SearchMarket",
@@ -54,7 +54,7 @@ class TestPerformance:
# Time search request
start_time = time.time()
response = client.get("/api/v1/product?search=Searchable", headers=auth_headers)
response = client.get("/api/v1/marketplace/product?search=Searchable", headers=auth_headers)
end_time = time.time()
assert response.status_code == 200
@@ -69,9 +69,9 @@ class TestPerformance:
marketplaces = ["Market1", "Market2"]
for i in range(200):
product = Product(
product_id=f"COMPLEX{i:03d}",
title=f"Complex Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"COMPLEX{i:03d}",
title=f"Complex MarketplaceProduct {i}",
brand=brands[i % 3],
marketplace=marketplaces[i % 2],
price=f"{10 + (i % 50)}.99",
@@ -85,7 +85,7 @@ class TestPerformance:
# Test complex filtering performance
start_time = time.time()
response = client.get(
"/api/v1/product?brand=Brand1&marketplace=Market1&limit=50",
"/api/v1/marketplace/product?brand=Brand1&marketplace=Market1&limit=50",
headers=auth_headers,
)
end_time = time.time()
@@ -100,9 +100,9 @@ class TestPerformance:
# Create a large dataset
products = []
for i in range(500):
product = Product(
product_id=f"LARGE{i:04d}",
title=f"Large Dataset Product {i}",
product = MarketplaceProduct(
marketplace_product_id=f"LARGE{i:04d}",
title=f"Large Dataset MarketplaceProduct {i}",
marketplace="LargeTest",
)
products.append(product)
@@ -115,7 +115,7 @@ class TestPerformance:
for offset in offsets:
start_time = time.time()
response = client.get(
f"/api/v1/product?skip={offset}&limit=20", headers=auth_headers
f"/api/v1/marketplace/product?skip={offset}&limit=20", headers=auth_headers
)
end_time = time.time()

View File

@@ -104,13 +104,13 @@ class TestErrorHandling:
def test_product_not_found(self, client, auth_headers):
"""Test accessing non-existent product"""
response = client.get("/api/v1/product/NONEXISTENT", headers=auth_headers)
response = client.get("/api/v1/marketplace/product/NONEXISTENT", headers=auth_headers)
assert response.status_code == 404
data = response.json()
assert data["error_code"] == "PRODUCT_NOT_FOUND"
assert data["status_code"] == 404
assert data["details"]["resource_type"] == "Product"
assert data["details"]["resource_type"] == "MarketplaceProduct"
assert data["details"]["identifier"] == "NONEXISTENT"
def test_duplicate_shop_creation(self, client, auth_headers, test_shop):
@@ -128,21 +128,21 @@ class TestErrorHandling:
assert data["status_code"] == 409
assert data["details"]["shop_code"] == test_shop.shop_code.upper()
def test_duplicate_product_creation(self, client, auth_headers, test_product):
def test_duplicate_product_creation(self, client, auth_headers, test_marketplace_product):
"""Test creating product with duplicate product ID"""
product_data = {
"product_id": test_product.product_id,
"title": "Duplicate Product",
"marketplace_product_id": test_marketplace_product.marketplace_product_id,
"title": "Duplicate MarketplaceProduct",
"gtin": "1234567890123"
}
response = client.post("/api/v1/product", headers=auth_headers, json=product_data)
response = client.post("/api/v1/marketplace/product", headers=auth_headers, json=product_data)
assert response.status_code == 409
data = response.json()
assert data["error_code"] == "PRODUCT_ALREADY_EXISTS"
assert data["status_code"] == 409
assert data["details"]["product_id"] == test_product.product_id
assert data["details"]["marketplace_product_id"] == test_marketplace_product.marketplace_product_id
def test_unauthorized_shop_access(self, client, auth_headers, inactive_shop):
"""Test accessing shop without proper permissions"""
@@ -191,12 +191,12 @@ class TestErrorHandling:
def test_validation_error_invalid_gtin(self, client, auth_headers):
"""Test validation error for invalid GTIN format"""
product_data = {
"product_id": "TESTPROD001",
"title": "Test Product",
"marketplace_product_id": "TESTPROD001",
"title": "Test MarketplaceProduct",
"gtin": "invalid_gtin_format"
}
response = client.post("/api/v1/product", headers=auth_headers, json=product_data)
response = client.post("/api/v1/marketplace/product", headers=auth_headers, json=product_data)
assert response.status_code == 422
data = response.json()
@@ -204,11 +204,11 @@ class TestErrorHandling:
assert data["status_code"] == 422
assert data["details"]["field"] == "gtin"
def test_stock_insufficient_quantity(self, client, auth_headers, test_shop, test_product):
def test_stock_insufficient_quantity(self, client, auth_headers, test_shop, test_marketplace_product):
"""Test business logic error for insufficient stock"""
# First create some stock
stock_data = {
"gtin": test_product.gtin,
"gtin": test_marketplace_product.gtin,
"location": "WAREHOUSE_A",
"quantity": 5
}
@@ -216,7 +216,7 @@ class TestErrorHandling:
# Try to remove more than available using your remove endpoint
remove_data = {
"gtin": test_product.gtin,
"gtin": test_marketplace_product.gtin,
"location": "WAREHOUSE_A",
"quantity": 10 # More than the 5 we added
}
@@ -345,7 +345,7 @@ class TestErrorHandling:
"""Test that all error responses follow consistent structure"""
test_cases = [
("/api/v1/shop/NONEXISTENT", 404),
("/api/v1/product/NONEXISTENT", 404),
("/api/v1/marketplace/product/NONEXISTENT", 404),
]
for endpoint, expected_status in test_cases:

View File

@@ -1,4 +1,4 @@
product_id,title,price,currency,brand,marketplace
TEST001,Sample Product 1,19.99,EUR,TestBrand,TestMarket
TEST002,Sample Product 2,29.99,EUR,TestBrand,TestMarket
TEST003,Sample Product 3,39.99,USD,AnotherBrand,TestMarket
TEST001,Sample MarketplaceProduct 1,19.99,EUR,TestBrand,TestMarket
TEST002,Sample MarketplaceProduct 2,29.99,EUR,TestBrand,TestMarket
TEST003,Sample MarketplaceProduct 3,39.99,USD,AnotherBrand,TestMarket
1 product_id title price currency brand marketplace
2 TEST001 Sample Product 1 Sample MarketplaceProduct 1 19.99 EUR TestBrand TestMarket
3 TEST002 Sample Product 2 Sample MarketplaceProduct 2 29.99 EUR TestBrand TestMarket
4 TEST003 Sample Product 3 Sample MarketplaceProduct 3 39.99 USD AnotherBrand TestMarket

View File

@@ -41,7 +41,8 @@ class TestRateLimiter:
# Next request should be blocked
assert limiter.allow_request(client_id, max_requests, 3600) is False
@pytest.mark.unit
@pytest.mark.auth # for auth manager tests
class TestAuthManager:
def test_password_hashing_and_verification(self):
"""Test password hashing and verification"""

View File

@@ -1,7 +1,7 @@
# tests/unit/models/test_database_models.py
import pytest
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
from models.database.shop import Shop
from models.database.stock import Stock
from models.database.user import User
@@ -30,10 +30,10 @@ class TestDatabaseModels:
assert user.updated_at is not None
def test_product_model(self, db):
"""Test Product model creation"""
product = Product(
product_id="DB_TEST_001",
title="Database Test Product",
"""Test MarketplaceProduct model creation"""
marketplace_product = MarketplaceProduct(
marketplace_product_id="DB_TEST_001",
title="Database Test MarketplaceProduct",
description="Testing product model",
price="25.99",
currency="USD",
@@ -44,13 +44,13 @@ class TestDatabaseModels:
shop_name="DBTestShop",
)
db.add(product)
db.add(marketplace_product)
db.commit()
db.refresh(product)
db.refresh(marketplace_product)
assert product.id is not None
assert product.product_id == "DB_TEST_001"
assert product.created_at is not None
assert marketplace_product.id is not None
assert marketplace_product.marketplace_product_id == "DB_TEST_001"
assert marketplace_product.created_at is not None
def test_stock_model(self, db):
"""Test Stock model creation"""
@@ -87,13 +87,13 @@ class TestDatabaseModels:
def test_database_constraints(self, db):
"""Test database constraints and unique indexes"""
# Test unique product_id constraint
product1 = Product(product_id="UNIQUE_001", title="Product 1")
# Test unique marketplace_product_id constraint
product1 = MarketplaceProduct(marketplace_product_id="UNIQUE_001", title="MarketplaceProduct 1")
db.add(product1)
db.commit()
# This should raise an integrity error
with pytest.raises(Exception): # Could be IntegrityError or similar
product2 = Product(product_id="UNIQUE_001", title="Product 2")
product2 = MarketplaceProduct(marketplace_product_id="UNIQUE_001", title="MarketplaceProduct 2")
db.add(product2)
db.commit()

View File

@@ -10,7 +10,7 @@ from app.exceptions import (
AdminOperationException,
)
from app.services.admin_service import AdminService
from models.database.marketplace import MarketplaceImportJob
from models.database.marketplace_import_job import MarketplaceImportJob
from models.database.shop import Shop
@@ -169,51 +169,51 @@ class TestAdminService:
assert exception.error_code == "SHOP_NOT_FOUND"
# Marketplace Import Jobs Tests
def test_get_marketplace_import_jobs_no_filters(self, db, test_marketplace_job):
def test_get_marketplace_import_jobs_no_filters(self, db, test_marketplace_import_job):
"""Test getting marketplace import jobs without filters"""
result = self.service.get_marketplace_import_jobs(db, skip=0, limit=10)
assert len(result) >= 1
# Find our test job in the results
test_job = next(
(job for job in result if job.job_id == test_marketplace_job.id), None
(job for job in result if job.job_id == test_marketplace_import_job.id), None
)
assert test_job is not None
assert test_job.marketplace == test_marketplace_job.marketplace
assert test_job.shop_name == test_marketplace_job.shop_name
assert test_job.status == test_marketplace_job.status
assert test_job.marketplace == test_marketplace_import_job.marketplace
assert test_job.shop_name == test_marketplace_import_job.shop_name
assert test_job.status == test_marketplace_import_job.status
def test_get_marketplace_import_jobs_with_marketplace_filter(self, db, test_marketplace_job):
def test_get_marketplace_import_jobs_with_marketplace_filter(self, db, test_marketplace_import_job):
"""Test filtering marketplace import jobs by marketplace"""
result = self.service.get_marketplace_import_jobs(
db, marketplace=test_marketplace_job.marketplace, skip=0, limit=10
db, marketplace=test_marketplace_import_job.marketplace, skip=0, limit=10
)
assert len(result) >= 1
for job in result:
assert test_marketplace_job.marketplace.lower() in job.marketplace.lower()
assert test_marketplace_import_job.marketplace.lower() in job.marketplace.lower()
def test_get_marketplace_import_jobs_with_shop_filter(self, db, test_marketplace_job):
def test_get_marketplace_import_jobs_with_shop_filter(self, db, test_marketplace_import_job):
"""Test filtering marketplace import jobs by shop name"""
result = self.service.get_marketplace_import_jobs(
db, shop_name=test_marketplace_job.shop_name, skip=0, limit=10
db, shop_name=test_marketplace_import_job.shop_name, skip=0, limit=10
)
assert len(result) >= 1
for job in result:
assert test_marketplace_job.shop_name.lower() in job.shop_name.lower()
assert test_marketplace_import_job.shop_name.lower() in job.shop_name.lower()
def test_get_marketplace_import_jobs_with_status_filter(self, db, test_marketplace_job):
def test_get_marketplace_import_jobs_with_status_filter(self, db, test_marketplace_import_job):
"""Test filtering marketplace import jobs by status"""
result = self.service.get_marketplace_import_jobs(
db, status=test_marketplace_job.status, skip=0, limit=10
db, status=test_marketplace_import_job.status, skip=0, limit=10
)
assert len(result) >= 1
for job in result:
assert job.status == test_marketplace_job.status
assert job.status == test_marketplace_import_job.status
def test_get_marketplace_import_jobs_pagination(self, db, test_marketplace_job):
def test_get_marketplace_import_jobs_pagination(self, db, test_marketplace_import_job):
"""Test marketplace import jobs pagination"""
result_page1 = self.service.get_marketplace_import_jobs(db, skip=0, limit=1)
result_page2 = self.service.get_marketplace_import_jobs(db, skip=1, limit=1)

View File

@@ -4,7 +4,7 @@ from datetime import datetime
import pytest
from app.exceptions.marketplace import (
from app.exceptions.marketplace_import_job import (
ImportJobNotFoundException,
ImportJobNotOwnedException,
ImportJobCannotBeCancelledException,
@@ -12,9 +12,9 @@ from app.exceptions.marketplace import (
)
from app.exceptions.shop import ShopNotFoundException, UnauthorizedShopAccessException
from app.exceptions.base import ValidationException
from app.services.marketplace_service import MarketplaceService
from models.schemas.marketplace import MarketplaceImportRequest
from models.database.marketplace import MarketplaceImportJob
from app.services.marketplace_import_job_service import MarketplaceImportJobService
from models.schemas.marketplace_import_job import MarketplaceImportJobRequest
from models.database.marketplace_import_job import MarketplaceImportJob
from models.database.shop import Shop
from models.database.user import User
@@ -23,7 +23,7 @@ from models.database.user import User
@pytest.mark.marketplace
class TestMarketplaceService:
def setup_method(self):
self.service = MarketplaceService()
self.service = MarketplaceImportJobService()
def test_validate_shop_access_success(self, db, test_shop, test_user):
"""Test successful shop access validation"""
@@ -76,7 +76,7 @@ class TestMarketplaceService:
test_shop.owner_id = test_user.id
db.commit()
request = MarketplaceImportRequest(
request = MarketplaceImportJobRequest(
url="https://example.com/products.csv",
marketplace="Amazon",
shop_code=test_shop.shop_code,
@@ -94,7 +94,7 @@ class TestMarketplaceService:
def test_create_import_job_invalid_shop(self, db, test_user):
"""Test import job creation with invalid shop"""
request = MarketplaceImportRequest(
request = MarketplaceImportJobRequest(
url="https://example.com/products.csv",
marketplace="Amazon",
shop_code="INVALID_SHOP",
@@ -114,7 +114,7 @@ class TestMarketplaceService:
test_shop.owner_id = other_user.id
db.commit()
request = MarketplaceImportRequest(
request = MarketplaceImportJobRequest(
url="https://example.com/products.csv",
marketplace="Amazon",
shop_code=test_shop.shop_code,
@@ -127,24 +127,24 @@ class TestMarketplaceService:
exception = exc_info.value
assert exception.error_code == "UNAUTHORIZED_SHOP_ACCESS"
def test_get_import_job_by_id_success(self, db, test_marketplace_job, test_user):
def test_get_import_job_by_id_success(self, db, test_marketplace_import_job, test_user):
"""Test getting import job by ID for job owner"""
result = self.service.get_import_job_by_id(
db, test_marketplace_job.id, test_user
db, test_marketplace_import_job.id, test_user
)
assert result.id == test_marketplace_job.id
assert result.id == test_marketplace_import_job.id
assert result.user_id == test_user.id
def test_get_import_job_by_id_admin_access(
self, db, test_marketplace_job, test_admin
self, db, test_marketplace_import_job, test_admin
):
"""Test that admin can access any import job"""
result = self.service.get_import_job_by_id(
db, test_marketplace_job.id, test_admin
db, test_marketplace_import_job.id, test_admin
)
assert result.id == test_marketplace_job.id
assert result.id == test_marketplace_import_job.id
def test_get_import_job_by_id_not_found(self, db, test_user):
"""Test getting non-existent import job"""
@@ -157,42 +157,42 @@ class TestMarketplaceService:
assert "99999" in exception.message
def test_get_import_job_by_id_access_denied(
self, db, test_marketplace_job, other_user
self, db, test_marketplace_import_job, other_user
):
"""Test access denied when user doesn't own the job"""
with pytest.raises(ImportJobNotOwnedException) as exc_info:
self.service.get_import_job_by_id(db, test_marketplace_job.id, other_user)
self.service.get_import_job_by_id(db, test_marketplace_import_job.id, other_user)
exception = exc_info.value
assert exception.error_code == "IMPORT_JOB_NOT_OWNED"
assert exception.status_code == 403
assert str(test_marketplace_job.id) in exception.message
assert str(test_marketplace_import_job.id) in exception.message
def test_get_import_jobs_user_filter(self, db, test_marketplace_job, test_user):
def test_get_import_jobs_user_filter(self, db, test_marketplace_import_job, test_user):
"""Test getting import jobs filtered by user"""
jobs = self.service.get_import_jobs(db, test_user)
assert len(jobs) >= 1
assert any(job.id == test_marketplace_job.id for job in jobs)
assert test_marketplace_job.user_id == test_user.id
assert any(job.id == test_marketplace_import_job.id for job in jobs)
assert test_marketplace_import_job.user_id == test_user.id
def test_get_import_jobs_admin_sees_all(self, db, test_marketplace_job, test_admin):
def test_get_import_jobs_admin_sees_all(self, db, test_marketplace_import_job, test_admin):
"""Test that admin sees all import jobs"""
jobs = self.service.get_import_jobs(db, test_admin)
assert len(jobs) >= 1
assert any(job.id == test_marketplace_job.id for job in jobs)
assert any(job.id == test_marketplace_import_job.id for job in jobs)
def test_get_import_jobs_with_marketplace_filter(
self, db, test_marketplace_job, test_user
self, db, test_marketplace_import_job, test_user
):
"""Test getting import jobs with marketplace filter"""
jobs = self.service.get_import_jobs(
db, test_user, marketplace=test_marketplace_job.marketplace
db, test_user, marketplace=test_marketplace_import_job.marketplace
)
assert len(jobs) >= 1
assert any(job.marketplace == test_marketplace_job.marketplace for job in jobs)
assert any(job.marketplace == test_marketplace_import_job.marketplace for job in jobs)
def test_get_import_jobs_with_pagination(self, db, test_user, test_shop):
"""Test getting import jobs with pagination"""
@@ -228,11 +228,11 @@ class TestMarketplaceService:
assert exception.error_code == "VALIDATION_ERROR"
assert "Failed to retrieve import jobs" in exception.message
def test_update_job_status_success(self, db, test_marketplace_job):
def test_update_job_status_success(self, db, test_marketplace_import_job):
"""Test updating job status"""
result = self.service.update_job_status(
db,
test_marketplace_job.id,
test_marketplace_import_job.id,
"completed",
imported_count=100,
total_processed=100,
@@ -260,7 +260,7 @@ class TestMarketplaceService:
assert exception.error_code == "VALIDATION_ERROR"
assert "Failed to update job status" in exception.message
def test_get_job_stats_user(self, db, test_marketplace_job, test_user):
def test_get_job_stats_user(self, db, test_marketplace_import_job, test_user):
"""Test getting job statistics for user"""
stats = self.service.get_job_stats(db, test_user)
@@ -271,7 +271,7 @@ class TestMarketplaceService:
assert "failed_jobs" in stats
assert isinstance(stats["total_jobs"], int)
def test_get_job_stats_admin(self, db, test_marketplace_job, test_admin):
def test_get_job_stats_admin(self, db, test_marketplace_import_job, test_admin):
"""Test getting job statistics for admin"""
stats = self.service.get_job_stats(db, test_admin)
@@ -287,14 +287,14 @@ class TestMarketplaceService:
assert exception.error_code == "VALIDATION_ERROR"
assert "Failed to retrieve job statistics" in exception.message
def test_convert_to_response_model(self, test_marketplace_job):
def test_convert_to_response_model(self, test_marketplace_import_job):
"""Test converting database model to response model"""
response = self.service.convert_to_response_model(test_marketplace_job)
response = self.service.convert_to_response_model(test_marketplace_import_job)
assert response.job_id == test_marketplace_job.id
assert response.status == test_marketplace_job.status
assert response.marketplace == test_marketplace_job.marketplace
assert response.imported == (test_marketplace_job.imported_count or 0)
assert response.job_id == test_marketplace_import_job.id
assert response.status == test_marketplace_import_job.status
assert response.marketplace == test_marketplace_import_job.marketplace
assert response.imported == (test_marketplace_import_job.imported_count or 0)
def test_cancel_import_job_success(self, db, test_user, test_shop):
"""Test cancelling a pending import job"""
@@ -330,24 +330,24 @@ class TestMarketplaceService:
exception = exc_info.value
assert exception.error_code == "IMPORT_JOB_NOT_FOUND"
def test_cancel_import_job_access_denied(self, db, test_marketplace_job, other_user):
def test_cancel_import_job_access_denied(self, db, test_marketplace_import_job, other_user):
"""Test cancelling import job without access"""
with pytest.raises(ImportJobNotOwnedException) as exc_info:
self.service.cancel_import_job(db, test_marketplace_job.id, other_user)
self.service.cancel_import_job(db, test_marketplace_import_job.id, other_user)
exception = exc_info.value
assert exception.error_code == "IMPORT_JOB_NOT_OWNED"
def test_cancel_import_job_invalid_status(
self, db, test_marketplace_job, test_user
self, db, test_marketplace_import_job, test_user
):
"""Test cancelling a job that can't be cancelled"""
# Set job status to completed
test_marketplace_job.status = "completed"
test_marketplace_import_job.status = "completed"
db.commit()
with pytest.raises(ImportJobCannotBeCancelledException) as exc_info:
self.service.cancel_import_job(db, test_marketplace_job.id, test_user)
self.service.cancel_import_job(db, test_marketplace_import_job.id, test_user)
exception = exc_info.value
assert exception.error_code == "IMPORT_JOB_CANNOT_BE_CANCELLED"
@@ -396,10 +396,10 @@ class TestMarketplaceService:
exception = exc_info.value
assert exception.error_code == "IMPORT_JOB_NOT_FOUND"
def test_delete_import_job_access_denied(self, db, test_marketplace_job, other_user):
def test_delete_import_job_access_denied(self, db, test_marketplace_import_job, other_user):
"""Test deleting import job without access"""
with pytest.raises(ImportJobNotOwnedException) as exc_info:
self.service.delete_import_job(db, test_marketplace_job.id, other_user)
self.service.delete_import_job(db, test_marketplace_import_job.id, other_user)
exception = exc_info.value
assert exception.error_code == "IMPORT_JOB_NOT_OWNED"
@@ -449,7 +449,7 @@ class TestMarketplaceService:
def test_create_import_job_database_error(self, db_with_error, test_user):
"""Test import job creation handles database errors"""
request = MarketplaceImportRequest(
request = MarketplaceImportJobRequest(
url="https://example.com/products.csv",
marketplace="Amazon",
shop_code="TEST_SHOP",

View File

@@ -1,29 +1,29 @@
# tests/test_product_service.py
import pytest
from app.services.product_service import ProductService
from app.services.marketplace_product_service import MarketplaceProductService
from app.exceptions import (
ProductNotFoundException,
ProductAlreadyExistsException,
InvalidProductDataException,
ProductValidationException,
MarketplaceProductNotFoundException,
MarketplaceProductAlreadyExistsException,
InvalidMarketplaceProductDataException,
MarketplaceProductValidationException,
ValidationException,
)
from models.schemas.product import ProductCreate, ProductUpdate
from models.database.product import Product
from models.schemas.marketplace_product import MarketplaceProductCreate, MarketplaceProductUpdate
from models.database.marketplace_product import MarketplaceProduct
@pytest.mark.unit
@pytest.mark.products
class TestProductService:
def setup_method(self):
self.service = ProductService()
self.service = MarketplaceProductService()
def test_create_product_success(self, db):
"""Test successful product creation with valid data"""
product_data = ProductCreate(
product_id="SVC001",
title="Service Test Product",
product_data = MarketplaceProductCreate(
marketplace_product_id="SVC001",
title="Service Test MarketplaceProduct",
gtin="1234567890123",
price="19.99",
marketplace="TestMarket",
@@ -31,22 +31,22 @@ class TestProductService:
product = self.service.create_product(db, product_data)
assert product.product_id == "SVC001"
assert product.title == "Service Test Product"
assert product.marketplace_product_id == "SVC001"
assert product.title == "Service Test MarketplaceProduct"
assert product.gtin == "1234567890123"
assert product.marketplace == "TestMarket"
assert product.price == "19.99" # Price is stored as string after processing
def test_create_product_invalid_gtin(self, db):
"""Test product creation with invalid GTIN raises InvalidProductDataException"""
product_data = ProductCreate(
product_id="SVC002",
title="Service Test Product",
"""Test product creation with invalid GTIN raises InvalidMarketplaceProductDataException"""
product_data = MarketplaceProductCreate(
marketplace_product_id="SVC002",
title="Service Test MarketplaceProduct",
gtin="invalid_gtin",
price="19.99",
)
with pytest.raises(InvalidProductDataException) as exc_info:
with pytest.raises(InvalidMarketplaceProductDataException) as exc_info:
self.service.create_product(db, product_data)
assert exc_info.value.error_code == "INVALID_PRODUCT_DATA"
@@ -55,201 +55,201 @@ class TestProductService:
assert exc_info.value.details.get("field") == "gtin"
def test_create_product_missing_product_id(self, db):
"""Test product creation without product_id raises ProductValidationException"""
product_data = ProductCreate(
product_id="", # Empty product ID
title="Service Test Product",
"""Test product creation without marketplace_product_id raises MarketplaceProductValidationException"""
product_data = MarketplaceProductCreate(
marketplace_product_id="", # Empty product ID
title="Service Test MarketplaceProduct",
price="19.99",
)
with pytest.raises(ProductValidationException) as exc_info:
with pytest.raises(MarketplaceProductValidationException) as exc_info:
self.service.create_product(db, product_data)
assert exc_info.value.error_code == "PRODUCT_VALIDATION_FAILED"
assert "Product ID is required" in str(exc_info.value)
assert exc_info.value.details.get("field") == "product_id"
assert "MarketplaceProduct ID is required" in str(exc_info.value)
assert exc_info.value.details.get("field") == "marketplace_product_id"
def test_create_product_missing_title(self, db):
"""Test product creation without title raises ProductValidationException"""
product_data = ProductCreate(
product_id="SVC003",
"""Test product creation without title raises MarketplaceProductValidationException"""
product_data = MarketplaceProductCreate(
marketplace_product_id="SVC003",
title="", # Empty title
price="19.99",
)
with pytest.raises(ProductValidationException) as exc_info:
with pytest.raises(MarketplaceProductValidationException) as exc_info:
self.service.create_product(db, product_data)
assert exc_info.value.error_code == "PRODUCT_VALIDATION_FAILED"
assert "Product title is required" in str(exc_info.value)
assert "MarketplaceProduct title is required" in str(exc_info.value)
assert exc_info.value.details.get("field") == "title"
def test_create_product_already_exists(self, db, test_product):
"""Test creating product with existing ID raises ProductAlreadyExistsException"""
product_data = ProductCreate(
product_id=test_product.product_id, # Use existing product ID
title="Duplicate Product",
def test_create_product_already_exists(self, db, test_marketplace_product):
"""Test creating product with existing ID raises MarketplaceProductAlreadyExistsException"""
product_data = MarketplaceProductCreate(
marketplace_product_id=test_marketplace_product.marketplace_product_id, # Use existing product ID
title="Duplicate MarketplaceProduct",
price="29.99",
)
with pytest.raises(ProductAlreadyExistsException) as exc_info:
with pytest.raises(MarketplaceProductAlreadyExistsException) as exc_info:
self.service.create_product(db, product_data)
assert exc_info.value.error_code == "PRODUCT_ALREADY_EXISTS"
assert test_product.product_id in str(exc_info.value)
assert test_marketplace_product.marketplace_product_id in str(exc_info.value)
assert exc_info.value.status_code == 409
assert exc_info.value.details.get("product_id") == test_product.product_id
assert exc_info.value.details.get("marketplace_product_id") == test_marketplace_product.marketplace_product_id
def test_create_product_invalid_price(self, db):
"""Test product creation with invalid price raises InvalidProductDataException"""
product_data = ProductCreate(
product_id="SVC004",
title="Service Test Product",
"""Test product creation with invalid price raises InvalidMarketplaceProductDataException"""
product_data = MarketplaceProductCreate(
marketplace_product_id="SVC004",
title="Service Test MarketplaceProduct",
price="invalid_price",
)
with pytest.raises(InvalidProductDataException) as exc_info:
with pytest.raises(InvalidMarketplaceProductDataException) as exc_info:
self.service.create_product(db, product_data)
assert exc_info.value.error_code == "INVALID_PRODUCT_DATA"
assert "Invalid price format" in str(exc_info.value)
assert exc_info.value.details.get("field") == "price"
def test_get_product_by_id_or_raise_success(self, db, test_product):
def test_get_product_by_id_or_raise_success(self, db, test_marketplace_product):
"""Test successful product retrieval by ID"""
product = self.service.get_product_by_id_or_raise(db, test_product.product_id)
product = self.service.get_product_by_id_or_raise(db, test_marketplace_product.marketplace_product_id)
assert product.product_id == test_product.product_id
assert product.title == test_product.title
assert product.marketplace_product_id == test_marketplace_product.marketplace_product_id
assert product.title == test_marketplace_product.title
def test_get_product_by_id_or_raise_not_found(self, db):
"""Test product retrieval with non-existent ID raises ProductNotFoundException"""
with pytest.raises(ProductNotFoundException) as exc_info:
"""Test product retrieval with non-existent ID raises MarketplaceProductNotFoundException"""
with pytest.raises(MarketplaceProductNotFoundException) as exc_info:
self.service.get_product_by_id_or_raise(db, "NONEXISTENT")
assert exc_info.value.error_code == "PRODUCT_NOT_FOUND"
assert "NONEXISTENT" in str(exc_info.value)
assert exc_info.value.status_code == 404
assert exc_info.value.details.get("resource_type") == "Product"
assert exc_info.value.details.get("resource_type") == "MarketplaceProduct"
assert exc_info.value.details.get("identifier") == "NONEXISTENT"
def test_get_products_with_filters_success(self, db, test_product):
def test_get_products_with_filters_success(self, db, test_marketplace_product):
"""Test getting products with various filters"""
products, total = self.service.get_products_with_filters(
db, brand=test_product.brand
db, brand=test_marketplace_product.brand
)
assert total == 1
assert len(products) == 1
assert products[0].brand == test_product.brand
assert products[0].brand == test_marketplace_product.brand
def test_get_products_with_search(self, db, test_product):
def test_get_products_with_search(self, db, test_marketplace_product):
"""Test getting products with search term"""
products, total = self.service.get_products_with_filters(
db, search="Test Product"
db, search="Test MarketplaceProduct"
)
assert total >= 1
assert len(products) >= 1
# Verify search worked by checking that title contains search term
found_product = next((p for p in products if p.product_id == test_product.product_id), None)
found_product = next((p for p in products if p.marketplace_product_id == test_marketplace_product.marketplace_product_id), None)
assert found_product is not None
def test_update_product_success(self, db, test_product):
def test_update_product_success(self, db, test_marketplace_product):
"""Test successful product update"""
update_data = ProductUpdate(
title="Updated Product Title",
update_data = MarketplaceProductUpdate(
title="Updated MarketplaceProduct Title",
price="39.99"
)
updated_product = self.service.update_product(db, test_product.product_id, update_data)
updated_product = self.service.update_product(db, test_marketplace_product.marketplace_product_id, update_data)
assert updated_product.title == "Updated Product Title"
assert updated_product.title == "Updated MarketplaceProduct Title"
assert updated_product.price == "39.99" # Price is stored as string after processing
assert updated_product.product_id == test_product.product_id # ID unchanged
assert updated_product.marketplace_product_id == test_marketplace_product.marketplace_product_id # ID unchanged
def test_update_product_not_found(self, db):
"""Test updating non-existent product raises ProductNotFoundException"""
update_data = ProductUpdate(title="Updated Title")
"""Test updating non-existent product raises MarketplaceProductNotFoundException"""
update_data = MarketplaceProductUpdate(title="Updated Title")
with pytest.raises(ProductNotFoundException) as exc_info:
with pytest.raises(MarketplaceProductNotFoundException) as exc_info:
self.service.update_product(db, "NONEXISTENT", update_data)
assert exc_info.value.error_code == "PRODUCT_NOT_FOUND"
assert "NONEXISTENT" in str(exc_info.value)
def test_update_product_invalid_gtin(self, db, test_product):
"""Test updating product with invalid GTIN raises InvalidProductDataException"""
update_data = ProductUpdate(gtin="invalid_gtin")
def test_update_product_invalid_gtin(self, db, test_marketplace_product):
"""Test updating product with invalid GTIN raises InvalidMarketplaceProductDataException"""
update_data = MarketplaceProductUpdate(gtin="invalid_gtin")
with pytest.raises(InvalidProductDataException) as exc_info:
self.service.update_product(db, test_product.product_id, update_data)
with pytest.raises(InvalidMarketplaceProductDataException) as exc_info:
self.service.update_product(db, test_marketplace_product.marketplace_product_id, update_data)
assert exc_info.value.error_code == "INVALID_PRODUCT_DATA"
assert "Invalid GTIN format" in str(exc_info.value)
assert exc_info.value.details.get("field") == "gtin"
def test_update_product_empty_title(self, db, test_product):
"""Test updating product with empty title raises ProductValidationException"""
update_data = ProductUpdate(title="")
def test_update_product_empty_title(self, db, test_marketplace_product):
"""Test updating product with empty title raises MarketplaceProductValidationException"""
update_data = MarketplaceProductUpdate(title="")
with pytest.raises(ProductValidationException) as exc_info:
self.service.update_product(db, test_product.product_id, update_data)
with pytest.raises(MarketplaceProductValidationException) as exc_info:
self.service.update_product(db, test_marketplace_product.marketplace_product_id, update_data)
assert exc_info.value.error_code == "PRODUCT_VALIDATION_FAILED"
assert "Product title cannot be empty" in str(exc_info.value)
assert "MarketplaceProduct title cannot be empty" in str(exc_info.value)
assert exc_info.value.details.get("field") == "title"
def test_update_product_invalid_price(self, db, test_product):
"""Test updating product with invalid price raises InvalidProductDataException"""
update_data = ProductUpdate(price="invalid_price")
def test_update_product_invalid_price(self, db, test_marketplace_product):
"""Test updating product with invalid price raises InvalidMarketplaceProductDataException"""
update_data = MarketplaceProductUpdate(price="invalid_price")
with pytest.raises(InvalidProductDataException) as exc_info:
self.service.update_product(db, test_product.product_id, update_data)
with pytest.raises(InvalidMarketplaceProductDataException) as exc_info:
self.service.update_product(db, test_marketplace_product.marketplace_product_id, update_data)
assert exc_info.value.error_code == "INVALID_PRODUCT_DATA"
assert "Invalid price format" in str(exc_info.value)
assert exc_info.value.details.get("field") == "price"
def test_delete_product_success(self, db, test_product):
def test_delete_product_success(self, db, test_marketplace_product):
"""Test successful product deletion"""
result = self.service.delete_product(db, test_product.product_id)
result = self.service.delete_product(db, test_marketplace_product.marketplace_product_id)
assert result is True
# Verify product is deleted
deleted_product = self.service.get_product_by_id(db, test_product.product_id)
deleted_product = self.service.get_product_by_id(db, test_marketplace_product.marketplace_product_id)
assert deleted_product is None
def test_delete_product_not_found(self, db):
"""Test deleting non-existent product raises ProductNotFoundException"""
with pytest.raises(ProductNotFoundException) as exc_info:
"""Test deleting non-existent product raises MarketplaceProductNotFoundException"""
with pytest.raises(MarketplaceProductNotFoundException) as exc_info:
self.service.delete_product(db, "NONEXISTENT")
assert exc_info.value.error_code == "PRODUCT_NOT_FOUND"
assert "NONEXISTENT" in str(exc_info.value)
def test_get_stock_info_success(self, db, test_product_with_stock):
def test_get_stock_info_success(self, db, test_marketplace_product_with_stock):
"""Test getting stock info for product with stock"""
# Extract the product from the dictionary
product = test_product_with_stock['product']
marketplace_product = test_marketplace_product_with_stock['marketplace_product']
stock_info = self.service.get_stock_info(db, product.gtin)
stock_info = self.service.get_stock_info(db, marketplace_product.gtin)
assert stock_info is not None
assert stock_info.gtin == product.gtin
assert stock_info.gtin == marketplace_product.gtin
assert stock_info.total_quantity > 0
assert len(stock_info.locations) > 0
def test_get_stock_info_no_stock(self, db, test_product):
def test_get_stock_info_no_stock(self, db, test_marketplace_product):
"""Test getting stock info for product without stock"""
stock_info = self.service.get_stock_info(db, test_product.gtin or "1234567890123")
stock_info = self.service.get_stock_info(db, test_marketplace_product.gtin or "1234567890123")
assert stock_info is None
def test_product_exists_true(self, db, test_product):
def test_product_exists_true(self, db, test_marketplace_product):
"""Test product_exists returns True for existing product"""
exists = self.service.product_exists(db, test_product.product_id)
exists = self.service.product_exists(db, test_marketplace_product.marketplace_product_id)
assert exists is True
def test_product_exists_false(self, db):
@@ -257,7 +257,7 @@ class TestProductService:
exists = self.service.product_exists(db, "NONEXISTENT")
assert exists is False
def test_generate_csv_export_success(self, db, test_product):
def test_generate_csv_export_success(self, db, test_marketplace_product):
"""Test CSV export generation"""
csv_generator = self.service.generate_csv_export(db)
@@ -265,17 +265,17 @@ class TestProductService:
csv_lines = list(csv_generator)
assert len(csv_lines) > 1 # Header + at least one data row
assert csv_lines[0].startswith("product_id,title,description") # Check header
assert csv_lines[0].startswith("marketplace_product_id,title,description") # Check header
# Check that test product appears in CSV
csv_content = "".join(csv_lines)
assert test_product.product_id in csv_content
assert test_marketplace_product.marketplace_product_id in csv_content
def test_generate_csv_export_with_filters(self, db, test_product):
def test_generate_csv_export_with_filters(self, db, test_marketplace_product):
"""Test CSV export with marketplace filter"""
csv_generator = self.service.generate_csv_export(
db,
marketplace=test_product.marketplace
marketplace=test_marketplace_product.marketplace
)
csv_lines = list(csv_generator)
@@ -283,4 +283,4 @@ class TestProductService:
if len(csv_lines) > 1: # If there's data
csv_content = "".join(csv_lines)
assert test_product.marketplace in csv_content
assert test_marketplace_product.marketplace in csv_content

View File

@@ -7,7 +7,7 @@ from app.exceptions import (
ShopAlreadyExistsException,
UnauthorizedShopAccessException,
InvalidShopDataException,
ProductNotFoundException,
MarketplaceProductNotFoundException,
ShopProductAlreadyExistsException,
MaxShopsReachedException,
ValidationException,
@@ -179,7 +179,7 @@ class TestShopService:
def test_add_product_to_shop_success(self, db, test_shop, unique_product):
"""Test successfully adding product to shop"""
shop_product_data = ShopProductCreate(
product_id=unique_product.product_id,
marketplace_product_id=unique_product.marketplace_product_id,
price="15.99",
is_featured=True,
stock_quantity=5,
@@ -191,25 +191,25 @@ class TestShopService:
assert shop_product is not None
assert shop_product.shop_id == test_shop.id
assert shop_product.product_id == unique_product.id
assert shop_product.marketplace_product_id == unique_product.id
def test_add_product_to_shop_product_not_found(self, db, test_shop):
"""Test adding non-existent product to shop fails"""
shop_product_data = ShopProductCreate(product_id="NONEXISTENT", price="15.99")
shop_product_data = ShopProductCreate(marketplace_product_id="NONEXISTENT", price="15.99")
with pytest.raises(ProductNotFoundException) as exc_info:
with pytest.raises(MarketplaceProductNotFoundException) as exc_info:
self.service.add_product_to_shop(db, test_shop, shop_product_data)
exception = exc_info.value
assert exception.status_code == 404
assert exception.error_code == "PRODUCT_NOT_FOUND"
assert exception.details["resource_type"] == "Product"
assert exception.details["resource_type"] == "MarketplaceProduct"
assert exception.details["identifier"] == "NONEXISTENT"
def test_add_product_to_shop_already_exists(self, db, test_shop, shop_product):
"""Test adding product that's already in shop fails"""
shop_product_data = ShopProductCreate(
product_id=shop_product.product.product_id, price="15.99"
marketplace_product_id=shop_product.product.marketplace_product_id, price="15.99"
)
with pytest.raises(ShopProductAlreadyExistsException) as exc_info:
@@ -219,7 +219,7 @@ class TestShopService:
assert exception.status_code == 409
assert exception.error_code == "SHOP_PRODUCT_ALREADY_EXISTS"
assert exception.details["shop_code"] == test_shop.shop_code
assert exception.details["product_id"] == shop_product.product.product_id
assert exception.details["marketplace_product_id"] == shop_product.product.marketplace_product_id
def test_get_shop_products_owner_access(
self, db, test_user, test_shop, shop_product
@@ -229,8 +229,8 @@ class TestShopService:
assert total >= 1
assert len(products) >= 1
product_ids = [p.product_id for p in products]
assert shop_product.product_id in product_ids
product_ids = [p.marketplace_product_id for p in products]
assert shop_product.marketplace_product_id in product_ids
def test_get_shop_products_access_denied(self, db, test_user, inactive_shop):
"""Test non-owner cannot access unverified shop products"""
@@ -300,7 +300,7 @@ class TestShopService:
monkeypatch.setattr(db, "commit", mock_commit)
shop_product_data = ShopProductCreate(
product_id=unique_product.product_id, price="15.99"
marketplace_product_id=unique_product.marketplace_product_id, price="15.99"
)
with pytest.raises(ValidationException) as exc_info:

View File

@@ -2,7 +2,7 @@
import pytest
from app.services.stats_service import StatsService
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
from models.database.stock import Stock
@@ -15,7 +15,7 @@ class TestStatsService:
"""Setup method following the same pattern as other service tests"""
self.service = StatsService()
def test_get_comprehensive_stats_basic(self, db, test_product, test_stock):
def test_get_comprehensive_stats_basic(self, db, test_marketplace_product, test_stock):
"""Test getting comprehensive stats with basic data"""
stats = self.service.get_comprehensive_stats(db)
@@ -31,13 +31,13 @@ class TestStatsService:
assert stats["total_stock_entries"] >= 1
assert stats["total_inventory_quantity"] >= 10 # test_stock has quantity 10
def test_get_comprehensive_stats_multiple_products(self, db, test_product):
def test_get_comprehensive_stats_multiple_products(self, db, test_marketplace_product):
"""Test comprehensive stats with multiple products across different dimensions"""
# Create products with different brands, categories, marketplaces
additional_products = [
Product(
product_id="PROD002",
title="Product 2",
MarketplaceProduct(
marketplace_product_id="PROD002",
title="MarketplaceProduct 2",
brand="DifferentBrand",
google_product_category="Different Category",
marketplace="Amazon",
@@ -45,9 +45,9 @@ class TestStatsService:
price="15.99",
currency="EUR",
),
Product(
product_id="PROD003",
title="Product 3",
MarketplaceProduct(
marketplace_product_id="PROD003",
title="MarketplaceProduct 3",
brand="ThirdBrand",
google_product_category="Third Category",
marketplace="eBay",
@@ -55,12 +55,12 @@ class TestStatsService:
price="25.99",
currency="USD",
),
Product(
product_id="PROD004",
title="Product 4",
brand="TestBrand", # Same as test_product
MarketplaceProduct(
marketplace_product_id="PROD004",
title="MarketplaceProduct 4",
brand="TestBrand", # Same as test_marketplace_product
google_product_category="Different Category",
marketplace="Letzshop", # Same as test_product
marketplace="Letzshop", # Same as test_marketplace_product
shop_name="DifferentShop",
price="35.99",
currency="EUR",
@@ -71,7 +71,7 @@ class TestStatsService:
stats = self.service.get_comprehensive_stats(db)
assert stats["total_products"] >= 4 # test_product + 3 additional
assert stats["total_products"] >= 4 # test_marketplace_product + 3 additional
assert stats["unique_brands"] >= 3 # TestBrand, DifferentBrand, ThirdBrand
assert stats["unique_categories"] >= 2 # At least 2 different categories
assert stats["unique_marketplaces"] >= 3 # Letzshop, Amazon, eBay
@@ -81,9 +81,9 @@ class TestStatsService:
"""Test comprehensive stats handles null/empty values correctly"""
# Create products with null/empty values
products_with_nulls = [
Product(
product_id="NULL001",
title="Product with Nulls",
MarketplaceProduct(
marketplace_product_id="NULL001",
title="MarketplaceProduct with Nulls",
brand=None, # Null brand
google_product_category=None, # Null category
marketplace=None, # Null marketplace
@@ -91,9 +91,9 @@ class TestStatsService:
price="10.00",
currency="EUR",
),
Product(
product_id="EMPTY001",
title="Product with Empty Values",
MarketplaceProduct(
marketplace_product_id="EMPTY001",
title="MarketplaceProduct with Empty Values",
brand="", # Empty brand
google_product_category="", # Empty category
marketplace="", # Empty marketplace
@@ -115,7 +115,7 @@ class TestStatsService:
assert isinstance(stats["unique_marketplaces"], int)
assert isinstance(stats["unique_shops"], int)
def test_get_marketplace_breakdown_stats_basic(self, db, test_product):
def test_get_marketplace_breakdown_stats_basic(self, db, test_marketplace_product):
"""Test getting marketplace breakdown stats with basic data"""
stats = self.service.get_marketplace_breakdown_stats(db)
@@ -124,7 +124,7 @@ class TestStatsService:
# Find our test marketplace in the results
test_marketplace_stat = next(
(stat for stat in stats if stat["marketplace"] == test_product.marketplace),
(stat for stat in stats if stat["marketplace"] == test_marketplace_product.marketplace),
None,
)
assert test_marketplace_stat is not None
@@ -133,32 +133,32 @@ class TestStatsService:
assert test_marketplace_stat["unique_brands"] >= 1
def test_get_marketplace_breakdown_stats_multiple_marketplaces(
self, db, test_product
self, db, test_marketplace_product
):
"""Test marketplace breakdown with multiple marketplaces"""
# Create products for different marketplaces
marketplace_products = [
Product(
product_id="AMAZON001",
title="Amazon Product 1",
MarketplaceProduct(
marketplace_product_id="AMAZON001",
title="Amazon MarketplaceProduct 1",
brand="AmazonBrand1",
marketplace="Amazon",
shop_name="AmazonShop1",
price="20.00",
currency="EUR",
),
Product(
product_id="AMAZON002",
title="Amazon Product 2",
MarketplaceProduct(
marketplace_product_id="AMAZON002",
title="Amazon MarketplaceProduct 2",
brand="AmazonBrand2",
marketplace="Amazon",
shop_name="AmazonShop2",
price="25.00",
currency="EUR",
),
Product(
product_id="EBAY001",
title="eBay Product",
MarketplaceProduct(
marketplace_product_id="EBAY001",
title="eBay MarketplaceProduct",
brand="eBayBrand",
marketplace="eBay",
shop_name="eBayShop",
@@ -171,11 +171,11 @@ class TestStatsService:
stats = self.service.get_marketplace_breakdown_stats(db)
# Should have at least 3 marketplaces: test_product.marketplace, Amazon, eBay
# Should have at least 3 marketplaces: test_marketplace_product.marketplace, Amazon, eBay
marketplace_names = [stat["marketplace"] for stat in stats]
assert "Amazon" in marketplace_names
assert "eBay" in marketplace_names
assert test_product.marketplace in marketplace_names
assert test_marketplace_product.marketplace in marketplace_names
# Check Amazon stats specifically
amazon_stat = next(stat for stat in stats if stat["marketplace"] == "Amazon")
@@ -192,9 +192,9 @@ class TestStatsService:
def test_get_marketplace_breakdown_stats_excludes_nulls(self, db):
"""Test marketplace breakdown excludes products with null marketplaces"""
# Create product with null marketplace
null_marketplace_product = Product(
product_id="NULLMARKET001",
title="Product without marketplace",
null_marketplace_product = MarketplaceProduct(
marketplace_product_id="NULLMARKET001",
title="MarketplaceProduct without marketplace",
marketplace=None,
shop_name="SomeShop",
brand="SomeBrand",
@@ -212,29 +212,29 @@ class TestStatsService:
]
assert None not in marketplace_names
def test_get_product_count(self, db, test_product):
def test_get_product_count(self, db, test_marketplace_product):
"""Test getting total product count"""
count = self.service._get_product_count(db)
assert count >= 1
assert isinstance(count, int)
def test_get_unique_brands_count(self, db, test_product):
def test_get_unique_brands_count(self, db, test_marketplace_product):
"""Test getting unique brands count"""
# Add products with different brands
brand_products = [
Product(
product_id="BRAND001",
title="Brand Product 1",
MarketplaceProduct(
marketplace_product_id="BRAND001",
title="Brand MarketplaceProduct 1",
brand="BrandA",
marketplace="Test",
shop_name="TestShop",
price="10.00",
currency="EUR",
),
Product(
product_id="BRAND002",
title="Brand Product 2",
MarketplaceProduct(
marketplace_product_id="BRAND002",
title="Brand MarketplaceProduct 2",
brand="BrandB",
marketplace="Test",
shop_name="TestShop",
@@ -249,25 +249,25 @@ class TestStatsService:
assert (
count >= 2
) # At least BrandA and BrandB, plus possibly test_product brand
) # At least BrandA and BrandB, plus possibly test_marketplace_product brand
assert isinstance(count, int)
def test_get_unique_categories_count(self, db, test_product):
def test_get_unique_categories_count(self, db, test_marketplace_product):
"""Test getting unique categories count"""
# Add products with different categories
category_products = [
Product(
product_id="CAT001",
title="Category Product 1",
MarketplaceProduct(
marketplace_product_id="CAT001",
title="Category MarketplaceProduct 1",
google_product_category="Electronics",
marketplace="Test",
shop_name="TestShop",
price="10.00",
currency="EUR",
),
Product(
product_id="CAT002",
title="Category Product 2",
MarketplaceProduct(
marketplace_product_id="CAT002",
title="Category MarketplaceProduct 2",
google_product_category="Books",
marketplace="Test",
shop_name="TestShop",
@@ -283,21 +283,21 @@ class TestStatsService:
assert count >= 2 # At least Electronics and Books
assert isinstance(count, int)
def test_get_unique_marketplaces_count(self, db, test_product):
def test_get_unique_marketplaces_count(self, db, test_marketplace_product):
"""Test getting unique marketplaces count"""
# Add products with different marketplaces
marketplace_products = [
Product(
product_id="MARKET001",
title="Marketplace Product 1",
MarketplaceProduct(
marketplace_product_id="MARKET001",
title="Marketplace MarketplaceProduct 1",
marketplace="Amazon",
shop_name="AmazonShop",
price="10.00",
currency="EUR",
),
Product(
product_id="MARKET002",
title="Marketplace Product 2",
MarketplaceProduct(
marketplace_product_id="MARKET002",
title="Marketplace MarketplaceProduct 2",
marketplace="eBay",
shop_name="eBayShop",
price="15.00",
@@ -309,24 +309,24 @@ class TestStatsService:
count = self.service._get_unique_marketplaces_count(db)
assert count >= 2 # At least Amazon and eBay, plus test_product marketplace
assert count >= 2 # At least Amazon and eBay, plus test_marketplace_product marketplace
assert isinstance(count, int)
def test_get_unique_shops_count(self, db, test_product):
def test_get_unique_shops_count(self, db, test_marketplace_product):
"""Test getting unique shops count"""
# Add products with different shop names
shop_products = [
Product(
product_id="SHOP001",
title="Shop Product 1",
MarketplaceProduct(
marketplace_product_id="SHOP001",
title="Shop MarketplaceProduct 1",
marketplace="Test",
shop_name="ShopA",
price="10.00",
currency="EUR",
),
Product(
product_id="SHOP002",
title="Shop Product 2",
MarketplaceProduct(
marketplace_product_id="SHOP002",
title="Shop MarketplaceProduct 2",
marketplace="Test",
shop_name="ShopB",
price="15.00",
@@ -338,7 +338,7 @@ class TestStatsService:
count = self.service._get_unique_shops_count(db)
assert count >= 2 # At least ShopA and ShopB, plus test_product shop
assert count >= 2 # At least ShopA and ShopB, plus test_marketplace_product shop
assert isinstance(count, int)
def test_get_stock_statistics(self, db, test_stock):
@@ -374,27 +374,27 @@ class TestStatsService:
"""Test getting brands for a specific marketplace"""
# Create products for specific marketplace
marketplace_products = [
Product(
product_id="SPECIFIC001",
title="Specific Product 1",
MarketplaceProduct(
marketplace_product_id="SPECIFIC001",
title="Specific MarketplaceProduct 1",
brand="SpecificBrand1",
marketplace="SpecificMarket",
shop_name="SpecificShop1",
price="10.00",
currency="EUR",
),
Product(
product_id="SPECIFIC002",
title="Specific Product 2",
MarketplaceProduct(
marketplace_product_id="SPECIFIC002",
title="Specific MarketplaceProduct 2",
brand="SpecificBrand2",
marketplace="SpecificMarket",
shop_name="SpecificShop2",
price="15.00",
currency="EUR",
),
Product(
product_id="OTHER001",
title="Other Product",
MarketplaceProduct(
marketplace_product_id="OTHER001",
title="Other MarketplaceProduct",
brand="OtherBrand",
marketplace="OtherMarket",
shop_name="OtherShop",
@@ -416,18 +416,18 @@ class TestStatsService:
"""Test getting shops for a specific marketplace"""
# Create products for specific marketplace
marketplace_products = [
Product(
product_id="SHOPTEST001",
title="Shop Test Product 1",
MarketplaceProduct(
marketplace_product_id="SHOPTEST001",
title="Shop Test MarketplaceProduct 1",
brand="TestBrand",
marketplace="TestMarketplace",
shop_name="TestShop1",
price="10.00",
currency="EUR",
),
Product(
product_id="SHOPTEST002",
title="Shop Test Product 2",
MarketplaceProduct(
marketplace_product_id="SHOPTEST002",
title="Shop Test MarketplaceProduct 2",
brand="TestBrand",
marketplace="TestMarketplace",
shop_name="TestShop2",
@@ -448,25 +448,25 @@ class TestStatsService:
"""Test getting product count for a specific marketplace"""
# Create products for specific marketplace
marketplace_products = [
Product(
product_id="COUNT001",
title="Count Product 1",
MarketplaceProduct(
marketplace_product_id="COUNT001",
title="Count MarketplaceProduct 1",
marketplace="CountMarketplace",
shop_name="CountShop",
price="10.00",
currency="EUR",
),
Product(
product_id="COUNT002",
title="Count Product 2",
MarketplaceProduct(
marketplace_product_id="COUNT002",
title="Count MarketplaceProduct 2",
marketplace="CountMarketplace",
shop_name="CountShop",
price="15.00",
currency="EUR",
),
Product(
product_id="COUNT003",
title="Count Product 3",
MarketplaceProduct(
marketplace_product_id="COUNT003",
title="Count MarketplaceProduct 3",
marketplace="CountMarketplace",
shop_name="CountShop",
price="20.00",

View File

@@ -14,7 +14,7 @@ from app.exceptions import (
ValidationException,
)
from models.schemas.stock import StockAdd, StockCreate, StockUpdate
from models.database.product import Product
from models.database.marketplace_product import MarketplaceProduct
from models.database.stock import Stock
@@ -254,7 +254,7 @@ class TestStockService:
# The service prevents negative stock through InsufficientStockException
assert exc_info.value.error_code == "INSUFFICIENT_STOCK"
def test_get_stock_by_gtin_success(self, db, test_stock, test_product):
def test_get_stock_by_gtin_success(self, db, test_stock, test_marketplace_product):
"""Test getting stock summary by GTIN successfully."""
result = self.service.get_stock_by_gtin(db, test_stock.gtin)
@@ -263,11 +263,11 @@ class TestStockService:
assert len(result.locations) == 1
assert result.locations[0].location == test_stock.location
assert result.locations[0].quantity == test_stock.quantity
assert result.product_title == test_product.title
assert result.product_title == test_marketplace_product.title
def test_get_stock_by_gtin_multiple_locations_success(self, db, test_product):
def test_get_stock_by_gtin_multiple_locations_success(self, db, test_marketplace_product):
"""Test getting stock summary with multiple locations successfully."""
unique_gtin = test_product.gtin
unique_gtin = test_marketplace_product.gtin
unique_id = str(uuid.uuid4())[:8]
# Create multiple stock entries for the same GTIN with unique locations
@@ -301,13 +301,13 @@ class TestStockService:
assert exc_info.value.error_code == "STOCK_VALIDATION_FAILED"
assert "Invalid GTIN format" in str(exc_info.value)
def test_get_total_stock_success(self, db, test_stock, test_product):
def test_get_total_stock_success(self, db, test_stock, test_marketplace_product):
"""Test getting total stock for a GTIN successfully."""
result = self.service.get_total_stock(db, test_stock.gtin)
assert result["gtin"] == test_stock.gtin
assert result["total_quantity"] == test_stock.quantity
assert result["product_title"] == test_product.title
assert result["product_title"] == test_marketplace_product.title
assert result["locations_count"] == 1
def test_get_total_stock_invalid_gtin_validation_error(self, db):
@@ -415,7 +415,7 @@ class TestStockService:
assert exc_info.value.error_code == "STOCK_NOT_FOUND"
assert "99999" in str(exc_info.value)
def test_get_low_stock_items_success(self, db, test_stock, test_product):
def test_get_low_stock_items_success(self, db, test_stock, test_marketplace_product):
"""Test getting low stock items successfully."""
# Set stock to a low value
test_stock.quantity = 5
@@ -428,7 +428,7 @@ class TestStockService:
assert low_stock_item is not None
assert low_stock_item["current_quantity"] == 5
assert low_stock_item["location"] == test_stock.location
assert low_stock_item["product_title"] == test_product.title
assert low_stock_item["product_title"] == test_marketplace_product.title
def test_get_low_stock_items_invalid_threshold_error(self, db):
"""Test getting low stock items with invalid threshold returns InvalidQuantityException."""
@@ -491,9 +491,9 @@ class TestStockService:
@pytest.fixture
def test_product_with_stock(db, test_stock):
"""Create a test product that corresponds to the test stock."""
product = Product(
product_id="STOCK_TEST_001",
title="Stock Test Product",
product = MarketplaceProduct(
marketplace_product_id="STOCK_TEST_001",
title="Stock Test MarketplaceProduct",
gtin=test_stock.gtin,
price="29.99",
brand="TestBrand",

View File

@@ -18,7 +18,7 @@ class TestCSVProcessor:
def test_download_csv_encoding_fallback(self, mock_get):
"""Test CSV download with encoding fallback"""
# Create content with special characters that would fail UTF-8 if not properly encoded
special_content = "product_id,title,price\nTEST001,Café Product,10.99"
special_content = "marketplace_product_id,title,price\nTEST001,Café MarketplaceProduct,10.99"
mock_response = Mock()
mock_response.status_code = 200
@@ -31,7 +31,7 @@ class TestCSVProcessor:
mock_get.assert_called_once_with("http://example.com/test.csv", timeout=30)
assert isinstance(csv_content, str)
assert "Café Product" in csv_content
assert "Café MarketplaceProduct" in csv_content
@patch("requests.get")
def test_download_csv_encoding_ignore_fallback(self, mock_get):
@@ -41,7 +41,7 @@ class TestCSVProcessor:
mock_response.status_code = 200
# Create bytes that will fail most encodings
mock_response.content = (
b"product_id,title,price\nTEST001,\xff\xfe Product,10.99"
b"marketplace_product_id,title,price\nTEST001,\xff\xfe MarketplaceProduct,10.99"
)
mock_response.raise_for_status.return_value = None
mock_get.return_value = mock_response
@@ -51,7 +51,7 @@ class TestCSVProcessor:
mock_get.assert_called_once_with("http://example.com/test.csv", timeout=30)
assert isinstance(csv_content, str)
# Should still contain basic content even with ignored errors
assert "product_id,title,price" in csv_content
assert "marketplace_product_id,title,price" in csv_content
assert "TEST001" in csv_content
@patch("requests.get")
@@ -91,15 +91,15 @@ class TestCSVProcessor:
def test_parse_csv_content(self):
"""Test CSV content parsing"""
csv_content = """product_id,title,price,marketplace
TEST001,Test Product 1,10.99,TestMarket
TEST002,Test Product 2,15.99,TestMarket"""
csv_content = """marketplace_product_id,title,price,marketplace
TEST001,Test MarketplaceProduct 1,10.99,TestMarket
TEST002,Test MarketplaceProduct 2,15.99,TestMarket"""
df = self.processor.parse_csv(csv_content)
assert len(df) == 2
assert "product_id" in df.columns
assert df.iloc[0]["product_id"] == "TEST001"
assert "marketplace_product_id" in df.columns
assert df.iloc[0]["marketplace_product_id"] == "TEST001"
assert df.iloc[1]["price"] == 15.99
@pytest.mark.asyncio
@@ -112,8 +112,8 @@ TEST002,Test Product 2,15.99,TestMarket"""
mock_download.return_value = "csv_content"
mock_df = pd.DataFrame(
{
"product_id": ["TEST001", "TEST002"],
"title": ["Product 1", "Product 2"],
"marketplace_product_id": ["TEST001", "TEST002"],
"title": ["MarketplaceProduct 1", "MarketplaceProduct 2"],
"price": ["10.99", "15.99"],
"marketplace": ["TestMarket", "TestMarket"],
"shop_name": ["TestShop", "TestShop"],