#6 tests: temporarily patch Flask-SQLAlchemy to use a specific connection
Closed 3 years ago by mjia. Opened 3 years ago by mjia.
mjia/waiverdb master  into  master

file modified
+9 -18
@@ -39,29 +39,20 @@ 

      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):

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

Pull-Request has been closed by mjia

3 years ago
Metadata