~javiljoen/shopping-list

51c1cdffa3071d5f5b6bf750183bb409b482cec5 — JA Viljoen 4 years ago 8c594aa
Add POST /items handler
2 files changed, 55 insertions(+), 3 deletions(-)

M src/groceries/web/api.py
M tests/test_rest_server.py
M src/groceries/web/api.py => src/groceries/web/api.py +25 -3
@@ 1,6 1,6 @@
from flask import Blueprint, abort, current_app, jsonify, url_for
from flask import Blueprint, abort, current_app, jsonify, request, url_for

from groceries.model import GroceryList
from groceries.model import GroceryList, Item


def dictify(item):


@@ 24,6 24,11 @@ def resource_not_found(e):
    return jsonify(error=str(e)), 404


@bp.errorhandler(400)
def bad_request(e):
    return jsonify(error=str(e)), 400


@bp.route("/")
@bp.route("/items/")
def index():


@@ 32,6 37,23 @@ def index():
    return jsonify(items=[dictify(i) for i in items])


@bp.route("/items/", methods=["POST"])
def create_item():
    try:
        item = Item(**request.json)
    except TypeError:
        abort(400, description="Missing fields in request")

    grocery_list = GroceryList(current_app.config["BACKEND"])

    try:
        grocery_list.add_item(*item)
    except ValueError:
        abort(400, description=f"Item with name {item.name!r} already exists")

    return dictify(item), 201


@bp.route("/items/<name>")
def get_item(name):
    grocery_list = GroceryList(current_app.config["BACKEND"])


@@ 40,7 62,7 @@ def get_item(name):
    if not items:
        abort(404, description=f"No resource with name {name!r}")

    return jsonify(dictify(items[0]))
    return dictify(items[0])


@bp.route("/items/<name>", methods=["DELETE"])

M tests/test_rest_server.py => tests/test_rest_server.py +30 -0
@@ 80,3 80,33 @@ def test_delete_unknown_item(client):
    assert response.get_json() == {
        "error": "404 Not Found: No resource with name 'jabberwocky'"
    }


def test_create_item(client):
    item = dict(name="turkey", section="frozen", priority=2)
    response = client.post("/api/items/", json=item)
    assert response.status_code == 201
    assert response.get_json() == dict(
        **item, preferred_shop=None, url="/api/items/turkey"
    )
    assert client.get("/api/items/turkey").status_code == 200


def test_create_item_with_missing_fields(client):
    response = client.post("/api/items/")
    assert response.status_code == 400

    response = client.post("/api/items/", json={"name": "turkey"})
    assert response.status_code == 400
    assert response.get_json() == {
        "error": "400 Bad Request: Missing fields in request"
    }


def test_create_existing_item(client):
    item = dict(name="apples", section="fruit", priority=0)
    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"
    }