Skip to content

Instantly share code, notes, and snippets.

@drocco007
Last active January 25, 2016 22:45
Show Gist options
  • Save drocco007/8485816 to your computer and use it in GitHub Desktop.
Save drocco007/8485816 to your computer and use it in GitHub Desktop.
py.test + SQLAlchemy transactional testing
import pytest
from turbogears.database import get_engine, session
@pytest.fixture(autouse=True)
def wrap_transaction(request):
"""Automatically wrap test cases in a transaction, rolled back on
completion. Uses an "external," non-ORM transaction that is durable
against inner transactions used by the ORM. Thanks to @sontek
http://sontek.net/blog/detail/writing-tests-for-pyramid-and-sqlalchemy
"""
connection = get_engine().connect()
# begin a non-ORM transaction
transaction = connection.begin()
session.bind = connection
def _tear_down():
transaction.rollback()
session.close()
connection.close()
request.addfinalizer(_tear_down)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment