Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ The API provides the following endpoints:
| GET | `/restaurants` | `Lists all the restaurants.` |
| GET | `/restaurants?{query}` | `Lists all the restaurants that match searching query: name=...&hasMenu=...&sort_by=...&sort_desc=...` |
| GET | `/restaurants/{restaurant_id}` | `Retrieves a specific restaurant by its ID.` |
| POST | `/restaurants` | `Creates a restaurant. Returns 201, 409 if the same name and address already exist, 422 for invalid input.` |
| PATCH | `/restaurants/{restaurant_id}` | `Updates only the fields sent. Returns 200, 404 for an unknown ID, 409 for a duplicate, 422 for invalid input.` |


## API Documentation
Expand Down
43 changes: 43 additions & 0 deletions backend/app/api/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from backend.app.services.restaurant_service import RestaurantService
from backend.app.schemas.menu_item import MenuItem
from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
from backend.app.schemas.restaurant_request import RestaurantCreate, RestaurantUpdate
from backend.app.core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError

def create_routes(app: FastAPI):
@app.get("/health")
Expand Down Expand Up @@ -76,3 +78,44 @@ def get_restaurant(restaurant_id: str):
return restaurant
except JSONDecodeError:
raise HTTPException(status_code=500, detail="Invalid JSON data")


@app.post(
"/restaurants",
response_model=Restaurant,
status_code=201,
summary="Create a restaurant",
responses={409: {"description": "A restaurant with the same name and address already exists"}},
)
def create_restaurant(request: RestaurantCreate):
"""Creates a new restaurant. The server generates its id, and it starts with no menu."""
restaurant_service = get_restaurant_service()

try:
return restaurant_service.create_restaurant(request)

except DuplicateRestaurantError as e:
raise HTTPException(status_code=409, detail=str(e))


@app.patch(
"/restaurants/{restaurant_id}",
response_model=Restaurant,
summary="Update a restaurant's information",
responses={
404: {"description": "No restaurant has this id"},
409: {"description": "Another restaurant already has the same name and address"},
},
)
def update_restaurant(restaurant_id: str, request: RestaurantUpdate):
"""Changes only the fields that are sent. The id and menu can't be changed here."""
restaurant_service = get_restaurant_service()

try:
return restaurant_service.update_restaurant(restaurant_id, request)

except RestaurantNotFoundError as e:
raise HTTPException(status_code=404, detail=str(e))

except DuplicateRestaurantError as e:
raise HTTPException(status_code=409, detail=str(e))
5 changes: 5 additions & 0 deletions backend/app/core/exceptions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class RestaurantNotFoundError(Exception):
"""No restaurant has the given ID."""

class DuplicateRestaurantError(Exception):
"""Another restaurant already has the same name and address."""
40 changes: 40 additions & 0 deletions backend/app/services/restaurant_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from backend.app.schemas.menu_item import MenuItem
from backend.app.schemas.menu_item_request import MenuItemCreate, MenuItemUpdate
from backend.app.schemas.menu import Menu
from backend.app.schemas.restaurant_request import RestaurantCreate, RestaurantUpdate
from backend.app.core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError

UNCATEGORIZED_MENU_SECTION_ID = "uncategorized"
UNCATEGORIZED_MENU_SECTION_NAME = "Uncategorized"
Expand Down Expand Up @@ -40,6 +42,44 @@ def get_sort_value(r):
def get_restaurant_by_id(self, restaurant_id: str):
return self.repository.get_restaurant_by_id(restaurant_id)

def create_restaurant(self, request: RestaurantCreate) -> Restaurant:
restaurants = self.repository.get_all_restaurants()
self._check_not_duplicate(restaurants, request.name, request.address)

# id, type and hasMenu are filled in by the Restaurant model (new restaurants start with no menu)
new_restaurant = Restaurant(**request.model_dump())

restaurants.append(new_restaurant)
self.repository.save_restaurants(restaurants)

return new_restaurant

def update_restaurant(self, restaurant_id: str, request: RestaurantUpdate) -> Restaurant:
restaurants = self.repository.get_all_restaurants()
restaurant = next((r for r in restaurants if r.id == restaurant_id), None)

if restaurant is None:
raise RestaurantNotFoundError(f"Restaurant with id '{restaurant_id}' is not found")

# Fields that were not sent (or sent as null) keep their current value
changes = request.model_dump(exclude_none=True)

other_restaurants = [r for r in restaurants if r.id != restaurant_id]
self._check_not_duplicate(other_restaurants, changes.get("name", restaurant.name), changes.get("address", restaurant.address))

for field, value in changes.items():
setattr(restaurant, field, value)

self.repository.save_restaurants(restaurants)

return restaurant

def _check_not_duplicate(self, restaurants: list[Restaurant], name: str, address: str) -> None:
# Chains share names, so a restaurant only counts as a duplicate if the address matches too
for restaurant in restaurants:
if restaurant.name.lower() == name.lower() and restaurant.address.lower() == address.lower():
raise DuplicateRestaurantError(f"A restaurant named '{name}' already exists at '{address}'")

def _find_restaurant(self, restaurants: list[Restaurant], restaurant_id: str) -> Restaurant:
for restaurant in restaurants:
if restaurant.id == restaurant_id:
Expand Down
100 changes: 100 additions & 0 deletions backend/tests/test_restaurant_management_endpoints.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
from fastapi.testclient import TestClient
from backend.app.main import main

def new_restaurant(**changes):
data = {
"name": "Taco Town",
"address": "789 Pine St",
"telephone": "+1-250-555-0300",
"openingHours": "Mo-Sa 09:00-21:00",
}
return {**data, **changes}

# POST /restaurants

def test_create_restaurant_returns_201_with_new_restaurant(client):
response = client.post("/restaurants", json=new_restaurant())

assert response.status_code == 201
data = response.json()
assert data["id"]
assert data["name"] == "Taco Town"
assert data["hasMenu"] is None

def test_created_restaurant_is_saved(client):
created = client.post("/restaurants", json=new_restaurant()).json()

# A fresh app reads from the JSON file again, like after a restart
restarted_client = TestClient(main())
response = restarted_client.get(f"/restaurants/{created['id']}")

assert response.status_code == 200
assert response.json()["name"] == "Taco Town"

def test_create_restaurant_with_missing_field_returns_422(client):
data = new_restaurant()
del data["address"]

response = client.post("/restaurants", json=data)

assert response.status_code == 422

def test_create_restaurant_with_id_returns_422(client):
response = client.post("/restaurants", json=new_restaurant(id="my-own-id"))

assert response.status_code == 422

def test_create_duplicate_restaurant_returns_409(client):
existing = client.get("/restaurants").json()[0]

response = client.post("/restaurants", json=new_restaurant(name=existing["name"], address=existing["address"]))

assert response.status_code == 409

# PATCH /restaurants/{restaurant_id}

def test_update_restaurant_changes_only_fields_sent(client):
existing = client.get("/restaurants").json()[0]

response = client.patch(f"/restaurants/{existing['id']}", json={"telephone": "+1-250-555-0199"})

assert response.status_code == 200
data = response.json()
assert data["telephone"] == "+1-250-555-0199"
assert data["name"] == existing["name"]
assert data["hasMenu"] == existing["hasMenu"]

def test_updated_restaurant_is_saved(client):
existing = client.get("/restaurants").json()[0]
client.patch(f"/restaurants/{existing['id']}", json={"name": "Renamed Cafe"})

restarted_client = TestClient(main())
response = restarted_client.get(f"/restaurants/{existing['id']}")

assert response.json()["name"] == "Renamed Cafe"

def test_update_unknown_restaurant_returns_404(client):
response = client.patch("/restaurants/does-not-exist", json={"name": "New Name"})

assert response.status_code == 404

def test_update_with_no_fields_returns_422(client):
existing = client.get("/restaurants").json()[0]

response = client.patch(f"/restaurants/{existing['id']}", json={})

assert response.status_code == 422

def test_update_with_invalid_opening_hours_returns_422(client):
existing = client.get("/restaurants").json()[0]

response = client.patch(f"/restaurants/{existing['id']}", json={"openingHours": "always open"})

assert response.status_code == 422

def test_update_into_duplicate_returns_409(client):
first, second = client.get("/restaurants").json()[:2]

response = client.patch(f"/restaurants/{first['id']}", json={"name": second["name"], "address": second["address"]})

assert response.status_code == 409
116 changes: 116 additions & 0 deletions backend/tests/test_restaurant_management_service.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import pytest
from unittest.mock import Mock

from backend.app.core.exceptions import DuplicateRestaurantError, RestaurantNotFoundError
from backend.app.schemas.restaurant import Restaurant
from backend.app.schemas.restaurant_request import RestaurantCreate, RestaurantUpdate
from backend.app.services.restaurant_service import RestaurantService

@pytest.fixture
def existing_restaurants():
return [
Restaurant(id="1", name="Pizza Palace", address="123 Main St", telephone="+1-250-555-0100", openingHours="Mo-Su 11:00-22:00"),
Restaurant(id="2", name="Burger Barn", address="456 Oak St", telephone="+1-250-555-0200", openingHours="Mo-Fr 10:00-20:00"),
]

@pytest.fixture
def repository(existing_restaurants):
repository = Mock()
repository.get_all_restaurants.return_value = existing_restaurants
return repository

@pytest.fixture
def service(repository):
return RestaurantService(repository)

def create_request(**changes):
data = {
"name": "Taco Town",
"address": "789 Pine St",
"telephone": "+1-250-555-0300",
"openingHours": "Mo-Sa 09:00-21:00",
}
return RestaurantCreate(**{**data, **changes})

# Creating a restaurant

def test_create_restaurant_returns_new_restaurant(service):
restaurant = service.create_restaurant(create_request())

assert restaurant.name == "Taco Town"
assert restaurant.address == "789 Pine St"
assert restaurant.description == ""
assert restaurant.type == "Restaurant"
assert restaurant.hasMenu is None

def test_create_restaurant_generates_new_id(service):
restaurant = service.create_restaurant(create_request())

assert restaurant.id
assert restaurant.id not in ["1", "2"]

def test_create_restaurant_saves_it_with_existing_restaurants(service, repository):
restaurant = service.create_restaurant(create_request())

saved = repository.save_restaurants.call_args.args[0]
assert [r.id for r in saved] == ["1", "2", restaurant.id]

def test_create_duplicate_restaurant_is_rejected(service, repository):
with pytest.raises(DuplicateRestaurantError):
service.create_restaurant(create_request(name="Pizza Palace", address="123 Main St"))

repository.save_restaurants.assert_not_called()

def test_duplicate_check_ignores_case(service):
with pytest.raises(DuplicateRestaurantError):
service.create_restaurant(create_request(name="PIZZA palace", address="123 main st"))

def test_same_name_at_different_address_is_allowed(service):
restaurant = service.create_restaurant(create_request(name="Pizza Palace", address="999 Elm St"))

assert restaurant.name == "Pizza Palace"

# Updating a restaurant

def test_update_changes_only_the_fields_sent(service):
restaurant = service.update_restaurant("1", RestaurantUpdate(telephone="+1-250-555-0199"))

assert restaurant.telephone == "+1-250-555-0199"
assert restaurant.name == "Pizza Palace"
assert restaurant.address == "123 Main St"
assert restaurant.openingHours == "Mo-Su 11:00-22:00"

def test_update_keeps_the_same_id(service):
restaurant = service.update_restaurant("1", RestaurantUpdate(name="Pizza Palace Downtown"))

assert restaurant.id == "1"

def test_update_ignores_fields_sent_as_null(service):
restaurant = service.update_restaurant("1", RestaurantUpdate(name=None, address="1 New Rd"))

assert restaurant.name == "Pizza Palace"
assert restaurant.address == "1 New Rd"

def test_update_saves_the_change(service, repository):
service.update_restaurant("1", RestaurantUpdate(name="Pizza Palace Downtown"))

saved = repository.save_restaurants.call_args.args[0]
assert saved[0].name == "Pizza Palace Downtown"
assert saved[1].name == "Burger Barn"

def test_update_unknown_restaurant_is_rejected(service, repository):
with pytest.raises(RestaurantNotFoundError):
service.update_restaurant("does-not-exist", RestaurantUpdate(name="New Name"))

repository.save_restaurants.assert_not_called()

def test_update_into_duplicate_of_another_restaurant_is_rejected(service, repository):
with pytest.raises(DuplicateRestaurantError):
service.update_restaurant("1", RestaurantUpdate(name="Burger Barn", address="456 Oak St"))

repository.save_restaurants.assert_not_called()

def test_update_with_its_own_name_and_address_is_allowed(service):
restaurant = service.update_restaurant("1", RestaurantUpdate(name="Pizza Palace", address="123 Main St"))

assert restaurant.name == "Pizza Palace"
Loading