| 1 |
from datetime import datetime |
| 2 |
|
| 3 |
import pytest |
| 4 |
from werkzeug.security import generate_password_hash |
| 5 |
|
| 6 |
from flaskr import create_app |
| 7 |
from flaskr import db |
| 8 |
from flaskr import init_db |
| 9 |
from flaskr.auth.models import User |
| 10 |
from flaskr.blog.models import Post |
| 11 |
|
| 12 |
_user1_pass = generate_password_hash("test") |
| 13 |
_user2_pass = generate_password_hash("other") |
| 14 |
|
| 15 |
|
| 16 |
@pytest.fixture |
| 17 |
def app(): |
| 18 |
"""Create and configure a new app instance for each test.""" |
| 19 |
# create the app with common test config |
| 20 |
app = create_app({"TESTING": True, "SQLALCHEMY_DATABASE_URI": "sqlite:///:memory:"}) |
| 21 |
|
| 22 |
# create the database and load test data |
| 23 |
# set _password to pre-generated hashes, since hashing for each test is slow |
| 24 |
with app.app_context(): |
| 25 |
init_db() |
| 26 |
user = User(username="test", password_hash=_user1_pass) |
| 27 |
db.session.add_all( |
| 28 |
( |
| 29 |
user, |
| 30 |
User(username="other", password_hash=_user2_pass), |
| 31 |
Post( |
| 32 |
title="test title", |
| 33 |
body="test\nbody", |
| 34 |
author=user, |
| 35 |
created=datetime(2018, 1, 1), |
| 36 |
), |
| 37 |
) |
| 38 |
) |
| 39 |
db.session.commit() |
| 40 |
|
| 41 |
yield app |
| 42 |
|
| 43 |
|
| 44 |
@pytest.fixture |
| 45 |
def client(app): |
| 46 |
"""A test client for the app.""" |
| 47 |
return app.test_client() |
| 48 |
|
| 49 |
|
| 50 |
@pytest.fixture |
| 51 |
def runner(app): |
| 52 |
"""A test runner for the app's Click commands.""" |
| 53 |
return app.test_cli_runner() |
| 54 |
|
| 55 |
|
| 56 |
class AuthActions: |
| 57 |
def __init__(self, client): |
| 58 |
self._client = client |
| 59 |
|
| 60 |
def login(self, username="test", password="test"): |
| 61 |
return self._client.post( |
| 62 |
"/auth/login", data={"username": username, "password": password} |
| 63 |
) |
| 64 |
|
| 65 |
def logout(self): |
| 66 |
return self._client.get("/auth/logout") |
| 67 |
|
| 68 |
|
| 69 |
@pytest.fixture |
| 70 |
def auth(client): |
| 71 |
return AuthActions(client) |