| 1 |
import pytest |
| 2 |
from flask import g |
| 3 |
from flask import session |
| 4 |
|
| 5 |
from flaskr import db |
| 6 |
from flaskr.auth.models import User |
| 7 |
|
| 8 |
|
| 9 |
def test_register(client, app): |
| 10 |
# test that viewing the page renders without template errors |
| 11 |
assert client.get("/auth/register").status_code == 200 |
| 12 |
|
| 13 |
# test that successful registration redirects to the login page |
| 14 |
response = client.post("/auth/register", data={"username": "a", "password": "a"}) |
| 15 |
assert response.headers["Location"] == "/auth/login" |
| 16 |
|
| 17 |
# test that the user was inserted into the database |
| 18 |
with app.app_context(): |
| 19 |
select = db.select(User).filter_by(username="a") |
| 20 |
user = db.session.execute(select).scalar() |
| 21 |
assert user is not None |
| 22 |
|
| 23 |
|
| 24 |
def test_user_password(app): |
| 25 |
user = User(username="a", password="a") |
| 26 |
assert user.password_hash != "a" |
| 27 |
assert user.check_password("a") |
| 28 |
|
| 29 |
|
| 30 |
@pytest.mark.parametrize( |
| 31 |
("username", "password", "message"), |
| 32 |
( |
| 33 |
("", "", "Username is required."), |
| 34 |
("a", "", "Password is required."), |
| 35 |
("test", "test", "already registered"), |
| 36 |
), |
| 37 |
) |
| 38 |
def test_register_validate_input(client, username, password, message): |
| 39 |
response = client.post( |
| 40 |
"/auth/register", data={"username": username, "password": password} |
| 41 |
) |
| 42 |
assert message in response.text |
| 43 |
|
| 44 |
|
| 45 |
def test_login(client, auth): |
| 46 |
# test that viewing the page renders without template errors |
| 47 |
assert client.get("/auth/login").status_code == 200 |
| 48 |
|
| 49 |
# test that successful login redirects to the index page |
| 50 |
response = auth.login() |
| 51 |
assert response.headers["Location"] == "/" |
| 52 |
|
| 53 |
# login request set the user_id in the session |
| 54 |
# check that the user is loaded from the session |
| 55 |
with client: |
| 56 |
client.get("/") |
| 57 |
assert session["user_id"] == 1 |
| 58 |
assert g.user.username == "test" |
| 59 |
|
| 60 |
|
| 61 |
@pytest.mark.parametrize( |
| 62 |
("username", "password", "message"), |
| 63 |
(("a", "test", "Incorrect username."), ("test", "a", "Incorrect password.")), |
| 64 |
) |
| 65 |
def test_login_validate_input(auth, username, password, message): |
| 66 |
response = auth.login(username, password) |
| 67 |
assert message in response.text |
| 68 |
|
| 69 |
|
| 70 |
def test_logout(client, auth): |
| 71 |
auth.login() |
| 72 |
|
| 73 |
with client: |
| 74 |
auth.logout() |
| 75 |
assert "user_id" not in session |