Skip to content

Instantly share code, notes, and snippets.

@tspng
Created December 17, 2019 14:21
Show Gist options
  • Save tspng/612ede4702243582905e61afdcc1cc6d to your computer and use it in GitHub Desktop.
Save tspng/612ede4702243582905e61afdcc1cc6d to your computer and use it in GitHub Desktop.
Flask, Flask-Login, pytest example
import pytest
from backend import create_app
from backend.auth.models import User, Role
@pytest.fixture(scope="session")
def monkeypatch_session(request):
"""
Experimental session scoped monkeypatch fixture, see
https://github.com/pytest-dev/pytest/issues/363
"""
from _pytest.monkeypatch import MonkeyPatch
mpatch = MonkeyPatch()
yield mpatch
mpatch.undo()
@pytest.fixture
def client(app):
"""
A Flask test client. An instance of :class:`flask.testing.TestClient` by default.
"""
with app.test_client() as client:
yield client
@pytest.fixture(scope="session")
def app(request, monkeypatch_session):
"""Session-wide test `Flask` application."""
monkeypatch_session.setenv("FLASK_ENV", "testing")
app = create_app()
return app
@pytest.fixture(autouse=True)
def _setup_app_context_for_test(request, app):
"""
Given app is session-wide, sets up a app context per test to ensure that
app and request stack is not shared between tests.
"""
ctx = app.app_context()
ctx.push()
yield # tests will run here
ctx.pop()
@pytest.fixture()
def db(app, request):
"""Return a newly initialized database"""
from mpt.extensions import db as _db
with app.app_context():
_db.create_all()
yield _db
_db.drop_all()
@pytest.fixture
def admin(app):
"""Return an admin user instance."""
user = User(email=app.config["TESTUSER_EMAIL"], role=Role.ADMIN)
user.set_password(app.config["TESTUSER_PASSWORD"])
# Store the password in cleartext on this object, for ease of use during testing
user._cleartext_password = app.config["TESTUSER_PASSWORD"]
return user
@pytest.fixture
def as_admin(client, db, admin):
"""Log in as admin, use this fixture to test protected views."""
db.session.add(admin)
return client.post(
"/auth/login",
data=dict(email=admin.email, password=admin._cleartext_password),
follow_redirects=True,
)
import pytest
@pytest.mark.usefixtures("as_admin")
def test_user_list(client, admin):
r = client.get("/auth/user/list")
assert r.status_code == 200
assert b"User List" in r.data
assert bytes(admin.email, "utf-8") in r.data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment