From 9f94a2fb07426da24d55f530adea258bc244f18b Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Mon, 16 Nov 2026 21:59:34 -0700 Subject: [PATCH 1/8] Add customer models (#51) Customer is what gets stored (with the password hash), CustomerResponse is what the API returns (no hash). CustomerCreate/CustomerUpdate validate input, lowercase emails and keep passwords exactly as typed. --- backend/app/schemas/customer.py | 32 +++++++++++++ backend/app/schemas/customer_request.py | 44 +++++++++++++++++ backend/tests/test_customer_models.py | 64 +++++++++++++++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 backend/app/schemas/customer.py create mode 100644 backend/app/schemas/customer_request.py create mode 100644 backend/tests/test_customer_models.py diff --git a/backend/app/schemas/customer.py b/backend/app/schemas/customer.py new file mode 100644 index 0000000..1ffe7bd --- /dev/null +++ b/backend/app/schemas/customer.py @@ -0,0 +1,32 @@ +from typing import Literal + +from pydantic import BaseModel, Field + +from ..core.identifiers import generate_id + +CustomerRole = Literal["customer", "owner", "admin"] + + +class Customer(BaseModel): + """A customer as it is stored in customers.json (includes the password hash).""" + + id: str = Field(default_factory=generate_id, frozen=True) + name: str + email: str + hashedPassword: str + telephone: str | None = None + address: str | None = None + role: CustomerRole = "customer" + isActive: bool = True + + +class CustomerResponse(BaseModel): + """What the API sends back about a customer. Never includes the password hash.""" + + id: str + name: str + email: str + telephone: str | None = None + address: str | None = None + role: CustomerRole + isActive: bool diff --git a/backend/app/schemas/customer_request.py b/backend/app/schemas/customer_request.py new file mode 100644 index 0000000..2d925df --- /dev/null +++ b/backend/app/schemas/customer_request.py @@ -0,0 +1,44 @@ +from typing import Annotated + +from pydantic import BaseModel, ConfigDict, EmailStr, Field, StringConstraints, field_validator, model_validator + +from .restaurant_request import Address, Name, Telephone + +# Passwords are kept exactly as typed (no space stripping), otherwise login would not match +Password = Annotated[str, StringConstraints(strip_whitespace=False, min_length=8, max_length=128)] + + +def normalize_email(email: str | None) -> str | None: + # Emails are compared case-insensitively, so they are always stored in lowercase + return email.lower() if email is not None else None + + +class CustomerCreate(BaseModel): + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + name: Name = Field(description="Customer's full name") + email: EmailStr = Field(description="Email address, used to sign in. Must not already be registered") + password: Password = Field(description="Password, 8-128 characters") + telephone: Telephone | None = Field(None, description="Phone number: digits, spaces, '+', '(', ')', '-', '.', 7-25 characters") + address: Address | None = Field(None, description="Delivery address") + + _lowercase_email = field_validator("email")(normalize_email) + + +class CustomerUpdate(BaseModel): + """Only the fields that are sent get changed. A field left out or sent as null stays the same.""" + + model_config = ConfigDict(extra="forbid", str_strip_whitespace=True) + + name: Name | None = Field(None, description="New name") + email: EmailStr | None = Field(None, description="New email address. Must not belong to another customer") + telephone: Telephone | None = Field(None, description="New phone number") + address: Address | None = Field(None, description="New delivery address") + + _lowercase_email = field_validator("email")(normalize_email) + + @model_validator(mode="after") + def check_at_least_one_field(self): + if all(value is None for value in self.model_dump().values()): + raise ValueError("At least one field must be provided") + return self diff --git a/backend/tests/test_customer_models.py b/backend/tests/test_customer_models.py new file mode 100644 index 0000000..f942421 --- /dev/null +++ b/backend/tests/test_customer_models.py @@ -0,0 +1,64 @@ +import pytest +from pydantic import ValidationError + +from backend.app.schemas.customer import Customer, CustomerResponse +from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate + + +def valid_customer(**changes): + data = {"name": "Jordan Smith", "email": "jordan@example.com", "password": "password123"} + return {**data, **changes} + + +def test_create_accepts_minimal_valid_customer(): + customer = CustomerCreate(**valid_customer()) + + assert customer.telephone is None + assert customer.address is None + + +def test_create_stores_email_in_lowercase(): + customer = CustomerCreate(**valid_customer(email="Jordan@Example.COM")) + + assert customer.email == "jordan@example.com" + + +def test_create_keeps_spaces_in_password(): + customer = CustomerCreate(**valid_customer(password=" spaced out ")) + + assert customer.password == " spaced out " + + +@pytest.mark.parametrize("field, value", [ + ("email", "not-an-email"), + ("password", "short"), + ("name", ""), + ("telephone", "call me"), +]) +def test_create_rejects_invalid_values(field, value): + with pytest.raises(ValidationError): + CustomerCreate(**valid_customer(**{field: value})) + + +@pytest.mark.parametrize("field", ["role", "isActive", "id", "hashedPassword"]) +def test_create_rejects_fields_the_client_should_not_set(field): + with pytest.raises(ValidationError): + CustomerCreate(**valid_customer(**{field: "anything"})) + + +def test_update_needs_at_least_one_field(): + with pytest.raises(ValidationError): + CustomerUpdate() + + +def test_update_rejects_password_change(): + with pytest.raises(ValidationError): + CustomerUpdate(password="newpassword123") + + +def test_response_leaves_out_the_password_hash(): + customer = Customer(name="Jordan", email="jordan@example.com", hashedPassword="secret-hash") + + response = CustomerResponse.model_validate(customer.model_dump()) + + assert "hashedPassword" not in response.model_dump() From 36e42908d859695e0e89aefb7716da08cbfa04b7 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Mon, 16 Nov 2026 21:59:34 -0700 Subject: [PATCH 2/8] Add customer repository and service Register (hashes the password with argon2 via pwdlib, rejects a used email), get, update info/address and deactivate (soft delete, isActive=false). get_active_customer is for the auth dependency and cart/checkout to use. --- backend/app/core/exceptions.py | 9 ++ backend/app/core/security.py | 13 ++ .../app/repositories/customer_repository.py | 27 ++++ backend/app/services/customer_service.py | 80 +++++++++++ backend/requirements.txt | 5 + backend/tests/test_customer_service.py | 126 ++++++++++++++++++ 6 files changed, 260 insertions(+) create mode 100644 backend/app/core/security.py create mode 100644 backend/app/repositories/customer_repository.py create mode 100644 backend/app/services/customer_service.py create mode 100644 backend/tests/test_customer_service.py diff --git a/backend/app/core/exceptions.py b/backend/app/core/exceptions.py index 3934acb..a6b04c4 100644 --- a/backend/app/core/exceptions.py +++ b/backend/app/core/exceptions.py @@ -3,3 +3,12 @@ class RestaurantNotFoundError(Exception): class DuplicateRestaurantError(Exception): """Another restaurant already has the same name and address.""" + +class CustomerNotFoundError(Exception): + """No customer has the given ID.""" + +class DuplicateEmailError(Exception): + """Another customer is already registered with this email.""" + +class CustomerDeactivatedError(Exception): + """The customer's account has been deactivated.""" diff --git a/backend/app/core/security.py b/backend/app/core/security.py new file mode 100644 index 0000000..65266d2 --- /dev/null +++ b/backend/app/core/security.py @@ -0,0 +1,13 @@ +from pwdlib import PasswordHash + +# Argon2 hashing. Each hash gets its own random salt, so no secret key is needed here. +# (The SECRET_KEY in .env is only for signing login tokens.) +password_hash = PasswordHash.recommended() + + +def hash_password(password: str) -> str: + return password_hash.hash(password) + + +def verify_password(password: str, hashed_password: str) -> bool: + return password_hash.verify(password, hashed_password) diff --git a/backend/app/repositories/customer_repository.py b/backend/app/repositories/customer_repository.py new file mode 100644 index 0000000..624fa58 --- /dev/null +++ b/backend/app/repositories/customer_repository.py @@ -0,0 +1,27 @@ +from pathlib import Path + +from .json_repository import JsonRepository +from ..schemas.customer import Customer + + +class CustomerRepository(JsonRepository[Customer]): + def __init__(self, customers_file_path: Path) -> None: + super().__init__(customers_file_path, Customer) + + def get_all_customers(self) -> list[Customer]: + return self._load_all() + + def save_customers(self, customers: list[Customer]) -> None: + self._save_all(customers) + + def get_customer_by_id(self, customer_id: str) -> Customer | None: + for customer in self.get_all_customers(): + if customer.id == customer_id: + return customer + return None + + def get_customer_by_email(self, email: str) -> Customer | None: + for customer in self.get_all_customers(): + if customer.email == email.lower(): + return customer + return None diff --git a/backend/app/services/customer_service.py b/backend/app/services/customer_service.py new file mode 100644 index 0000000..d8635ff --- /dev/null +++ b/backend/app/services/customer_service.py @@ -0,0 +1,80 @@ +from ..core.exceptions import CustomerDeactivatedError, CustomerNotFoundError, DuplicateEmailError +from ..core.security import hash_password +from ..repositories.customer_repository import CustomerRepository +from ..schemas.customer import Customer +from ..schemas.customer_request import CustomerCreate, CustomerUpdate + + +class CustomerService: + def __init__(self, repository: CustomerRepository): + self.repository: CustomerRepository = repository + + def register_customer(self, request: CustomerCreate) -> Customer: + customers = self.repository.get_all_customers() + self._check_email_not_taken(customers, request.email) + + # The plain password is never stored, only its hash + data = request.model_dump(exclude={"password"}) + new_customer = Customer(**data, hashedPassword=hash_password(request.password)) + + customers.append(new_customer) + self.repository.save_customers(customers) + + return new_customer + + def get_customer(self, customer_id: str) -> Customer: + customer = self.repository.get_customer_by_id(customer_id) + if customer is None: + raise CustomerNotFoundError(f"Customer with id '{customer_id}' is not found") + return customer + + def get_customer_by_email(self, email: str) -> Customer | None: + return self.repository.get_customer_by_email(email) + + def get_active_customer(self, customer_id: str) -> Customer: + """Like get_customer, but a deactivated account counts as an error. + Used for anything a customer does while signed in (profile, cart, checkout).""" + customer = self.get_customer(customer_id) + if not customer.isActive: + raise CustomerDeactivatedError(f"Customer with id '{customer_id}' is deactivated") + return customer + + def update_customer(self, customer_id: str, request: CustomerUpdate) -> Customer: + customers = self.repository.get_all_customers() + customer = self._find_active(customers, customer_id) + + # Fields that were not sent (or sent as null) keep their current value + changes = request.model_dump(exclude_none=True) + + if "email" in changes: + other_customers = [c for c in customers if c.id != customer_id] + self._check_email_not_taken(other_customers, changes["email"]) + + for field, value in changes.items(): + setattr(customer, field, value) + + self.repository.save_customers(customers) + + return customer + + def deactivate_customer(self, customer_id: str) -> None: + # Soft delete: the account stays in the file so past orders still point to a real customer, + # but it can't sign in or be used anymore. + customers = self.repository.get_all_customers() + customer = self._find_active(customers, customer_id) + + customer.isActive = False + self.repository.save_customers(customers) + + def _find_active(self, customers: list[Customer], customer_id: str) -> Customer: + customer = next((c for c in customers if c.id == customer_id), None) + if customer is None: + raise CustomerNotFoundError(f"Customer with id '{customer_id}' is not found") + if not customer.isActive: + raise CustomerDeactivatedError(f"Customer with id '{customer_id}' is deactivated") + return customer + + def _check_email_not_taken(self, customers: list[Customer], email: str) -> None: + # Deactivated accounts still hold their email, so it can't be reused for a new account + if any(customer.email == email.lower() for customer in customers): + raise DuplicateEmailError(f"A customer with email '{email}' already exists") diff --git a/backend/requirements.txt b/backend/requirements.txt index 5f8d2ae..1ff0a45 100644 --- a/backend/requirements.txt +++ b/backend/requirements.txt @@ -2,7 +2,10 @@ agent-detector==2.0.0 annotated-doc==0.0.5 annotated-types==0.8.0 anyio==4.15.1 +argon2-cffi-bindings==26.2.0 +argon2-cffi==25.1.0 certifi==2026.7.22 +cffi==2.1.1 click==8.5.0 detect-installer==0.2.1 dnspython==2.8.0 @@ -25,6 +28,8 @@ mdurl==0.1.2 nanoid==2.0.0 packaging==26.3 pluggy==1.6.0 +pwdlib==0.4.2 +pycparser==3.12 pydantic==2.13.5 pydantic-extra-types==2.11.1 pydantic-settings==2.15.0 diff --git a/backend/tests/test_customer_service.py b/backend/tests/test_customer_service.py new file mode 100644 index 0000000..1d213e9 --- /dev/null +++ b/backend/tests/test_customer_service.py @@ -0,0 +1,126 @@ +from unittest.mock import Mock + +import pytest + +from backend.app.core.exceptions import CustomerDeactivatedError, CustomerNotFoundError, DuplicateEmailError +from backend.app.core.security import verify_password +from backend.app.repositories.customer_repository import CustomerRepository +from backend.app.schemas.customer import Customer +from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate +from backend.app.services.customer_service import CustomerService + + +def make_service(*customers): + repository = Mock(spec=CustomerRepository) + repository.get_all_customers.return_value = list(customers) + repository.get_customer_by_id.side_effect = lambda customer_id: next((c for c in customers if c.id == customer_id), None) + return CustomerService(repository), repository + + +def existing(**changes): + data = {"id": "c1", "name": "Alex", "email": "alex@example.com", "hashedPassword": "hash"} + return Customer(**{**data, **changes}) + + +# register + +def test_register_saves_customer_with_hashed_password(): + service, repository = make_service() + + customer = service.register_customer(CustomerCreate(name="Jordan", email="jordan@example.com", password="password123")) + + assert customer.hashedPassword != "password123" + assert verify_password("password123", customer.hashedPassword) + assert customer.role == "customer" + assert customer.isActive is True + repository.save_customers.assert_called_once_with([customer]) + + +def test_register_rejects_email_already_used_with_different_case(): + service, repository = make_service(existing()) + + with pytest.raises(DuplicateEmailError): + service.register_customer(CustomerCreate(name="Other", email="ALEX@example.com", password="password123")) + + repository.save_customers.assert_not_called() + + +def test_register_rejects_email_of_deactivated_account(): + service, _ = make_service(existing(isActive=False)) + + with pytest.raises(DuplicateEmailError): + service.register_customer(CustomerCreate(name="Other", email="alex@example.com", password="password123")) + + +# get + +def test_get_customer_raises_when_id_is_unknown(): + service, _ = make_service() + + with pytest.raises(CustomerNotFoundError): + service.get_customer("missing") + + +def test_get_active_customer_raises_for_deactivated_account(): + service, _ = make_service(existing(isActive=False)) + + with pytest.raises(CustomerDeactivatedError): + service.get_active_customer("c1") + + +# update + +def test_update_changes_only_sent_fields(): + service, repository = make_service(existing(telephone="+1-250-555-0100")) + + customer = service.update_customer("c1", CustomerUpdate(address="3333 University Way, Kelowna, BC")) + + assert customer.address == "3333 University Way, Kelowna, BC" + assert customer.telephone == "+1-250-555-0100" + assert customer.name == "Alex" + repository.save_customers.assert_called_once() + + +def test_update_rejects_email_used_by_another_customer(): + service, repository = make_service(existing(), existing(id="c2", email="taken@example.com")) + + with pytest.raises(DuplicateEmailError): + service.update_customer("c1", CustomerUpdate(email="taken@example.com")) + + repository.save_customers.assert_not_called() + + +def test_update_allows_keeping_own_email(): + service, _ = make_service(existing()) + + customer = service.update_customer("c1", CustomerUpdate(email="alex@example.com", name="Alex M")) + + assert customer.name == "Alex M" + + +def test_update_rejects_deactivated_customer(): + service, repository = make_service(existing(isActive=False)) + + with pytest.raises(CustomerDeactivatedError): + service.update_customer("c1", CustomerUpdate(name="New")) + + repository.save_customers.assert_not_called() + + +# deactivate + +def test_deactivate_marks_customer_inactive_and_keeps_them_saved(): + customer = existing() + service, repository = make_service(customer) + + service.deactivate_customer("c1") + + assert customer.isActive is False + repository.save_customers.assert_called_once_with([customer]) + + +def test_deactivate_unknown_customer_raises(): + service, _ = make_service() + + with pytest.raises(CustomerNotFoundError): + service.deactivate_customer("missing") From aaef50ed49a30a1c799867f5555f3ec7f70fc443 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Mon, 16 Nov 2026 21:59:34 -0700 Subject: [PATCH 3/8] Add customer endpoints (#53) POST /customers, and GET/PATCH/DELETE /customers/me. The /me routes use get_current_customer, which rejects everything with 401 until the JWT login is merged. Tests fake a signed-in customer with dependency_overrides. Added customers.json to test-data, sample-data and the conftest file list. --- README.md | 4 + backend/app/api/routes.py | 76 ++++++++++++- backend/app/core/dependencies.py | 30 ++++- backend/sample-data/customers.json | 1 + backend/tests/conftest.py | 2 +- backend/tests/test-data/customers.json | 22 ++++ backend/tests/test_customer_endpoints.py | 133 +++++++++++++++++++++++ 7 files changed, 263 insertions(+), 5 deletions(-) create mode 100644 backend/sample-data/customers.json create mode 100644 backend/tests/test-data/customers.json create mode 100644 backend/tests/test_customer_endpoints.py diff --git a/README.md b/README.md index ecdf93a..63e52e6 100644 --- a/README.md +++ b/README.md @@ -174,6 +174,10 @@ The API provides the following endpoints: | POST | `/api/v1/restaurants/{restaurant_id}/menu-items` | `Creates a new menu item. Returns 201, 404 if the restaurant is not found, 422 for invalid input.` | | PATCH | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Updates a menu item's fields. Returns 200, 404 if the item or restaurant is not found, 422 for invalid input.` | | DELETE | `/api/v1/restaurants/{restaurant_id}/menu-items/{menu_item_id}` | `Deletes a specific menu item. Returns 204 on success, 404 if not found.` | +| POST | `/api/v1/customers` | `Registers a customer. Returns 201 (without the password), 409 if the email is already registered, 422 for invalid input.` | +| GET | `/api/v1/customers/me` | `Returns the signed-in customer's info. Returns 401 if not signed in.` | +| PATCH | `/api/v1/customers/me` | `Updates the signed-in customer's name, email, telephone or delivery address. Returns 200, 401, 409 if the email is taken, 422 for invalid input.` | +| DELETE | `/api/v1/customers/me` | `Deactivates the signed-in customer's account (kept but marked inactive). Returns 204, 401 if not signed in.` | ## API Documentation diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index e1d6257..2aa987e 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -1,14 +1,17 @@ from fastapi import FastAPI, HTTPException, Depends, APIRouter from json import JSONDecodeError -from ..core.dependencies import get_restaurant_service +from ..core.dependencies import get_restaurant_service, get_customer_service, get_current_customer from ..schemas.restaurant import Restaurant from ..schemas.restaurant_query import RestaurantQuery from ..services.restaurant_service import RestaurantService from ..schemas.menu_item import MenuItem from ..schemas.menu_item_request import MenuItemCreate, MenuItemUpdate from ..schemas.restaurant_request import RestaurantCreate, RestaurantUpdate -from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError +from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError, DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError +from ..schemas.customer import Customer, CustomerResponse +from ..schemas.customer_request import CustomerCreate, CustomerUpdate +from ..services.customer_service import CustomerService def create_routes(api: FastAPI | APIRouter): @api.get("/health") @@ -121,6 +124,75 @@ def update_restaurant(restaurant_id: str, request: RestaurantUpdate): raise HTTPException(status_code=409, detail=str(e)) + @api.post( + "/customers", + response_model=CustomerResponse, + status_code=201, + summary="Register a customer", + responses={409: {"description": "A customer with this email already exists"}}, + ) + def register_customer(request: CustomerCreate, customer_service: CustomerService = Depends(get_customer_service)): + """Creates a new customer account. The password is stored hashed and never returned.""" + try: + return customer_service.register_customer(request) + + except DuplicateEmailError as e: + raise HTTPException(status_code=409, detail=str(e)) + + + @api.get( + "/customers/me", + response_model=CustomerResponse, + summary="Get the signed-in customer's info", + responses={401: {"description": "Not signed in"}}, + ) + def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)): + return current_customer + + + @api.patch( + "/customers/me", + response_model=CustomerResponse, + summary="Update the signed-in customer's info and delivery address", + responses={ + 401: {"description": "Not signed in"}, + 409: {"description": "Another customer already uses this email"}, + }, + ) + def update_my_customer_info( + request: CustomerUpdate, + current_customer: Customer = Depends(get_current_customer), + customer_service: CustomerService = Depends(get_customer_service), + ): + """Changes only the fields that are sent. The password, role and id can't be changed here.""" + try: + return customer_service.update_customer(current_customer.id, request) + + except DuplicateEmailError as e: + raise HTTPException(status_code=409, detail=str(e)) + + except (CustomerNotFoundError, CustomerDeactivatedError) as e: + raise HTTPException(status_code=401, detail=str(e)) + + + @api.delete( + "/customers/me", + status_code=204, + summary="Deactivate the signed-in customer's account", + responses={401: {"description": "Not signed in"}}, + ) + def deactivate_my_account( + current_customer: Customer = Depends(get_current_customer), + customer_service: CustomerService = Depends(get_customer_service), + ): + """The account is kept (so past orders stay valid) but marked inactive, so it can't be used again.""" + try: + customer_service.deactivate_customer(current_customer.id) + + except (CustomerNotFoundError, CustomerDeactivatedError) as e: + raise HTTPException(status_code=401, detail=str(e)) + + @api.get("/", include_in_schema=False) @api.get("/{path:path}", include_in_schema=False) def api_not_found(path: str): diff --git a/backend/app/core/dependencies.py b/backend/app/core/dependencies.py index 4a8af31..fae084b 100644 --- a/backend/app/core/dependencies.py +++ b/backend/app/core/dependencies.py @@ -1,13 +1,39 @@ from pathlib import Path +from fastapi import HTTPException, status + from ..services.restaurant_service import RestaurantService +from ..services.customer_service import CustomerService from ..repositories.restaurant_repository import RestaurantRepository +from ..repositories.customer_repository import CustomerRepository +from ..schemas.customer import Customer + def get_data_dir() -> Path: data_dir = Path(__file__).resolve().parents[2] / "data" - if not data_dir.exists(): data_dir.mkdir() + + if not data_dir.exists(): + data_dir.mkdir() + return data_dir def get_restaurant_service(): restaurant_repository = RestaurantRepository(get_data_dir() / "restaurants.json") - return RestaurantService(restaurant_repository) \ No newline at end of file + return RestaurantService(restaurant_repository) + +def get_customer_service() -> CustomerService: + customer_repository = CustomerRepository(get_data_dir() / "customers.json") + return CustomerService(customer_repository) + +def get_current_customer() -> Customer: + """Returns the signed-in customer for protected endpoints. + + Placeholder until the JWT login (#52) is merged: it rejects every request, so the + protected endpoints are locked by default. The auth work replaces the body with + token decoding + customer_service.get_active_customer(customer_id). + """ + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Not authenticated", + headers={"WWW-Authenticate": "Bearer"}, + ) diff --git a/backend/sample-data/customers.json b/backend/sample-data/customers.json new file mode 100644 index 0000000..fe51488 --- /dev/null +++ b/backend/sample-data/customers.json @@ -0,0 +1 @@ +[] diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 6226bea..7de52c8 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -14,7 +14,7 @@ @pytest.fixture(autouse=True) def isolated_data(): - files_to_track = ["restaurants.json"] + files_to_track = ["restaurants.json", "customers.json"] for name in files_to_track: test_file = TEST_DATA / name diff --git a/backend/tests/test-data/customers.json b/backend/tests/test-data/customers.json new file mode 100644 index 0000000..606da29 --- /dev/null +++ b/backend/tests/test-data/customers.json @@ -0,0 +1,22 @@ +[ + { + "id": "cust000000000000active", + "name": "Alex Morgan", + "email": "alex@example.com", + "hashedPassword": "$argon2id$v=19$m=65536,t=3,p=4$pMImEqYcVJFExSYw9Az4gg$2UD0II/GuSsdSHMbgRxTnuG0e83GvSkr5qu6x+c1BeU", + "telephone": "+1-250-555-0111", + "address": "1234 University Way, Kelowna, BC", + "role": "customer", + "isActive": true + }, + { + "id": "cust00000000000inactive", + "name": "Sam Lee", + "email": "sam@example.com", + "hashedPassword": "$argon2id$v=19$m=65536,t=3,p=4$y10GQ6SKAnoDIUU+W419vQ$l7ZAlCATZsgNcxLwWaaPPq+C6qxsBiSgWkNw4rkDg60", + "telephone": null, + "address": null, + "role": "customer", + "isActive": false + } +] diff --git a/backend/tests/test_customer_endpoints.py b/backend/tests/test_customer_endpoints.py new file mode 100644 index 0000000..d8ef791 --- /dev/null +++ b/backend/tests/test_customer_endpoints.py @@ -0,0 +1,133 @@ +import pytest +from fastapi import HTTPException +from fastapi.testclient import TestClient + +from backend.app.core.dependencies import get_current_customer, get_customer_service +from backend.app.core.exceptions import CustomerDeactivatedError, CustomerNotFoundError +from backend.app.main import main + +ACTIVE_CUSTOMER_ID = "cust000000000000active" # Alex Morgan in test-data/customers.json + + +def new_customer(**changes): + data = {"name": "Jordan Smith", "email": "jordan@example.com", "password": "password123"} + return {**data, **changes} + + +def client_signed_in_as(customer_id): + # Login (JWT) is a separate task, so these tests pretend the request is signed in + # by replacing get_current_customer, the same way the real one will look the customer up. + def fake_current_customer(): + try: + return get_customer_service().get_active_customer(customer_id) + except (CustomerNotFoundError, CustomerDeactivatedError): + raise HTTPException(status_code=401, detail="Not authenticated") + + app = main() + app.dependency_overrides[get_current_customer] = fake_current_customer + return TestClient(app) + + +@pytest.fixture +def signed_in_client(): + return client_signed_in_as(ACTIVE_CUSTOMER_ID) + + +# POST /customers + +def test_register_returns_201_without_password(client): + response = client.post("/api/v1/customers", json=new_customer(address="1 Main St")) + + assert response.status_code == 201 + data = response.json() + assert data["id"] + assert data["email"] == "jordan@example.com" + assert data["address"] == "1 Main St" + assert data["role"] == "customer" + assert data["isActive"] is True + assert "password" not in data + assert "hashedPassword" not in data + + +def test_registered_customer_is_saved(client): + created = client.post("/api/v1/customers", json=new_customer()).json() + + # A fresh app reads customers.json again, like after a restart + response = client_signed_in_as(created["id"]).get("/api/v1/customers/me") + + assert response.status_code == 200 + assert response.json()["name"] == "Jordan Smith" + + +def test_register_with_existing_email_returns_409(client): + response = client.post("/api/v1/customers", json=new_customer(email="Alex@Example.com")) + + assert response.status_code == 409 + + +def test_register_with_invalid_email_returns_422(client): + response = client.post("/api/v1/customers", json=new_customer(email="nope")) + + assert response.status_code == 422 + + +# Not signed in + +@pytest.mark.parametrize("method", ["get", "patch", "delete"]) +def test_my_account_endpoints_need_sign_in(client, method): + kwargs = {"json": {"name": "Hacker"}} if method == "patch" else {} + + response = getattr(client, method)("/api/v1/customers/me", **kwargs) + + assert response.status_code == 401 + + +# GET /customers/me + +def test_get_my_info_returns_signed_in_customer(signed_in_client): + response = signed_in_client.get("/api/v1/customers/me") + + assert response.status_code == 200 + assert response.json()["email"] == "alex@example.com" + assert "hashedPassword" not in response.json() + + +# PATCH /customers/me + +def test_update_delivery_address(signed_in_client): + response = signed_in_client.patch("/api/v1/customers/me", json={"address": "999 New Rd, Kelowna, BC"}) + + assert response.status_code == 200 + assert response.json()["address"] == "999 New Rd, Kelowna, BC" + assert response.json()["name"] == "Alex Morgan" + + +def test_update_to_taken_email_returns_409(signed_in_client): + signed_in_client.post("/api/v1/customers", json=new_customer()) + + response = signed_in_client.patch("/api/v1/customers/me", json={"email": "jordan@example.com"}) + + assert response.status_code == 409 + + +def test_update_with_no_fields_returns_422(signed_in_client): + response = signed_in_client.patch("/api/v1/customers/me", json={}) + + assert response.status_code == 422 + + +def test_update_cannot_change_role(signed_in_client): + response = signed_in_client.patch("/api/v1/customers/me", json={"role": "admin"}) + + assert response.status_code == 422 + + +# DELETE /customers/me + +def test_deactivate_returns_204_and_locks_the_account(signed_in_client): + response = signed_in_client.delete("/api/v1/customers/me") + + assert response.status_code == 204 + + # The same customer can't use their account anymore + assert signed_in_client.get("/api/v1/customers/me").status_code == 401 From bdf28c72b0dcf7c7e1296008fbb3a2c1b2f87037 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Mon, 16 Nov 2026 22:02:43 -0700 Subject: [PATCH 4/8] Lock customer saves so parallel sign-ups don't overwrite each other Two registrations at the same time could both pass the email check and the second save would drop the first customer. Register/update/deactivate now hold the file lock around load -> change -> save, and the password is hashed before taking it. Also rejects passwords that are only spaces. --- backend/app/schemas/customer_request.py | 7 ++++ backend/app/services/customer_service.py | 42 ++++++++++++---------- backend/tests/test_customer_models.py | 1 + backend/tests/test_customer_service.py | 46 ++++++++++++++++++++++-- 4 files changed, 75 insertions(+), 21 deletions(-) diff --git a/backend/app/schemas/customer_request.py b/backend/app/schemas/customer_request.py index 2d925df..fe5c13b 100644 --- a/backend/app/schemas/customer_request.py +++ b/backend/app/schemas/customer_request.py @@ -24,6 +24,13 @@ class CustomerCreate(BaseModel): _lowercase_email = field_validator("email")(normalize_email) + @field_validator("password") + @classmethod + def check_password_not_blank(cls, password: str) -> str: + if not password.strip(): + raise ValueError("Password can't be only spaces") + return password + class CustomerUpdate(BaseModel): """Only the fields that are sent get changed. A field left out or sent as null stays the same.""" diff --git a/backend/app/services/customer_service.py b/backend/app/services/customer_service.py index d8635ff..2e00fb8 100644 --- a/backend/app/services/customer_service.py +++ b/backend/app/services/customer_service.py @@ -10,15 +10,17 @@ def __init__(self, repository: CustomerRepository): self.repository: CustomerRepository = repository def register_customer(self, request: CustomerCreate) -> Customer: - customers = self.repository.get_all_customers() - self._check_email_not_taken(customers, request.email) - - # The plain password is never stored, only its hash + # The plain password is never stored, only its hash. Hashing is slow, so it's done + # before taking the lock to keep other requests from waiting on it. data = request.model_dump(exclude={"password"}) new_customer = Customer(**data, hashedPassword=hash_password(request.password)) - customers.append(new_customer) - self.repository.save_customers(customers) + with self.repository.lock(): + customers = self.repository.get_all_customers() + self._check_email_not_taken(customers, request.email) + + customers.append(new_customer) + self.repository.save_customers(customers) return new_customer @@ -40,31 +42,33 @@ def get_active_customer(self, customer_id: str) -> Customer: return customer def update_customer(self, customer_id: str, request: CustomerUpdate) -> Customer: - customers = self.repository.get_all_customers() - customer = self._find_active(customers, customer_id) - # Fields that were not sent (or sent as null) keep their current value changes = request.model_dump(exclude_none=True) - if "email" in changes: - other_customers = [c for c in customers if c.id != customer_id] - self._check_email_not_taken(other_customers, changes["email"]) + with self.repository.lock(): + customers = self.repository.get_all_customers() + customer = self._find_active(customers, customer_id) + + if "email" in changes: + other_customers = [c for c in customers if c.id != customer_id] + self._check_email_not_taken(other_customers, changes["email"]) - for field, value in changes.items(): - setattr(customer, field, value) + for field, value in changes.items(): + setattr(customer, field, value) - self.repository.save_customers(customers) + self.repository.save_customers(customers) return customer def deactivate_customer(self, customer_id: str) -> None: # Soft delete: the account stays in the file so past orders still point to a real customer, # but it can't sign in or be used anymore. - customers = self.repository.get_all_customers() - customer = self._find_active(customers, customer_id) + with self.repository.lock(): + customers = self.repository.get_all_customers() + customer = self._find_active(customers, customer_id) - customer.isActive = False - self.repository.save_customers(customers) + customer.isActive = False + self.repository.save_customers(customers) def _find_active(self, customers: list[Customer], customer_id: str) -> Customer: customer = next((c for c in customers if c.id == customer_id), None) diff --git a/backend/tests/test_customer_models.py b/backend/tests/test_customer_models.py index f942421..fcf81a3 100644 --- a/backend/tests/test_customer_models.py +++ b/backend/tests/test_customer_models.py @@ -32,6 +32,7 @@ def test_create_keeps_spaces_in_password(): @pytest.mark.parametrize("field, value", [ ("email", "not-an-email"), ("password", "short"), + ("password", " "), ("name", ""), ("telephone", "call me"), ]) diff --git a/backend/tests/test_customer_service.py b/backend/tests/test_customer_service.py index 1d213e9..48277bc 100644 --- a/backend/tests/test_customer_service.py +++ b/backend/tests/test_customer_service.py @@ -1,4 +1,5 @@ -from unittest.mock import Mock +import threading +from unittest.mock import MagicMock import pytest @@ -8,10 +9,12 @@ from backend.app.schemas.customer import Customer from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate from backend.app.services.customer_service import CustomerService +from backend.app.repositories.customer_repository import CustomerRepository as RealCustomerRepository def make_service(*customers): - repository = Mock(spec=CustomerRepository) + # MagicMock (not Mock) so `with repository.lock():` works + repository = MagicMock(spec=CustomerRepository) repository.get_all_customers.return_value = list(customers) repository.get_customer_by_id.side_effect = lambda customer_id: next((c for c in customers if c.id == customer_id), None) return CustomerService(repository), repository @@ -124,3 +127,42 @@ def test_deactivate_unknown_customer_raises(): with pytest.raises(CustomerNotFoundError): service.deactivate_customer("missing") + + +# Two sign-ups at the same time (regression test for a lost-update bug found in review) + +def register_in_parallel(file_path, emails): + file_path.write_text("[]") + results = [] + + def register(email): + # A new service + repository per call, like separate requests + service = CustomerService(RealCustomerRepository(file_path)) + try: + service.register_customer(CustomerCreate(name="Parallel", email=email, password="password123")) + results.append("ok") + except DuplicateEmailError: + results.append("duplicate") + + threads = [threading.Thread(target=register, args=(email,)) for email in emails] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + return results, RealCustomerRepository(file_path).get_all_customers() + + +def test_parallel_registrations_are_all_saved(tmp_path): + results, saved = register_in_parallel(tmp_path / "customers.json", [f"user{n}@example.com" for n in range(8)]) + + assert results.count("ok") == 8 + assert len(saved) == 8 + + +def test_parallel_registrations_with_same_email_create_only_one_account(tmp_path): + results, saved = register_in_parallel(tmp_path / "customers.json", ["same@example.com"] * 4) + + assert results.count("ok") == 1 + assert results.count("duplicate") == 3 + assert len(saved) == 1 From 2b71d5cfef203241e0a2ec445fe8a1bd62a157d1 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Tue, 17 Nov 2026 22:06:27 -0700 Subject: [PATCH 5/8] Test the 128 character password limit From Nathan's review: 128 characters is accepted, 129 is rejected. --- backend/tests/test_customer_models.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/backend/tests/test_customer_models.py b/backend/tests/test_customer_models.py index fcf81a3..167d92b 100644 --- a/backend/tests/test_customer_models.py +++ b/backend/tests/test_customer_models.py @@ -23,6 +23,12 @@ def test_create_stores_email_in_lowercase(): assert customer.email == "jordan@example.com" +def test_create_accepts_password_of_exactly_128_characters(): + customer = CustomerCreate(**valid_customer(password="a" * 128)) + + assert len(customer.password) == 128 + + def test_create_keeps_spaces_in_password(): customer = CustomerCreate(**valid_customer(password=" spaced out ")) @@ -33,6 +39,7 @@ def test_create_keeps_spaces_in_password(): ("email", "not-an-email"), ("password", "short"), ("password", " "), + ("password", "a" * 129), ("name", ""), ("telephone", "call me"), ]) From 50f0248d428d7c8c0b0261362fa10b66baec0638 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Tue, 17 Nov 2026 22:37:59 -0700 Subject: [PATCH 6/8] Clean up customer code - get_customer and get_active_customer did the same lookup, kept one - shorter comments, removed a duplicate import and a duplicate test --- backend/app/core/dependencies.py | 15 +++------------ backend/app/core/security.py | 3 +-- backend/app/services/customer_service.py | 13 +------------ backend/tests/test_customer_models.py | 9 --------- backend/tests/test_customer_service.py | 10 ++++------ 5 files changed, 9 insertions(+), 41 deletions(-) diff --git a/backend/app/core/dependencies.py b/backend/app/core/dependencies.py index fae084b..9c35d45 100644 --- a/backend/app/core/dependencies.py +++ b/backend/app/core/dependencies.py @@ -1,6 +1,6 @@ from pathlib import Path -from fastapi import HTTPException, status +from fastapi import HTTPException from ..services.restaurant_service import RestaurantService from ..services.customer_service import CustomerService @@ -26,14 +26,5 @@ def get_customer_service() -> CustomerService: return CustomerService(customer_repository) def get_current_customer() -> Customer: - """Returns the signed-in customer for protected endpoints. - - Placeholder until the JWT login (#52) is merged: it rejects every request, so the - protected endpoints are locked by default. The auth work replaces the body with - token decoding + customer_service.get_active_customer(customer_id). - """ - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "Bearer"}, - ) + """Placeholder until login (#52) is merged: rejects every request.""" + raise HTTPException(status_code=401, detail="Not authenticated", headers={"WWW-Authenticate": "Bearer"}) diff --git a/backend/app/core/security.py b/backend/app/core/security.py index 65266d2..ad8b3d3 100644 --- a/backend/app/core/security.py +++ b/backend/app/core/security.py @@ -1,7 +1,6 @@ from pwdlib import PasswordHash -# Argon2 hashing. Each hash gets its own random salt, so no secret key is needed here. -# (The SECRET_KEY in .env is only for signing login tokens.) +# Argon2, each hash gets its own random salt password_hash = PasswordHash.recommended() diff --git a/backend/app/services/customer_service.py b/backend/app/services/customer_service.py index 2e00fb8..a2fc22d 100644 --- a/backend/app/services/customer_service.py +++ b/backend/app/services/customer_service.py @@ -24,22 +24,11 @@ def register_customer(self, request: CustomerCreate) -> Customer: return new_customer - def get_customer(self, customer_id: str) -> Customer: - customer = self.repository.get_customer_by_id(customer_id) - if customer is None: - raise CustomerNotFoundError(f"Customer with id '{customer_id}' is not found") - return customer - def get_customer_by_email(self, email: str) -> Customer | None: return self.repository.get_customer_by_email(email) def get_active_customer(self, customer_id: str) -> Customer: - """Like get_customer, but a deactivated account counts as an error. - Used for anything a customer does while signed in (profile, cart, checkout).""" - customer = self.get_customer(customer_id) - if not customer.isActive: - raise CustomerDeactivatedError(f"Customer with id '{customer_id}' is deactivated") - return customer + return self._find_active(self.repository.get_all_customers(), customer_id) def update_customer(self, customer_id: str, request: CustomerUpdate) -> Customer: # Fields that were not sent (or sent as null) keep their current value diff --git a/backend/tests/test_customer_models.py b/backend/tests/test_customer_models.py index 167d92b..9b2355a 100644 --- a/backend/tests/test_customer_models.py +++ b/backend/tests/test_customer_models.py @@ -1,7 +1,6 @@ import pytest from pydantic import ValidationError -from backend.app.schemas.customer import Customer, CustomerResponse from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate @@ -62,11 +61,3 @@ def test_update_needs_at_least_one_field(): def test_update_rejects_password_change(): with pytest.raises(ValidationError): CustomerUpdate(password="newpassword123") - - -def test_response_leaves_out_the_password_hash(): - customer = Customer(name="Jordan", email="jordan@example.com", hashedPassword="secret-hash") - - response = CustomerResponse.model_validate(customer.model_dump()) - - assert "hashedPassword" not in response.model_dump() diff --git a/backend/tests/test_customer_service.py b/backend/tests/test_customer_service.py index 48277bc..f2eaee4 100644 --- a/backend/tests/test_customer_service.py +++ b/backend/tests/test_customer_service.py @@ -9,14 +9,12 @@ from backend.app.schemas.customer import Customer from backend.app.schemas.customer_request import CustomerCreate, CustomerUpdate from backend.app.services.customer_service import CustomerService -from backend.app.repositories.customer_repository import CustomerRepository as RealCustomerRepository def make_service(*customers): # MagicMock (not Mock) so `with repository.lock():` works repository = MagicMock(spec=CustomerRepository) repository.get_all_customers.return_value = list(customers) - repository.get_customer_by_id.side_effect = lambda customer_id: next((c for c in customers if c.id == customer_id), None) return CustomerService(repository), repository @@ -61,7 +59,7 @@ def test_get_customer_raises_when_id_is_unknown(): service, _ = make_service() with pytest.raises(CustomerNotFoundError): - service.get_customer("missing") + service.get_active_customer("missing") def test_get_active_customer_raises_for_deactivated_account(): @@ -129,7 +127,7 @@ def test_deactivate_unknown_customer_raises(): service.deactivate_customer("missing") -# Two sign-ups at the same time (regression test for a lost-update bug found in review) +# Regression: parallel sign-ups used to overwrite each other (found in review) def register_in_parallel(file_path, emails): file_path.write_text("[]") @@ -137,7 +135,7 @@ def register_in_parallel(file_path, emails): def register(email): # A new service + repository per call, like separate requests - service = CustomerService(RealCustomerRepository(file_path)) + service = CustomerService(CustomerRepository(file_path)) try: service.register_customer(CustomerCreate(name="Parallel", email=email, password="password123")) results.append("ok") @@ -150,7 +148,7 @@ def register(email): for thread in threads: thread.join() - return results, RealCustomerRepository(file_path).get_all_customers() + return results, CustomerRepository(file_path).get_all_customers() def test_parallel_registrations_are_all_saved(tmp_path): From ff8f5d0d0415fc050b043856bbc11bd80c58c402 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Tue, 17 Nov 2026 22:37:59 -0700 Subject: [PATCH 7/8] Document error responses for customer endpoints Added an ErrorResponse model so 401/409 show their body in /docs, and a description for GET /customers/me. --- backend/app/api/routes.py | 12 +++++++----- backend/app/schemas/error.py | 7 +++++++ 2 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 backend/app/schemas/error.py diff --git a/backend/app/api/routes.py b/backend/app/api/routes.py index 2aa987e..315e1d0 100644 --- a/backend/app/api/routes.py +++ b/backend/app/api/routes.py @@ -10,6 +10,7 @@ from ..schemas.restaurant_request import RestaurantCreate, RestaurantUpdate from ..core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError, DuplicateEmailError, CustomerNotFoundError, CustomerDeactivatedError from ..schemas.customer import Customer, CustomerResponse +from ..schemas.error import ErrorResponse from ..schemas.customer_request import CustomerCreate, CustomerUpdate from ..services.customer_service import CustomerService @@ -129,7 +130,7 @@ def update_restaurant(restaurant_id: str, request: RestaurantUpdate): response_model=CustomerResponse, status_code=201, summary="Register a customer", - responses={409: {"description": "A customer with this email already exists"}}, + responses={409: {"model": ErrorResponse, "description": "A customer with this email already exists"}}, ) def register_customer(request: CustomerCreate, customer_service: CustomerService = Depends(get_customer_service)): """Creates a new customer account. The password is stored hashed and never returned.""" @@ -144,9 +145,10 @@ def register_customer(request: CustomerCreate, customer_service: CustomerService "/customers/me", response_model=CustomerResponse, summary="Get the signed-in customer's info", - responses={401: {"description": "Not signed in"}}, + responses={401: {"model": ErrorResponse, "description": "Not signed in"}}, ) def get_my_customer_info(current_customer: Customer = Depends(get_current_customer)): + """Returns the customer the request is signed in as. The password hash is never included.""" return current_customer @@ -155,8 +157,8 @@ def get_my_customer_info(current_customer: Customer = Depends(get_current_custom response_model=CustomerResponse, summary="Update the signed-in customer's info and delivery address", responses={ - 401: {"description": "Not signed in"}, - 409: {"description": "Another customer already uses this email"}, + 401: {"model": ErrorResponse, "description": "Not signed in"}, + 409: {"model": ErrorResponse, "description": "Another customer already uses this email"}, }, ) def update_my_customer_info( @@ -179,7 +181,7 @@ def update_my_customer_info( "/customers/me", status_code=204, summary="Deactivate the signed-in customer's account", - responses={401: {"description": "Not signed in"}}, + responses={401: {"model": ErrorResponse, "description": "Not signed in"}}, ) def deactivate_my_account( current_customer: Customer = Depends(get_current_customer), diff --git a/backend/app/schemas/error.py b/backend/app/schemas/error.py new file mode 100644 index 0000000..0bfd8e7 --- /dev/null +++ b/backend/app/schemas/error.py @@ -0,0 +1,7 @@ +from pydantic import BaseModel + + +class ErrorResponse(BaseModel): + """Body of every error the API sends on purpose (401, 404, 409...).""" + + detail: str From 0e87d6dea085179aaa307be6c27ebc957cf5d649 Mon Sep 17 00:00:00 2001 From: Mustafa Tiritoglu Date: Tue, 17 Nov 2026 22:38:27 -0700 Subject: [PATCH 8/8] Fix two customer tests that passed for the wrong reason - role and password tests now send a valid field too, so the 422 really comes from the forbidden field - added repository tests for lookups by id/email and stable ids - removed a lower() in the service that never did anything (emails are already lowercased by the request model) --- backend/app/services/customer_service.py | 2 +- backend/tests/test_customer_endpoints.py | 3 ++- backend/tests/test_customer_models.py | 2 +- backend/tests/test_customer_repository.py | 33 +++++++++++++++++++++++ 4 files changed, 37 insertions(+), 3 deletions(-) create mode 100644 backend/tests/test_customer_repository.py diff --git a/backend/app/services/customer_service.py b/backend/app/services/customer_service.py index a2fc22d..516979f 100644 --- a/backend/app/services/customer_service.py +++ b/backend/app/services/customer_service.py @@ -69,5 +69,5 @@ def _find_active(self, customers: list[Customer], customer_id: str) -> Customer: def _check_email_not_taken(self, customers: list[Customer], email: str) -> None: # Deactivated accounts still hold their email, so it can't be reused for a new account - if any(customer.email == email.lower() for customer in customers): + if any(customer.email == email for customer in customers): raise DuplicateEmailError(f"A customer with email '{email}' already exists") diff --git a/backend/tests/test_customer_endpoints.py b/backend/tests/test_customer_endpoints.py index d8ef791..70bfc4a 100644 --- a/backend/tests/test_customer_endpoints.py +++ b/backend/tests/test_customer_endpoints.py @@ -117,9 +117,10 @@ def test_update_with_no_fields_returns_422(signed_in_client): def test_update_cannot_change_role(signed_in_client): - response = signed_in_client.patch("/api/v1/customers/me", json={"role": "admin"}) + response = signed_in_client.patch("/api/v1/customers/me", json={"name": "Alex", "role": "admin"}) assert response.status_code == 422 + assert signed_in_client.get("/api/v1/customers/me").json()["role"] == "customer" # DELETE /customers/me diff --git a/backend/tests/test_customer_models.py b/backend/tests/test_customer_models.py index 9b2355a..297fc3b 100644 --- a/backend/tests/test_customer_models.py +++ b/backend/tests/test_customer_models.py @@ -60,4 +60,4 @@ def test_update_needs_at_least_one_field(): def test_update_rejects_password_change(): with pytest.raises(ValidationError): - CustomerUpdate(password="newpassword123") + CustomerUpdate(name="Alex", password="newpassword123") diff --git a/backend/tests/test_customer_repository.py b/backend/tests/test_customer_repository.py new file mode 100644 index 0000000..cd1d030 --- /dev/null +++ b/backend/tests/test_customer_repository.py @@ -0,0 +1,33 @@ +from backend.app.repositories.customer_repository import CustomerRepository +from backend.app.schemas.customer import Customer + + +def make_repository(tmp_path): + repository = CustomerRepository(tmp_path / "customers.json") + repository.save_customers([ + Customer(id="c1", name="Alex", email="alex@example.com", hashedPassword="hash"), + Customer(id="c2", name="Sam", email="sam@example.com", hashedPassword="hash"), + ]) + return repository + + +def test_get_customer_by_id(tmp_path): + repository = make_repository(tmp_path) + + assert repository.get_customer_by_id("c2").name == "Sam" + assert repository.get_customer_by_id("missing") is None + + +def test_get_customer_by_email_ignores_case(tmp_path): + repository = make_repository(tmp_path) + + assert repository.get_customer_by_email("ALEX@Example.com").id == "c1" + assert repository.get_customer_by_email("nobody@example.com") is None + + +def test_ids_stay_the_same_after_reloading(tmp_path): + repository = make_repository(tmp_path) + + reloaded = CustomerRepository(tmp_path / "customers.json") + + assert [c.id for c in reloaded.get_all_customers()] == ["c1", "c2"]