M src/groceries/model.py => src/groceries/model.py +8 -0
@@ 24,6 24,14 @@ class GroceryList:
return items
+ def get_item(self, item_name):
+ item = self._repo.select(item_name)
+
+ if item is None:
+ raise LookupError(f"{item_name!r} not found in grocery list.")
+
+ return item
+
def add_item(self, name, section, priority, shop):
new_item = Item(name, section, priority, shop)
M src/groceries/web/api.py => src/groceries/web/api.py +11 -10
@@ 48,8 48,8 @@ def create_item():
try:
grocery_list.add_item(*item)
- except ValueError:
- abort(400, description=f"Item with name {item.name!r} already exists")
+ except ValueError as err:
+ abort(400, description=str(err))
return dictify(item), 201
@@ 57,21 57,22 @@ def create_item():
@bp.route("/items/<name>")
def get_item(name):
grocery_list = GroceryList(current_app.config["BACKEND"])
- items = [i for i in grocery_list.list_items() if i.name == name]
- if not items:
- abort(404, description=f"No resource with name {name!r}")
+ try:
+ item = grocery_list.get_item(name)
+ except LookupError as err:
+ abort(404, description=str(err))
- return dictify(items[0])
+ return dictify(item)
@bp.route("/items/<name>", methods=["DELETE"])
def delete_item(name):
grocery_list = GroceryList(current_app.config["BACKEND"])
- items = [i for i in grocery_list.list_items() if i.name == name]
- if not items:
- abort(404, description=f"No resource with name {name!r}")
+ try:
+ grocery_list.delete_item(name)
+ except LookupError as err:
+ abort(404, description=str(err))
- grocery_list.delete_item(name)
return jsonify(result=True), 204
M tests/test_rest_server.py => tests/test_rest_server.py +3 -3
@@ 64,7 64,7 @@ def test_get_an_unknown_item(client):
response = client.get("/api/items/jabberwocky")
assert response.status_code == 404
assert response.get_json() == {
- "error": "404 Not Found: No resource with name 'jabberwocky'"
+ "error": "404 Not Found: 'jabberwocky' not found in grocery list."
}
@@ 78,7 78,7 @@ def test_delete_unknown_item(client):
response = client.delete("/api/items/jabberwocky")
assert response.status_code == 404
assert response.get_json() == {
- "error": "404 Not Found: No resource with name 'jabberwocky'"
+ "error": "404 Not Found: 'jabberwocky' not found in grocery list."
}
@@ 108,5 108,5 @@ def test_create_existing_item(client):
response = client.post("/api/items/", json=item)
assert response.status_code == 400
assert response.get_json() == {
- "error": "400 Bad Request: Item with name 'apples' already exists"
+ "error": "400 Bad Request: 'produce: apples' already in grocery list."
}