musicmuster/conftest.py
Keith Edmunds db86d04b9a Make alembic.ini safe
All database URLs are commented out. The appropriate one should be
uncommented when needed.
2022-03-02 09:08:27 +00:00

84 lines
1.8 KiB
Python

# https://stewartadam.io/blog/2019/04/04/testing-flask-applications-code-database-views-flask-config-and-app-context-pytest
import pytest
import sys
sys.path.append("app")
from config import Config # noqa E402
from flask import g # noqa E402
from kpi import create_app # noqa E402
from kpi import db as _db # noqa E402
class TestConfig(Config):
# TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'
PYTESTING = True
# @pytest.fixture(scope="module")
# def app():
# app = create_app(TestConfig)
# app_context = app.app_context()
# app_context.push()
# db.create_all()
# return app
@pytest.fixture
def no_bank_holidays():
"Set no bank holidays"
g.BankHolidays = []
@pytest.fixture(scope="session")
def app(request):
"""Test session-wide test `Flask` application."""
app = create_app(TestConfig)
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(scope="session")
def db(app, request):
"""Returns session-wide initialized database"""
with app.app_context():
_db.create_all()
yield _db
_db.drop_all()
@pytest.fixture(scope="function")
def session(app, db, request):
"""Creates a new database session for each test,
rolling back changes afterwards"""
connection = _db.engine.connect()
transaction = connection.begin()
options = dict(bind=connection, binds={})
session = _db.create_scoped_session(options=options)
_db.session = session
yield session
transaction.rollback()
connection.close()
session.remove()