Skip to content

Instantly share code, notes, and snippets.

@lamogura
Created December 13, 2016 00:22
Show Gist options
  • Save lamogura/d95ef4ea9479eec6798742a31c88c871 to your computer and use it in GitHub Desktop.
Save lamogura/d95ef4ea9479eec6798742a31c88c871 to your computer and use it in GitHub Desktop.
pytest flask sqlalchemy setup that should work when model schemas are compatible with sqlite
# import pytest
# from server.api import create_app
# @pytest.fixture
# def client():
# return create_app().test_client()
# import os
import pytest
import json
from server.api import create_app
from server.core import db as _db
# TEST_DATABASE_URI = 'postgresql://localhost/tupacbio-test'
# ALEMBIC_CONFIG = os.path.join(os.getcwd(), 'alembic.ini')
class APIClient(object):
def __init__(self, test_client):
self.test_client = test_client
def get(self, *args, **kwargs):
return self.test_client.get(*args, **kwargs)
def get_json(self, *args, **kwargs):
res = self.get(*args, **kwargs)
if res.status_code == 200:
obj = json.loads(res.data.decode('utf8'))
return obj['data']
@pytest.fixture(scope='session')
def app(request):
"""Session-wide test `Flask` application."""
app = create_app()
# Establish an application context before running the tests.
ctx = app.app_context()
ctx.push()
def teardown():
ctx.pop()
request.addfinalizer(teardown)
return app
@pytest.fixture(scope='session')
def client(app):
"""Session-wide test client."""
return APIClient(app.test_client())
@pytest.fixture(scope='session')
def db(app, request):
"""Session-wide test database."""
def teardown():
_db.drop_all()
_db.app = app
_db.create_all()
request.addfinalizer(teardown)
return _db
@pytest.fixture(scope='function')
def session(db, request):
"""Creates a new database session for a test."""
connection = db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection, binds={})
session = db.create_scoped_session(options=options)
db.session = session
def teardown():
transaction.rollback()
connection.close()
session.remove()
request.addfinalizer(teardown)
return session
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment