From 011bb388aa4eb73bf71dfd567b0466ffba6f0200 Mon Sep 17 00:00:00 2001 From: Matt Jia Date: Feb 27 2017 23:03:47 +0000 Subject: tests: temporarily patch Flask-SQLAlchemy to use a specific connection Instead of replacing the whole session, we can temporarily patch Flask-SQLAlchemy to use a specific connection to workaround this issue[1]. This will make it easier if we want to inspect the state of the db after the test(comment out the monkeypatch and drop_all). [1] https://github.com/mitsuhiko/flask-sqlalchemy/issues/345 --- diff --git a/tests/conftest.py b/tests/conftest.py index db596eb..8050d00 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -39,29 +39,20 @@ def db(app, request): request.addfinalizer(teardown) return db -@pytest.fixture(scope='function') -def session(db, request): - """Creates a new database session for a test.""" +@pytest.yield_fixture +def session(db, monkeypatch): + """Patch Flask-SQLAlchemy to use a specific connection""" connection = db.engine.connect() transaction = connection.begin() - # https://github.com/mitsuhiko/flask-sqlalchemy/issues/345 - class _dict(dict): - def __nonzero__(self): - return True - - options = dict(bind=connection, binds=_dict()) - session = db.create_scoped_session(options=options) + # Patch Flask-SQLAlchemy to use our connection + monkeypatch.setattr(db, 'get_engine', lambda *args: connection) - db.session = session + yield db.session - def teardown(): - transaction.rollback() - connection.close() - session.remove() - - request.addfinalizer(teardown) - return session + db.session.remove() + transaction.rollback() + connection.close() @pytest.yield_fixture def client(app):