Debian Codegraph @

examples/flaskr/tests/test_blog.py

raw
1 import pytest
2
3 from flaskr import db
4 from flaskr.auth.models import User
5 from flaskr.blog.models import Post
6
7
8 def test_index(client, auth):
9 text = client.get("/").text
10 assert "Log In" in text
11 assert "Register" in text
12
13 auth.login()
14 text = client.get("/").text
15 assert "test title" in text
16 assert "by test on 2018-01-01" in text
17 assert "test\nbody" in text
18 assert 'href="/1/update"' in text
19
20
21 @pytest.mark.parametrize("path", ("/create", "/1/update", "/1/delete"))
22 def test_login_required(client, path):
23 response = client.post(path)
24 assert response.headers["Location"] == "/auth/login"
25
26
27 def test_author_required(app, client, auth):
28 # change the post author to another user
29 with app.app_context():
30 db.session.get(Post, 1).author = db.session.get(User, 2)
31 db.session.commit()
32
33 auth.login()
34 # current user can't modify other user's post
35 assert client.post("/1/update").status_code == 403
36 assert client.post("/1/delete").status_code == 403
37 # current user doesn't see edit link
38 assert 'href="/1/update"' not in client.get("/").text
39
40
41 @pytest.mark.parametrize("path", ("/2/update", "/2/delete"))
42 def test_exists_required(client, auth, path):
43 auth.login()
44 assert client.post(path).status_code == 404
45
46
47 def test_create(client, auth, app):
48 auth.login()
49 assert client.get("/create").status_code == 200
50 client.post("/create", data={"title": "created", "body": ""})
51
52 with app.app_context():
53 select = db.select(db.func.count(Post.id))
54 post_count = db.session.execute(select).scalar()
55 assert post_count == 2
56
57
58 def test_update(client, auth, app):
59 auth.login()
60 assert client.get("/1/update").status_code == 200
61 client.post("/1/update", data={"title": "updated", "body": ""})
62
63 with app.app_context():
64 assert db.session.get(Post, 1).title == "updated"
65
66
67 @pytest.mark.parametrize("path", ("/create", "/1/update"))
68 def test_create_update_validate(client, auth, path):
69 auth.login()
70 response = client.post(path, data={"title": "", "body": ""})
71 assert "Title is required." in response.text
72
73
74 def test_delete(client, auth, app):
75 auth.login()
76 response = client.post("/1/delete")
77 assert response.headers["Location"] == "/"
78
79 with app.app_context():
80 assert db.session.get(Post, 1) is None