I am using pytest as framework for testing my application and I want to use pytest factoryboy as well. Thusfar, my conftest.py looks pretty much like the example:
import factory
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from model import model
engine = create_engine('sqlite://')
session = scoped_session(sessionmaker(bind=engine))
# Create tables
model.Base.metadata.create_all(engine)
class ExampleFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = model.ExampleClass
sqlalchemy_session = session
label = factory.Sequence(lambda n: u'object_%d' % n)
I have multiple factories like this. The problem is that when I use factories in this manner, the session will not be torn down every unit test. I'm basically using one big session for the lot of unit tests that I have. Not very ideal. Using fixtures I could refresh a session every unit test. Is there a way to do this using factoryboy pytest?
Just tried a solution found here that do the job pretty well without being too complicated or dirty: wrapping each factory into a fixture which is provided with an other function-scoped session
fixture.
This could look like this for you:
@pytest.fixture
def session():
session = <session creation>
yield session
session.rollback()
session.close()
@pytest.fixture
def exemple_factory(session):
class ExampleFactory(factory.alchemy.SQLAlchemyModelFactory):
class Meta:
model = model.ExampleClass
sqlalchemy_session = session
label = factory.Sequence(lambda n: u'object_%d' % n)
return ExampleFactory
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With