test: add loyalty module tests for today's bug fixes
Some checks failed
Some checks failed
Covers card lookup route ordering, func.replace normalization, customer name in transactions, self-enrollment creation, and earn points endpoint. 54 tests total (was 1). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,16 @@
|
||||
"""Unit tests for CardService."""
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.customers.models.customer import Customer
|
||||
from app.modules.loyalty.exceptions import (
|
||||
CustomerIdentifierRequiredException,
|
||||
CustomerNotFoundByEmailException,
|
||||
)
|
||||
from app.modules.loyalty.models import LoyaltyCard, LoyaltyTransaction
|
||||
from app.modules.loyalty.models.loyalty_transaction import TransactionType
|
||||
from app.modules.loyalty.services.card_service import CardService
|
||||
|
||||
|
||||
@@ -16,3 +25,266 @@ class TestCardService:
|
||||
def test_service_instantiation(self):
|
||||
"""Service can be instantiated."""
|
||||
assert self.service is not None
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.loyalty
|
||||
class TestGetCardByNumber:
|
||||
"""Tests for card number lookup with SQL normalization (func.replace)."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = CardService()
|
||||
|
||||
def test_find_card_by_exact_number(self, db, test_loyalty_card):
|
||||
"""Find card by its exact stored card number."""
|
||||
result = self.service.get_card_by_number(db, test_loyalty_card.card_number)
|
||||
assert result is not None
|
||||
assert result.id == test_loyalty_card.id
|
||||
|
||||
def test_find_card_with_dashes_in_query(self, db, test_loyalty_program, test_customer, test_store):
|
||||
"""Query with dashes matches card stored without dashes."""
|
||||
card = LoyaltyCard(
|
||||
merchant_id=test_loyalty_program.merchant_id,
|
||||
program_id=test_loyalty_program.id,
|
||||
customer_id=test_customer.id,
|
||||
enrolled_at_store_id=test_store.id,
|
||||
card_number="ABCD1234",
|
||||
is_active=True,
|
||||
)
|
||||
db.add(card)
|
||||
db.commit()
|
||||
|
||||
result = self.service.get_card_by_number(db, "ABCD-1234")
|
||||
assert result is not None
|
||||
assert result.id == card.id
|
||||
|
||||
def test_find_card_with_spaces_in_query(self, db, test_loyalty_program, test_customer, test_store):
|
||||
"""Query with spaces matches card stored without spaces."""
|
||||
card = LoyaltyCard(
|
||||
merchant_id=test_loyalty_program.merchant_id,
|
||||
program_id=test_loyalty_program.id,
|
||||
customer_id=test_customer.id,
|
||||
enrolled_at_store_id=test_store.id,
|
||||
card_number="WXYZ5678",
|
||||
is_active=True,
|
||||
)
|
||||
db.add(card)
|
||||
db.commit()
|
||||
|
||||
result = self.service.get_card_by_number(db, "WXYZ 5678")
|
||||
assert result is not None
|
||||
assert result.id == card.id
|
||||
|
||||
def test_card_not_found_returns_none(self, db):
|
||||
"""Non-existent card number returns None."""
|
||||
result = self.service.get_card_by_number(db, "NONEXISTENT-999")
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.loyalty
|
||||
class TestSearchCardForStore:
|
||||
"""Tests for free-text card search scoped to store's merchant."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = CardService()
|
||||
|
||||
def test_search_by_card_number(self, db, test_loyalty_card, test_store):
|
||||
"""Find card by card number."""
|
||||
result = self.service.search_card_for_store(
|
||||
db, test_store.id, test_loyalty_card.card_number
|
||||
)
|
||||
assert result is not None
|
||||
assert result.id == test_loyalty_card.id
|
||||
|
||||
def test_search_by_customer_email(self, db, test_loyalty_card, test_store, test_customer):
|
||||
"""Find card by customer email."""
|
||||
result = self.service.search_card_for_store(
|
||||
db, test_store.id, test_customer.email
|
||||
)
|
||||
assert result is not None
|
||||
assert result.id == test_loyalty_card.id
|
||||
|
||||
def test_search_returns_none_for_wrong_merchant(self, db, test_loyalty_card, test_store):
|
||||
"""Card from a different merchant is not returned."""
|
||||
from app.modules.tenancy.models import Merchant, Store, User
|
||||
from middleware.auth import AuthManager
|
||||
|
||||
auth = AuthManager()
|
||||
uid = str(uuid.uuid4())[:8]
|
||||
|
||||
other_owner = User(
|
||||
email=f"other_{uid}@test.com",
|
||||
username=f"other_{uid}",
|
||||
hashed_password=auth.hash_password("pass123"),
|
||||
role="merchant_owner",
|
||||
is_active=True,
|
||||
)
|
||||
db.add(other_owner)
|
||||
db.flush()
|
||||
|
||||
other_merchant = Merchant(
|
||||
name="Other Merchant",
|
||||
owner_user_id=other_owner.id,
|
||||
contact_email="other@test.com",
|
||||
is_active=True,
|
||||
)
|
||||
db.add(other_merchant)
|
||||
db.flush()
|
||||
|
||||
other_store = Store(
|
||||
store_code=f"OTHER{uid}",
|
||||
subdomain=f"other{uid}",
|
||||
name="Other Store",
|
||||
merchant_id=other_merchant.id,
|
||||
is_active=True,
|
||||
)
|
||||
db.add(other_store)
|
||||
db.commit()
|
||||
|
||||
# Search from the other store — should not find the card
|
||||
result = self.service.search_card_for_store(
|
||||
db, other_store.id, test_loyalty_card.card_number
|
||||
)
|
||||
assert result is None
|
||||
|
||||
def test_search_returns_none_for_nonexistent(self, db, test_store):
|
||||
"""No match returns None."""
|
||||
result = self.service.search_card_for_store(db, test_store.id, "nobody@nowhere.com")
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.loyalty
|
||||
class TestResolveCustomerId:
|
||||
"""Tests for customer ID resolution including self-enrollment creation."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = CardService()
|
||||
|
||||
def test_resolve_by_customer_id(self, db, test_customer, test_store):
|
||||
"""Returns immediately when customer_id is provided."""
|
||||
result = self.service.resolve_customer_id(
|
||||
db, customer_id=test_customer.id, email=None, store_id=test_store.id
|
||||
)
|
||||
assert result == test_customer.id
|
||||
|
||||
def test_resolve_by_email(self, db, test_customer, test_store):
|
||||
"""Finds existing customer by email."""
|
||||
result = self.service.resolve_customer_id(
|
||||
db, customer_id=None, email=test_customer.email, store_id=test_store.id
|
||||
)
|
||||
assert result == test_customer.id
|
||||
|
||||
def test_resolve_creates_customer_when_missing(self, db, test_store):
|
||||
"""create_if_missing=True creates a new customer."""
|
||||
email = f"newcustomer-{uuid.uuid4().hex[:8]}@test.com"
|
||||
result = self.service.resolve_customer_id(
|
||||
db,
|
||||
customer_id=None,
|
||||
email=email,
|
||||
store_id=test_store.id,
|
||||
create_if_missing=True,
|
||||
customer_name="Jane Doe",
|
||||
customer_phone="+352123456",
|
||||
)
|
||||
assert result is not None
|
||||
|
||||
customer = db.query(Customer).filter(Customer.id == result).first()
|
||||
assert customer is not None
|
||||
assert customer.email == email
|
||||
assert customer.first_name == "Jane"
|
||||
assert customer.last_name == "Doe"
|
||||
assert customer.phone == "+352123456"
|
||||
assert customer.hashed_password.startswith("!loyalty-enroll!")
|
||||
assert customer.customer_number is not None
|
||||
assert customer.is_active is True
|
||||
|
||||
def test_resolve_splits_name_into_first_last(self, db, test_store):
|
||||
"""Full name with space is split into first_name and last_name."""
|
||||
email = f"split-{uuid.uuid4().hex[:8]}@test.com"
|
||||
result = self.service.resolve_customer_id(
|
||||
db,
|
||||
customer_id=None,
|
||||
email=email,
|
||||
store_id=test_store.id,
|
||||
create_if_missing=True,
|
||||
customer_name="John Michael Smith",
|
||||
)
|
||||
customer = db.query(Customer).filter(Customer.id == result).first()
|
||||
assert customer.first_name == "John"
|
||||
assert customer.last_name == "Michael Smith"
|
||||
|
||||
def test_resolve_raises_when_email_not_found(self, db, test_store):
|
||||
"""create_if_missing=False raises when email not found."""
|
||||
with pytest.raises(CustomerNotFoundByEmailException):
|
||||
self.service.resolve_customer_id(
|
||||
db,
|
||||
customer_id=None,
|
||||
email="nonexistent@test.com",
|
||||
store_id=test_store.id,
|
||||
create_if_missing=False,
|
||||
)
|
||||
|
||||
def test_resolve_raises_when_no_identifier(self, db, test_store):
|
||||
"""Raises when neither customer_id nor email provided."""
|
||||
with pytest.raises(CustomerIdentifierRequiredException):
|
||||
self.service.resolve_customer_id(
|
||||
db, customer_id=None, email=None, store_id=test_store.id
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.loyalty
|
||||
class TestGetStoreTransactions:
|
||||
"""Tests for merchant-scoped transaction retrieval with eager loading."""
|
||||
|
||||
def setup_method(self):
|
||||
self.service = CardService()
|
||||
|
||||
def test_returns_transactions_for_merchant(
|
||||
self, db, test_loyalty_card, test_loyalty_transaction
|
||||
):
|
||||
"""Returns transactions belonging to the merchant."""
|
||||
transactions, total = self.service.get_store_transactions(
|
||||
db, test_loyalty_card.merchant_id
|
||||
)
|
||||
assert total >= 1
|
||||
assert len(transactions) >= 1
|
||||
assert any(t.id == test_loyalty_transaction.id for t in transactions)
|
||||
|
||||
def test_eager_loads_customer(
|
||||
self, db, test_loyalty_card, test_loyalty_transaction
|
||||
):
|
||||
"""Verifies card.customer is accessible without lazy-load error."""
|
||||
transactions, _ = self.service.get_store_transactions(
|
||||
db, test_loyalty_card.merchant_id
|
||||
)
|
||||
tx = transactions[0]
|
||||
# This should not raise a lazy-loading error
|
||||
assert tx.card is not None
|
||||
assert tx.card.customer is not None
|
||||
assert tx.card.customer.email is not None
|
||||
|
||||
def test_pagination(self, db, test_loyalty_card, test_store):
|
||||
"""Skip and limit work correctly."""
|
||||
from datetime import UTC, datetime
|
||||
|
||||
# Create 3 transactions
|
||||
for i in range(3):
|
||||
t = LoyaltyTransaction(
|
||||
merchant_id=test_loyalty_card.merchant_id,
|
||||
card_id=test_loyalty_card.id,
|
||||
store_id=test_store.id,
|
||||
transaction_type=TransactionType.POINTS_EARNED.value,
|
||||
points_delta=10 * (i + 1),
|
||||
transaction_at=datetime.now(UTC),
|
||||
)
|
||||
db.add(t)
|
||||
db.commit()
|
||||
|
||||
transactions, total = self.service.get_store_transactions(
|
||||
db, test_loyalty_card.merchant_id, skip=0, limit=2
|
||||
)
|
||||
assert total >= 3
|
||||
assert len(transactions) == 2
|
||||
|
||||
75
app/modules/loyalty/tests/unit/test_schemas.py
Normal file
75
app/modules/loyalty/tests/unit/test_schemas.py
Normal file
@@ -0,0 +1,75 @@
|
||||
"""Unit tests for loyalty schemas."""
|
||||
|
||||
from datetime import UTC, datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app.modules.loyalty.schemas.card import (
|
||||
CardEnrollRequest,
|
||||
TransactionResponse,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.loyalty
|
||||
class TestCardEnrollRequest:
|
||||
"""Tests for enrollment request schema validation."""
|
||||
|
||||
def test_valid_with_email(self):
|
||||
"""Email-only enrollment is valid."""
|
||||
req = CardEnrollRequest(email="test@example.com")
|
||||
assert req.email == "test@example.com"
|
||||
assert req.customer_id is None
|
||||
|
||||
def test_valid_with_customer_id(self):
|
||||
"""Customer ID enrollment is valid."""
|
||||
req = CardEnrollRequest(customer_id=42)
|
||||
assert req.customer_id == 42
|
||||
assert req.email is None
|
||||
|
||||
def test_self_enrollment_fields(self):
|
||||
"""Self-enrollment accepts name, phone, birthday."""
|
||||
req = CardEnrollRequest(
|
||||
email="self@example.com",
|
||||
customer_name="Jane Doe",
|
||||
customer_phone="+352123456",
|
||||
customer_birthday="1990-01-15",
|
||||
)
|
||||
assert req.customer_name == "Jane Doe"
|
||||
assert req.customer_phone == "+352123456"
|
||||
assert req.customer_birthday == "1990-01-15"
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
@pytest.mark.loyalty
|
||||
class TestTransactionResponse:
|
||||
"""Tests for transaction response schema."""
|
||||
|
||||
def test_customer_name_field_defaults_none(self):
|
||||
"""customer_name field exists and defaults to None."""
|
||||
now = datetime.now(UTC)
|
||||
tx = TransactionResponse(
|
||||
id=1,
|
||||
card_id=1,
|
||||
transaction_type="points_earned",
|
||||
stamps_delta=0,
|
||||
points_delta=50,
|
||||
transaction_at=now,
|
||||
created_at=now,
|
||||
)
|
||||
assert tx.customer_name is None
|
||||
|
||||
def test_customer_name_can_be_set(self):
|
||||
"""customer_name can be explicitly set."""
|
||||
now = datetime.now(UTC)
|
||||
tx = TransactionResponse(
|
||||
id=1,
|
||||
card_id=1,
|
||||
transaction_type="card_created",
|
||||
stamps_delta=0,
|
||||
points_delta=0,
|
||||
customer_name="John Doe",
|
||||
transaction_at=now,
|
||||
created_at=now,
|
||||
)
|
||||
assert tx.customer_name == "John Doe"
|
||||
Reference in New Issue
Block a user