forked from cartsnitch/api
feat: merge cartsnitch/api into api/ subdirectory
Consolidate API gateway service into monorepo. Squashed from https://github.com/cartsnitch/api main (89bacb1). Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
"""Shared fixtures for E2E integration tests.
|
||||
|
||||
Seeds a realistic dataset with stores, products, price history,
|
||||
purchases, coupons, and shrinkflation events so E2E flows can
|
||||
exercise cross-resource queries against real data.
|
||||
"""
|
||||
|
||||
from datetime import date, timedelta
|
||||
from decimal import Decimal
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from cartsnitch_api.auth.jwt import decode_token
|
||||
from cartsnitch_api.models import (
|
||||
Coupon,
|
||||
NormalizedProduct,
|
||||
PriceHistory,
|
||||
Purchase,
|
||||
PurchaseItem,
|
||||
ShrinkflationEvent,
|
||||
Store,
|
||||
)
|
||||
|
||||
# Shared test constants
|
||||
ZERO_UUID = "00000000-0000-0000-0000-000000000000"
|
||||
BAD_UUID = "not-a-uuid"
|
||||
# Fixed anchor date for deterministic tests
|
||||
ANCHOR_DATE = date(2026, 3, 15)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def seed_data(db_engine, auth_headers):
|
||||
"""Seed a full dataset and return identifiers for test assertions."""
|
||||
factory = async_sessionmaker(db_engine, class_=AsyncSession, expire_on_commit=False)
|
||||
async with factory() as session:
|
||||
# -- Stores --
|
||||
meijer = Store(name="Meijer", slug="meijer")
|
||||
kroger = Store(name="Kroger", slug="kroger")
|
||||
target = Store(name="Target", slug="target")
|
||||
session.add_all([meijer, kroger, target])
|
||||
await session.flush()
|
||||
|
||||
# -- Products --
|
||||
cheerios = NormalizedProduct(
|
||||
canonical_name="Cheerios 18oz",
|
||||
category="pantry",
|
||||
brand="General Mills",
|
||||
size="18",
|
||||
size_unit="oz",
|
||||
upc_variants=["016000275263"],
|
||||
)
|
||||
milk = NormalizedProduct(
|
||||
canonical_name="Whole Milk 1gal",
|
||||
category="dairy",
|
||||
brand="Meijer",
|
||||
size="1",
|
||||
size_unit="gal",
|
||||
)
|
||||
chicken = NormalizedProduct(
|
||||
canonical_name="Chicken Breast 1lb",
|
||||
category="meat",
|
||||
brand=None,
|
||||
size="1",
|
||||
size_unit="lb",
|
||||
)
|
||||
session.add_all([cheerios, milk, chicken])
|
||||
await session.flush()
|
||||
|
||||
# -- Price history (multiple dates, multiple stores) --
|
||||
today = ANCHOR_DATE
|
||||
prices = []
|
||||
# Cheerios at Meijer: price increase over time
|
||||
for i, price_val in enumerate([Decimal("3.99"), Decimal("4.29"), Decimal("4.79")]):
|
||||
prices.append(
|
||||
PriceHistory(
|
||||
normalized_product_id=cheerios.id,
|
||||
store_id=meijer.id,
|
||||
observed_date=today - timedelta(days=60 - i * 30),
|
||||
regular_price=price_val,
|
||||
source="receipt",
|
||||
)
|
||||
)
|
||||
# Cheerios at Kroger: stable price
|
||||
for i in range(3):
|
||||
prices.append(
|
||||
PriceHistory(
|
||||
normalized_product_id=cheerios.id,
|
||||
store_id=kroger.id,
|
||||
observed_date=today - timedelta(days=60 - i * 30),
|
||||
regular_price=Decimal("4.49"),
|
||||
source="catalog",
|
||||
)
|
||||
)
|
||||
# Milk at Meijer
|
||||
prices.append(
|
||||
PriceHistory(
|
||||
normalized_product_id=milk.id,
|
||||
store_id=meijer.id,
|
||||
observed_date=today - timedelta(days=7),
|
||||
regular_price=Decimal("3.29"),
|
||||
source="receipt",
|
||||
)
|
||||
)
|
||||
# Milk at Kroger
|
||||
prices.append(
|
||||
PriceHistory(
|
||||
normalized_product_id=milk.id,
|
||||
store_id=kroger.id,
|
||||
observed_date=today - timedelta(days=5),
|
||||
regular_price=Decimal("3.49"),
|
||||
source="catalog",
|
||||
)
|
||||
)
|
||||
# Chicken at Target
|
||||
prices.append(
|
||||
PriceHistory(
|
||||
normalized_product_id=chicken.id,
|
||||
store_id=target.id,
|
||||
observed_date=today - timedelta(days=3),
|
||||
regular_price=Decimal("5.99"),
|
||||
source="catalog",
|
||||
)
|
||||
)
|
||||
session.add_all(prices)
|
||||
await session.flush()
|
||||
|
||||
# -- Purchases (need the user_id from the registered test user) --
|
||||
token = auth_headers["Authorization"].split(" ")[1]
|
||||
payload = decode_token(token)
|
||||
user_id = UUID(payload["sub"])
|
||||
|
||||
purchase1 = Purchase(
|
||||
user_id=user_id,
|
||||
store_id=meijer.id,
|
||||
receipt_id="meijer-2026-001",
|
||||
purchase_date=today - timedelta(days=10),
|
||||
total=Decimal("23.45"),
|
||||
subtotal=Decimal("21.50"),
|
||||
tax=Decimal("1.95"),
|
||||
)
|
||||
purchase2 = Purchase(
|
||||
user_id=user_id,
|
||||
store_id=kroger.id,
|
||||
receipt_id="kroger-2026-001",
|
||||
purchase_date=today - timedelta(days=5),
|
||||
total=Decimal("15.78"),
|
||||
subtotal=Decimal("14.50"),
|
||||
tax=Decimal("1.28"),
|
||||
)
|
||||
session.add_all([purchase1, purchase2])
|
||||
await session.flush()
|
||||
|
||||
# -- Purchase Items --
|
||||
item1 = PurchaseItem(
|
||||
purchase_id=purchase1.id,
|
||||
product_name_raw="Cheerios 18oz Box",
|
||||
quantity=Decimal("1"),
|
||||
unit_price=Decimal("4.79"),
|
||||
extended_price=Decimal("4.79"),
|
||||
normalized_product_id=cheerios.id,
|
||||
)
|
||||
item2 = PurchaseItem(
|
||||
purchase_id=purchase1.id,
|
||||
product_name_raw="Meijer Whole Milk 1gal",
|
||||
quantity=Decimal("2"),
|
||||
unit_price=Decimal("3.29"),
|
||||
extended_price=Decimal("6.58"),
|
||||
normalized_product_id=milk.id,
|
||||
)
|
||||
item3 = PurchaseItem(
|
||||
purchase_id=purchase2.id,
|
||||
product_name_raw="KRO CHEERIOS 18OZ",
|
||||
quantity=Decimal("1"),
|
||||
unit_price=Decimal("4.49"),
|
||||
extended_price=Decimal("4.49"),
|
||||
normalized_product_id=cheerios.id,
|
||||
)
|
||||
session.add_all([item1, item2, item3])
|
||||
await session.flush()
|
||||
|
||||
# -- Coupons --
|
||||
coupon1 = Coupon(
|
||||
store_id=meijer.id,
|
||||
normalized_product_id=cheerios.id,
|
||||
title="$1 off Cheerios",
|
||||
description="Save $1 on any Cheerios 18oz or larger",
|
||||
discount_type="fixed",
|
||||
discount_value=Decimal("1.00"),
|
||||
valid_from=today - timedelta(days=7),
|
||||
valid_to=today + timedelta(days=30),
|
||||
)
|
||||
coupon2 = Coupon(
|
||||
store_id=kroger.id,
|
||||
normalized_product_id=None,
|
||||
title="10% off dairy",
|
||||
description="10% off all dairy products",
|
||||
discount_type="percent",
|
||||
discount_value=Decimal("10.00"),
|
||||
valid_from=today - timedelta(days=3),
|
||||
valid_to=today + timedelta(days=14),
|
||||
)
|
||||
session.add_all([coupon1, coupon2])
|
||||
await session.flush()
|
||||
|
||||
# -- Shrinkflation events --
|
||||
shrink = ShrinkflationEvent(
|
||||
normalized_product_id=cheerios.id,
|
||||
detected_date=today - timedelta(days=15),
|
||||
old_size="20",
|
||||
new_size="18",
|
||||
old_unit="oz",
|
||||
new_unit="oz",
|
||||
price_at_old_size=Decimal("3.99"),
|
||||
price_at_new_size=Decimal("4.29"),
|
||||
confidence=Decimal("0.95"),
|
||||
notes="Size reduced from 20oz to 18oz while price increased",
|
||||
)
|
||||
session.add(shrink)
|
||||
await session.commit()
|
||||
|
||||
for obj in [
|
||||
meijer,
|
||||
kroger,
|
||||
target,
|
||||
cheerios,
|
||||
milk,
|
||||
chicken,
|
||||
purchase1,
|
||||
purchase2,
|
||||
item1,
|
||||
item2,
|
||||
item3,
|
||||
coupon1,
|
||||
coupon2,
|
||||
shrink,
|
||||
]:
|
||||
await session.refresh(obj)
|
||||
|
||||
return {
|
||||
"headers": auth_headers,
|
||||
"user_id": user_id,
|
||||
"stores": {"meijer": meijer, "kroger": kroger, "target": target},
|
||||
"products": {"cheerios": cheerios, "milk": milk, "chicken": chicken},
|
||||
"purchases": {"meijer_trip": purchase1, "kroger_trip": purchase2},
|
||||
"items": {"cheerios_meijer": item1, "milk_meijer": item2, "cheerios_kroger": item3},
|
||||
"coupons": {"cheerios_coupon": coupon1, "dairy_coupon": coupon2},
|
||||
"shrinkflation": {"cheerios_shrink": shrink},
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
"""E2E: Auth and token validation flows."""
|
||||
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAuthRegistrationLogin:
|
||||
"""Full registration → login → token refresh → profile flow."""
|
||||
|
||||
async def test_full_auth_lifecycle(self, client, db_engine):
|
||||
"""Register → login → get profile → refresh → get profile again."""
|
||||
# Register
|
||||
reg = await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "lifecycle@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "Lifecycle User",
|
||||
},
|
||||
)
|
||||
assert reg.status_code == 201
|
||||
tokens = reg.json()
|
||||
assert "access_token" in tokens
|
||||
assert "refresh_token" in tokens
|
||||
assert tokens["token_type"] == "bearer"
|
||||
assert tokens["expires_in"] > 0
|
||||
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
# Get profile with access token
|
||||
me = await client.get("/auth/me", headers=headers)
|
||||
assert me.status_code == 200
|
||||
assert me.json()["email"] == "lifecycle@example.com"
|
||||
assert me.json()["display_name"] == "Lifecycle User"
|
||||
|
||||
# Sleep 1s so the new token has a different exp than the registration token
|
||||
await asyncio.sleep(1)
|
||||
|
||||
# Login with same credentials
|
||||
login = await client.post(
|
||||
"/auth/login",
|
||||
json={"email": "lifecycle@example.com", "password": "securepass123"},
|
||||
)
|
||||
assert login.status_code == 200
|
||||
login_tokens = login.json()
|
||||
assert login_tokens["access_token"] != tokens["access_token"]
|
||||
|
||||
# Refresh token
|
||||
refresh = await client.post(
|
||||
"/auth/refresh",
|
||||
json={"refresh_token": tokens["refresh_token"]},
|
||||
)
|
||||
assert refresh.status_code == 200
|
||||
new_tokens = refresh.json()
|
||||
assert new_tokens["access_token"] != tokens["access_token"]
|
||||
|
||||
# Use refreshed token to access profile
|
||||
new_headers = {"Authorization": f"Bearer {new_tokens['access_token']}"}
|
||||
me2 = await client.get("/auth/me", headers=new_headers)
|
||||
assert me2.status_code == 200
|
||||
assert me2.json()["email"] == "lifecycle@example.com"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestTokenValidation:
|
||||
"""Token edge cases and error responses."""
|
||||
|
||||
async def test_expired_token_rejected(self, client, db_engine):
|
||||
"""Manually craft an expired token and verify rejection."""
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from jose import jwt
|
||||
|
||||
from cartsnitch_api.config import settings
|
||||
|
||||
payload = {
|
||||
"sub": str(uuid.uuid4()),
|
||||
"exp": datetime.now(UTC) - timedelta(minutes=5),
|
||||
"type": "access",
|
||||
}
|
||||
token = jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
|
||||
resp = await client.get("/auth/me", headers={"Authorization": f"Bearer {token}"})
|
||||
assert resp.status_code == 401
|
||||
|
||||
async def test_invalid_token_rejected(self, client, db_engine):
|
||||
resp = await client.get("/auth/me", headers={"Authorization": "Bearer not-a-real-token"})
|
||||
assert resp.status_code == 401
|
||||
|
||||
async def test_missing_auth_header(self, client, db_engine):
|
||||
resp = await client.get("/auth/me")
|
||||
assert resp.status_code in (401, 403)
|
||||
|
||||
async def test_refresh_token_cannot_access_endpoints(self, client, db_engine):
|
||||
"""A refresh token should not work as an access token."""
|
||||
reg = await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "refresh-test@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "Refresh Test",
|
||||
},
|
||||
)
|
||||
refresh_token = reg.json()["refresh_token"]
|
||||
resp = await client.get("/auth/me", headers={"Authorization": f"Bearer {refresh_token}"})
|
||||
assert resp.status_code == 401
|
||||
|
||||
async def test_deleted_user_token_invalid(self, client, db_engine):
|
||||
"""After deleting an account, tokens should no longer work."""
|
||||
reg = await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "delete-me@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "Delete Me",
|
||||
},
|
||||
)
|
||||
tokens = reg.json()
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
# Delete account
|
||||
delete_resp = await client.delete("/auth/me", headers=headers)
|
||||
assert delete_resp.status_code == 204
|
||||
|
||||
# Profile should fail
|
||||
me = await client.get("/auth/me", headers=headers)
|
||||
assert me.status_code in (401, 404)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAuthProtectedEndpoints:
|
||||
"""Verify auth is enforced on all user-specific endpoints."""
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"method,path",
|
||||
[
|
||||
("GET", "/purchases"),
|
||||
("GET", "/products"),
|
||||
("GET", "/prices/trends"),
|
||||
("GET", "/prices/increases"),
|
||||
("GET", "/coupons"),
|
||||
("GET", "/alerts"),
|
||||
("GET", "/me/stores"),
|
||||
],
|
||||
)
|
||||
async def test_endpoints_require_auth(self, client, db_engine, method, path):
|
||||
resp = await client.request(method, path)
|
||||
assert resp.status_code in (401, 403), f"{method} {path} should require auth"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestCrossUserDataIsolation:
|
||||
"""Verify that users cannot access other users' data."""
|
||||
|
||||
async def test_user_b_cannot_access_user_a_purchases(self, client, seed_data):
|
||||
"""Register a second user and verify they cannot see User A's purchases."""
|
||||
# User A's purchase (from seed_data)
|
||||
purchase_id = str(seed_data["purchases"]["meijer_trip"].id)
|
||||
|
||||
# Register User B
|
||||
reg = await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "userb@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "User B",
|
||||
},
|
||||
)
|
||||
assert reg.status_code == 201
|
||||
user_b_headers = {"Authorization": f"Bearer {reg.json()['access_token']}"}
|
||||
|
||||
# User B tries to access User A's specific purchase
|
||||
resp = await client.get(f"/purchases/{purchase_id}", headers=user_b_headers)
|
||||
assert resp.status_code in (403, 404), (
|
||||
"User B should not be able to access User A's purchase"
|
||||
)
|
||||
|
||||
async def test_user_b_purchase_list_is_empty(self, client, seed_data):
|
||||
"""A new user should see no purchases (not User A's purchases)."""
|
||||
reg = await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "userc@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "User C",
|
||||
},
|
||||
)
|
||||
assert reg.status_code == 201
|
||||
user_c_headers = {"Authorization": f"Bearer {reg.json()['access_token']}"}
|
||||
|
||||
resp = await client.get("/purchases", headers=user_c_headers)
|
||||
assert resp.status_code == 200
|
||||
assert len(resp.json()) == 0, "New user should have no purchases"
|
||||
|
||||
async def test_user_b_stores_isolated(self, client, seed_data):
|
||||
"""User B's connected stores should be independent from User A."""
|
||||
reg = await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "userd@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "User D",
|
||||
},
|
||||
)
|
||||
assert reg.status_code == 201
|
||||
user_d_headers = {"Authorization": f"Bearer {reg.json()['access_token']}"}
|
||||
|
||||
# User D should have no connected stores
|
||||
resp = await client.get("/me/stores", headers=user_d_headers)
|
||||
assert resp.status_code == 200
|
||||
assert len(resp.json()) == 0, "New user should have no connected stores"
|
||||
@@ -0,0 +1,114 @@
|
||||
"""E2E: Cross-resource flows — store connect → purchases → prices → coupons → alerts."""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestStoreConnectToPurchaseFlow:
|
||||
"""Connect a store, then verify purchases and related data are accessible."""
|
||||
|
||||
async def test_connect_store_then_list(self, client, seed_data):
|
||||
headers = seed_data["headers"]
|
||||
# Connect to Meijer
|
||||
resp = await client.post("/me/stores/meijer/connect", json={}, headers=headers)
|
||||
assert resp.status_code in (200, 201)
|
||||
|
||||
# Verify store appears in user's connected stores
|
||||
stores = await client.get("/me/stores", headers=headers)
|
||||
assert stores.status_code == 200
|
||||
slugs = [s["store"]["slug"] for s in stores.json()]
|
||||
assert "meijer" in slugs
|
||||
|
||||
async def test_disconnect_store(self, client, seed_data):
|
||||
headers = seed_data["headers"]
|
||||
await client.post("/me/stores/kroger/connect", json={}, headers=headers)
|
||||
resp = await client.delete("/me/stores/kroger", headers=headers)
|
||||
assert resp.status_code in (200, 204)
|
||||
|
||||
# Verify store no longer in connected list
|
||||
stores = await client.get("/me/stores", headers=headers)
|
||||
slugs = [s["store"]["slug"] for s in stores.json()]
|
||||
assert "kroger" not in slugs
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPurchaseToPriceFlow:
|
||||
"""Verify purchase data links to price comparison data."""
|
||||
|
||||
async def test_purchase_items_link_to_products(self, client, seed_data):
|
||||
"""Items from purchases reference products that have price data."""
|
||||
headers = seed_data["headers"]
|
||||
purchase_id = str(seed_data["purchases"]["meijer_trip"].id)
|
||||
|
||||
# Get purchase detail
|
||||
purchase = await client.get(f"/purchases/{purchase_id}", headers=headers)
|
||||
assert purchase.status_code == 200
|
||||
items = purchase.json()["line_items"]
|
||||
|
||||
# Get product detail for an item that has a product_id
|
||||
product_ids = [li["product_id"] for li in items if li.get("product_id")]
|
||||
assert len(product_ids) >= 1
|
||||
|
||||
for pid in product_ids:
|
||||
product = await client.get(f"/products/{pid}", headers=headers)
|
||||
assert product.status_code == 200
|
||||
assert len(product.json()["prices_by_store"]) >= 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestCouponFlow:
|
||||
"""Verify coupon listing and relevance filtering."""
|
||||
|
||||
async def test_list_all_coupons(self, client, seed_data):
|
||||
headers = seed_data["headers"]
|
||||
resp = await client.get("/coupons", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) >= 2
|
||||
descriptions = [c["description"] for c in data]
|
||||
assert any("Cheerios" in d for d in descriptions)
|
||||
|
||||
async def test_filter_coupons_by_store(self, client, seed_data):
|
||||
headers = seed_data["headers"]
|
||||
meijer_id = str(seed_data["stores"]["meijer"].id)
|
||||
resp = await client.get("/coupons", params={"store_id": meijer_id}, headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert all(c["store_name"] == "Meijer" for c in data)
|
||||
|
||||
async def test_relevant_coupons_for_user(self, client, seed_data):
|
||||
"""User bought Cheerios, so the Cheerios coupon should be relevant."""
|
||||
headers = seed_data["headers"]
|
||||
resp = await client.get("/coupons/relevant", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) >= 1, "Expected at least one relevant coupon for user with purchases"
|
||||
descriptions = [c["description"] for c in data]
|
||||
assert any("Cheerios" in d for d in descriptions)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestAlertFlow:
|
||||
"""Verify alert listing with seeded data."""
|
||||
|
||||
async def test_list_alerts(self, client, seed_data):
|
||||
"""User bought Cheerios which has a shrinkflation event — may appear as alert."""
|
||||
headers = seed_data["headers"]
|
||||
resp = await client.get("/alerts", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert isinstance(data, list)
|
||||
# If alerts are generated synchronously, verify shrinkflation alert content
|
||||
if len(data) > 0:
|
||||
alert_types = [a["alert_type"] for a in data]
|
||||
product_names = [a["product_name"] for a in data]
|
||||
assert any(t in ("shrinkflation", "price_increase") for t in alert_types)
|
||||
assert any("Cheerios" in name for name in product_names)
|
||||
|
||||
async def test_alert_settings_default(self, client, seed_data):
|
||||
headers = seed_data["headers"]
|
||||
resp = await client.get("/alerts/settings", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "price_increase_threshold_pct" in data
|
||||
assert "shrinkflation_enabled" in data
|
||||
@@ -0,0 +1,127 @@
|
||||
"""E2E: Error responses for bad input across all endpoint categories."""
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_e2e.conftest import BAD_UUID, ZERO_UUID
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestRegistrationErrors:
|
||||
"""Validation errors during user registration."""
|
||||
|
||||
async def test_short_password(self, client, db_engine):
|
||||
resp = await client.post(
|
||||
"/auth/register",
|
||||
json={"email": "short@example.com", "password": "short", "display_name": "Test"},
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_invalid_email(self, client, db_engine):
|
||||
resp = await client.post(
|
||||
"/auth/register",
|
||||
json={"email": "not-an-email", "password": "securepass123", "display_name": "Test"},
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_missing_fields(self, client, db_engine):
|
||||
resp = await client.post("/auth/register", json={})
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_empty_display_name(self, client, db_engine):
|
||||
resp = await client.post(
|
||||
"/auth/register",
|
||||
json={"email": "empty@example.com", "password": "securepass123", "display_name": ""},
|
||||
)
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_duplicate_email(self, client, db_engine):
|
||||
payload = {
|
||||
"email": "dupe@example.com",
|
||||
"password": "securepass123",
|
||||
"display_name": "First",
|
||||
}
|
||||
first = await client.post("/auth/register", json=payload)
|
||||
assert first.status_code == 201
|
||||
second = await client.post("/auth/register", json=payload)
|
||||
assert second.status_code == 409
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestLoginErrors:
|
||||
"""Login failure modes."""
|
||||
|
||||
async def test_wrong_password(self, client, db_engine):
|
||||
await client.post(
|
||||
"/auth/register",
|
||||
json={
|
||||
"email": "login-err@example.com",
|
||||
"password": "correctpass1",
|
||||
"display_name": "Login",
|
||||
},
|
||||
)
|
||||
resp = await client.post(
|
||||
"/auth/login",
|
||||
json={"email": "login-err@example.com", "password": "wrongpass123"},
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
async def test_nonexistent_user(self, client, db_engine):
|
||||
resp = await client.post(
|
||||
"/auth/login",
|
||||
json={"email": "nobody@example.com", "password": "doesntmatter"},
|
||||
)
|
||||
assert resp.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestNotFoundErrors:
|
||||
"""404 responses for missing resources."""
|
||||
|
||||
async def test_product_not_found(self, client, seed_data):
|
||||
resp = await client.get(f"/products/{ZERO_UUID}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 404
|
||||
|
||||
async def test_purchase_not_found(self, client, seed_data):
|
||||
resp = await client.get(f"/purchases/{ZERO_UUID}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 404
|
||||
|
||||
async def test_public_trend_not_found(self, client, seed_data):
|
||||
resp = await client.get(f"/public/trends/{ZERO_UUID}")
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestMalformedInput:
|
||||
"""Invalid UUID formats and bad query params."""
|
||||
|
||||
async def test_invalid_uuid_product(self, client, seed_data):
|
||||
resp = await client.get(f"/products/{BAD_UUID}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_invalid_uuid_purchase(self, client, seed_data):
|
||||
resp = await client.get(f"/purchases/{BAD_UUID}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_invalid_uuid_public_trend(self, client, seed_data):
|
||||
resp = await client.get(f"/public/trends/{BAD_UUID}")
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestStoreConnectionErrors:
|
||||
"""Store connection edge cases."""
|
||||
|
||||
async def test_connect_nonexistent_store(self, client, seed_data):
|
||||
resp = await client.post(
|
||||
"/me/stores/nonexistent-store/connect",
|
||||
json={},
|
||||
headers=seed_data["headers"],
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
async def test_connect_store_twice(self, client, seed_data):
|
||||
headers = seed_data["headers"]
|
||||
first = await client.post("/me/stores/meijer/connect", json={}, headers=headers)
|
||||
assert first.status_code in (200, 201)
|
||||
second = await client.post("/me/stores/meijer/connect", json={}, headers=headers)
|
||||
assert second.status_code == 409
|
||||
@@ -0,0 +1,102 @@
|
||||
"""E2E: Price history queries returning correct data."""
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPriceTrends:
|
||||
"""Verify price trend aggregation against seeded history."""
|
||||
|
||||
async def test_trends_returns_all_products(self, client, seed_data):
|
||||
resp = await client.get("/prices/trends", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
product_names = [t["product_name"] for t in data]
|
||||
assert "Cheerios 18oz" in product_names
|
||||
assert "Whole Milk 1gal" in product_names
|
||||
|
||||
async def test_trends_filter_by_category(self, client, seed_data):
|
||||
resp = await client.get(
|
||||
"/prices/trends", params={"category": "dairy"}, headers=seed_data["headers"]
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) >= 1
|
||||
# Only dairy products should appear
|
||||
for trend in data:
|
||||
assert trend["product_name"] == "Whole Milk 1gal"
|
||||
|
||||
async def test_trends_contain_data_points(self, client, seed_data):
|
||||
resp = await client.get("/prices/trends", headers=seed_data["headers"])
|
||||
data = resp.json()
|
||||
cheerios_trend = next(t for t in data if t["product_name"] == "Cheerios 18oz")
|
||||
assert len(cheerios_trend["data_points"]) >= 3
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPriceIncreases:
|
||||
"""Detect price increases from seeded price history."""
|
||||
|
||||
async def test_increases_detected(self, client, seed_data):
|
||||
resp = await client.get("/prices/increases", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
# Cheerios at Meijer went from 3.99 → 4.29 → 4.79
|
||||
cheerios_increases = [inc for inc in data if inc["product_name"] == "Cheerios 18oz"]
|
||||
assert len(cheerios_increases) >= 1
|
||||
# Verify the increase data makes sense
|
||||
for inc in cheerios_increases:
|
||||
assert inc["new_price"] > inc["old_price"]
|
||||
assert inc["increase_pct"] > 0
|
||||
assert inc["store_name"] == "Meijer"
|
||||
|
||||
async def test_stable_prices_not_flagged(self, client, seed_data):
|
||||
"""Kroger Cheerios price is stable at $4.49 — should not appear as increase."""
|
||||
resp = await client.get("/prices/increases", headers=seed_data["headers"])
|
||||
data = resp.json()
|
||||
kroger_increases = [
|
||||
inc
|
||||
for inc in data
|
||||
if inc["product_name"] == "Cheerios 18oz" and inc["store_name"] == "Kroger"
|
||||
]
|
||||
assert len(kroger_increases) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPriceComparison:
|
||||
"""Compare prices across stores for specific products."""
|
||||
|
||||
async def test_compare_cheerios_across_stores(self, client, seed_data):
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(
|
||||
"/prices/comparison",
|
||||
params={"product_ids": cheerios_id},
|
||||
headers=seed_data["headers"],
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) >= 1
|
||||
cheerios_cmp = data[0]
|
||||
assert cheerios_cmp["product_name"] == "Cheerios 18oz"
|
||||
store_names = [p["store_name"] for p in cheerios_cmp["prices"]]
|
||||
assert "Meijer" in store_names
|
||||
assert "Kroger" in store_names
|
||||
|
||||
async def test_compare_requires_product_ids(self, client, seed_data):
|
||||
"""product_ids is required — omitting it must return 422."""
|
||||
resp = await client.get("/prices/comparison", headers=seed_data["headers"])
|
||||
assert resp.status_code == 422
|
||||
|
||||
async def test_compare_multiple_products(self, client, seed_data):
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
milk_id = str(seed_data["products"]["milk"].id)
|
||||
resp = await client.get(
|
||||
"/prices/comparison",
|
||||
params=[("product_ids", cheerios_id), ("product_ids", milk_id)],
|
||||
headers=seed_data["headers"],
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
names = [c["product_name"] for c in data]
|
||||
assert "Cheerios 18oz" in names
|
||||
assert "Whole Milk 1gal" in names
|
||||
@@ -0,0 +1,82 @@
|
||||
"""E2E: Product search/lookup endpoints with real DB fixtures."""
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_e2e.conftest import ZERO_UUID
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestProductSearch:
|
||||
"""Search and filter products against seeded data."""
|
||||
|
||||
async def test_list_all_products(self, client, seed_data):
|
||||
resp = await client.get("/products", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
products = resp.json()
|
||||
names = [p["name"] for p in products]
|
||||
assert "Cheerios 18oz" in names
|
||||
assert "Whole Milk 1gal" in names
|
||||
assert "Chicken Breast 1lb" in names
|
||||
|
||||
async def test_search_by_name(self, client, seed_data):
|
||||
resp = await client.get("/products", params={"q": "cheerios"}, headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
products = resp.json()
|
||||
assert len(products) >= 1
|
||||
assert all("cheerios" in p["name"].lower() for p in products)
|
||||
|
||||
async def test_search_by_category(self, client, seed_data):
|
||||
resp = await client.get(
|
||||
"/products", params={"category": "dairy"}, headers=seed_data["headers"]
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
products = resp.json()
|
||||
assert len(products) >= 1
|
||||
assert all(p["category"] == "dairy" for p in products)
|
||||
|
||||
async def test_search_no_results(self, client, seed_data):
|
||||
resp = await client.get(
|
||||
"/products", params={"q": "nonexistentxyz"}, headers=seed_data["headers"]
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestProductLookup:
|
||||
"""Detailed product lookups with cross-store pricing."""
|
||||
|
||||
async def test_get_product_detail_with_prices(self, client, seed_data):
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(f"/products/{cheerios_id}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["name"] == "Cheerios 18oz"
|
||||
assert data["brand"] == "General Mills"
|
||||
assert data["category"] == "pantry"
|
||||
# Should have prices from both Meijer and Kroger
|
||||
store_names = [p["store_name"] for p in data["prices_by_store"]]
|
||||
assert "Meijer" in store_names
|
||||
assert "Kroger" in store_names
|
||||
|
||||
async def test_product_prices_reflect_latest(self, client, seed_data):
|
||||
"""The latest Meijer price for Cheerios should be 4.79 (the increase)."""
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(f"/products/{cheerios_id}", headers=seed_data["headers"])
|
||||
data = resp.json()
|
||||
meijer_price = next(p for p in data["prices_by_store"] if p["store_name"] == "Meijer")
|
||||
assert meijer_price["current_price"] == 4.79
|
||||
|
||||
async def test_product_not_found(self, client, seed_data):
|
||||
resp = await client.get(f"/products/{ZERO_UUID}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 404
|
||||
|
||||
async def test_product_price_history(self, client, seed_data):
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(f"/products/{cheerios_id}/prices", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data["data_points"]) >= 3 # At least the 3 Meijer observations
|
||||
# Verify chronological ordering exists
|
||||
prices = [dp["price"] for dp in data["data_points"]]
|
||||
assert len(prices) >= 3
|
||||
@@ -0,0 +1,59 @@
|
||||
"""E2E: Public price transparency endpoints (no auth required)."""
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPublicTrends:
|
||||
"""Public price trend endpoint — no auth, real data."""
|
||||
|
||||
async def test_public_trend_returns_data(self, client, seed_data):
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(f"/public/trends/{cheerios_id}")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["product_name"] == "Cheerios 18oz"
|
||||
assert len(data["data_points"]) >= 3
|
||||
|
||||
async def test_public_trend_no_auth_needed(self, client, seed_data):
|
||||
"""Confirm no Authorization header is required."""
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(f"/public/trends/{cheerios_id}")
|
||||
assert resp.status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPublicStoreComparison:
|
||||
"""Public store comparison endpoint."""
|
||||
|
||||
async def test_store_comparison(self, client, seed_data):
|
||||
cheerios_id = str(seed_data["products"]["cheerios"].id)
|
||||
resp = await client.get(
|
||||
"/public/store-comparison",
|
||||
params=[("product_ids", cheerios_id)],
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "products" in data
|
||||
assert len(data["products"]) >= 1
|
||||
|
||||
async def test_store_comparison_rejects_more_than_20_ids(self, client):
|
||||
"""max_length=20 guard: 21 product IDs must return 422."""
|
||||
too_many = [("product_ids", str(uuid.uuid4())) for _ in range(21)]
|
||||
resp = await client.get("/public/store-comparison", params=too_many)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPublicInflation:
|
||||
"""Public inflation index endpoint."""
|
||||
|
||||
async def test_inflation_returns_index(self, client, seed_data):
|
||||
resp = await client.get("/public/inflation")
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert "cartsnitch_index" in data
|
||||
assert "cpi_baseline" in data
|
||||
assert "categories" in data
|
||||
@@ -0,0 +1,87 @@
|
||||
"""E2E: Purchase listing, detail, and stats against real DB fixtures."""
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.test_e2e.conftest import ZERO_UUID
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPurchaseList:
|
||||
"""List and filter a user's purchases."""
|
||||
|
||||
async def test_list_user_purchases(self, client, seed_data):
|
||||
resp = await client.get("/purchases", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) >= 2
|
||||
store_names = [p["store_name"] for p in data]
|
||||
assert "Meijer" in store_names
|
||||
assert "Kroger" in store_names
|
||||
|
||||
async def test_filter_purchases_by_store(self, client, seed_data):
|
||||
meijer_id = str(seed_data["stores"]["meijer"].id)
|
||||
resp = await client.get(
|
||||
"/purchases", params={"store_id": meijer_id}, headers=seed_data["headers"]
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert len(data) >= 1
|
||||
assert all(p["store_name"] == "Meijer" for p in data)
|
||||
|
||||
async def test_purchases_require_auth(self, client, seed_data):
|
||||
resp = await client.get("/purchases")
|
||||
assert resp.status_code in (401, 403)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPurchaseDetail:
|
||||
"""Retrieve individual purchase with line items."""
|
||||
|
||||
async def test_get_purchase_detail(self, client, seed_data):
|
||||
purchase_id = str(seed_data["purchases"]["meijer_trip"].id)
|
||||
resp = await client.get(f"/purchases/{purchase_id}", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["store_name"] == "Meijer"
|
||||
assert data["total"] == 23.45
|
||||
assert len(data["line_items"]) == 2
|
||||
item_names = [li["name"] for li in data["line_items"]]
|
||||
assert "Cheerios 18oz Box" in item_names
|
||||
assert "Meijer Whole Milk 1gal" in item_names
|
||||
|
||||
async def test_line_item_amounts_correct(self, client, seed_data):
|
||||
purchase_id = str(seed_data["purchases"]["meijer_trip"].id)
|
||||
resp = await client.get(f"/purchases/{purchase_id}", headers=seed_data["headers"])
|
||||
data = resp.json()
|
||||
cheerios_item = next(li for li in data["line_items"] if "Cheerios" in li["name"])
|
||||
assert cheerios_item["unit_price"] == 4.79
|
||||
assert cheerios_item["quantity"] == 1.0
|
||||
assert cheerios_item["total_price"] == 4.79
|
||||
|
||||
async def test_purchase_not_found(self, client, seed_data):
|
||||
resp = await client.get(
|
||||
f"/purchases/{ZERO_UUID}",
|
||||
headers=seed_data["headers"],
|
||||
)
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestPurchaseStats:
|
||||
"""Verify spending aggregation across purchases."""
|
||||
|
||||
async def test_purchase_stats_totals(self, client, seed_data):
|
||||
resp = await client.get("/purchases/stats", headers=seed_data["headers"])
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["purchase_count"] == 2
|
||||
# 23.45 + 15.78 = 39.23
|
||||
assert abs(data["total_spent"] - 39.23) < 0.01
|
||||
|
||||
async def test_purchase_stats_by_store(self, client, seed_data):
|
||||
resp = await client.get("/purchases/stats", headers=seed_data["headers"])
|
||||
data = resp.json()
|
||||
assert "Meijer" in data["by_store"]
|
||||
assert "Kroger" in data["by_store"]
|
||||
assert abs(data["by_store"]["Meijer"] - 23.45) < 0.01
|
||||
assert abs(data["by_store"]["Kroger"] - 15.78) < 0.01
|
||||
Reference in New Issue
Block a user