~javiljoen/shopping-list

894d062917e5a80dcbdd983d1d1521396341c95a — JA Viljoen 4 years ago 958f919
Use url_for() to generate resource URLs

dictify() can no longer be easily tested, since it must be done against
a running Flask app. Thus, its test has been incorporated directly into
the `get_item` test; and the `index` test now delegates to `get_item`.
2 files changed, 18 insertions(+), 21 deletions(-)

M src/groceries/web/api.py
M tests/test_rest_server.py
M src/groceries/web/api.py => src/groceries/web/api.py +6 -5
@@ 1,17 1,18 @@
from urllib.parse import quote

from flask import Blueprint, abort, current_app, jsonify
from flask import Blueprint, abort, current_app, jsonify, url_for

from groceries.model import GroceryList


def dictify(item):
    with current_app.app_context():
        url = url_for(".get_item", name=item.name)

    return {
        "name": item.name,
        "section": item.section,
        "priority": item.priority,
        "preferred_shop": item.shop,
        "url": "/items/" + quote(item.name),
        "url": url,
    }




@@ 32,7 33,7 @@ def index():


@bp.route("/items/<name>")
def item(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]


M tests/test_rest_server.py => tests/test_rest_server.py +12 -16
@@ 1,9 1,9 @@
from urllib.parse import quote

import pytest

from groceries.model import Item
from groceries.sqldb import SqliteDB
from groceries.web import wsgi
from groceries.web.api import dictify


@pytest.mark.parametrize(


@@ 33,18 33,6 @@ def test_backend_configuration_fails_if_envvar_unset(monkeypatch):
        wsgi.main()


def test_dictify():
    item = Item("baking powder", "pantry", 1, None)

    assert dictify(item) == {
        "name": item.name,
        "section": item.section,
        "priority": item.priority,
        "preferred_shop": item.shop,
        "url": "/items/baking%20powder",
    }


@pytest.fixture()
def client(sqldb_mem):
    app = wsgi.create_app(backend=sqldb_mem)


@@ 54,14 42,22 @@ def client(sqldb_mem):
def test_get_items(client, items):
    response = client.get("/api/items/")
    assert response.status_code == 200
    assert response.get_json()["items"] == [dictify(i) for i in items]
    assert response.get_json() == {
        "items": [client.get("/api/items/" + i.name).get_json() for i in items]
    }


def test_get_an_item(client, items):
    item = items[-1]
    response = client.get("/api/items/" + item.name)
    assert response.status_code == 200
    assert response.get_json() == dictify(item)
    assert response.get_json() == dict(
        name=item.name,
        section=item.section,
        priority=item.priority,
        preferred_shop=item.shop,
        url="/api/items/" + quote(item.name),
    )


def test_get_an_unknown_item(client):