Skip to content

Instantly share code, notes, and snippets.

@einSelbst
Forked from kissgyorgy/sqlalchemy_conftest.py
Created March 14, 2018 12:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save einSelbst/6dd2d17e670f416271c45c4f27610e6f to your computer and use it in GitHub Desktop.
Save einSelbst/6dd2d17e670f416271c45c4f27610e6f to your computer and use it in GitHub Desktop.
Python: py.test fixture for SQLAlchemy test in a transaction, create tables only once!
from sqlalchemy import create_engine
from sqlalchemy.orm import Session
from myapp.models import BaseModel
import pytest
@pytest.fixture(scope='session')
def engine():
return create_engine('postgresql://localhost/test_database)
@pytest.yield_fixture(scope='session')
def tables(engine):
BaseModel.metadata.create_all(engine)
yield
BaseModel.metadata.drop_all(engine)
@pytest.yield_fixture
def dbsession(engine, tables):
"""Returns an sqlalchemy session, and after the test tears down everything properly."""
connection = engine.connect()
# begin the nested transaction
transaction = connection.begin()
# use the connection with the already started transaction
session = Session(bind=connection)
yield session
session.close()
# roll back the broader transaction
transaction.rollback()
# put back the connection to the connection pool
connection.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment