|
| 1 | +import flask |
| 2 | +import pytest |
| 3 | +from bson import ObjectId |
| 4 | + |
| 5 | + |
| 6 | +@pytest.fixture(autouse=True) |
| 7 | +def setup_endpoints(app, todo): |
| 8 | + Todo = todo |
| 9 | + |
| 10 | + @app.route("/") |
| 11 | + def index(): |
| 12 | + return flask.jsonify(result=Todo.objects()) |
| 13 | + |
| 14 | + @app.route("/add", methods=["POST"]) |
| 15 | + def add(): |
| 16 | + form = flask.request.form |
| 17 | + todo = Todo(title=form["title"], text=form["text"]) |
| 18 | + todo.save() |
| 19 | + return flask.jsonify(result=todo) |
| 20 | + |
| 21 | + @app.route("/show/<id>/") |
| 22 | + def show(id): |
| 23 | + return flask.jsonify(result=Todo.objects.get_or_404(id=id)) |
| 24 | + |
| 25 | + |
| 26 | +def test_with_id(app, todo): |
| 27 | + Todo = todo |
| 28 | + client = app.test_client() |
| 29 | + response = client.get("/show/%s/" % ObjectId()) |
| 30 | + assert response.status_code == 404 |
| 31 | + |
| 32 | + response = client.post("/add", data={"title": "First Item", "text": "The text"}) |
| 33 | + assert response.status_code == 200 |
| 34 | + |
| 35 | + response = client.get("/show/%s/" % Todo.objects.first().id) |
| 36 | + assert response.status_code == 200 |
| 37 | + |
| 38 | + result = flask.json.loads(response.data).get("result") |
| 39 | + assert ("title", "First Item") in result.items() |
| 40 | + |
| 41 | + |
| 42 | +def test_basic_insert(app): |
| 43 | + client = app.test_client() |
| 44 | + client.post("/add", data={"title": "First Item", "text": "The text"}) |
| 45 | + client.post("/add", data={"title": "2nd Item", "text": "The text"}) |
| 46 | + rv = client.get("/") |
| 47 | + result = flask.json.loads(rv.data).get("result") |
| 48 | + |
| 49 | + assert len(result) == 2 |
0 commit comments