Skip to content

Commit

Permalink
Move session setup closer to documentation example
Browse files Browse the repository at this point in the history
  • Loading branch information
grahamalama committed Mar 8, 2023
1 parent a1ab292 commit b561dfb
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions tests/unit/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,18 +124,23 @@ def dbsession(connection):
"""
transaction = connection.begin()
session = ScopedSessionLocal()
nested = session.begin_nested()
nested = connection.begin_nested()

# If the application code calls session.commit, it will end the nested
# transaction. Need to start a new one when that happens.
@event.listens_for(ScopedSessionLocal, "after_transaction_end")
@event.listens_for(session, "after_transaction_end")
def end_savepoint(*args):
nonlocal nested
if nested.is_active:
if not nested.is_active:
session.expire_all()
nested = session.begin_nested()
nested = connection.begin_nested()

yield session
# a nescessary addition to the example in the documentation linked above.
# Without this, the listener is not removed after each test ends and
# SQLAlchemy emits warnings:
# `SAWarning: nested transaction already deassociated from connection`
event.remove(session, "after_transaction_end", end_savepoint)
session.close()
transaction.rollback()

Expand Down

0 comments on commit b561dfb

Please sign in to comment.