factoryboy pytest 会话管理

has*_*bal 5 python unit-testing pytest factory-boy

我使用 pytest 作为测试我的应用程序的框架,我也想使用 pytest factoryboy。到目前为止,我的 conftest.py 看起来很像这个例子:

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)
Run Code Online (Sandbox Code Playgroud)

我有多个这样的工厂。问题是当我以这种方式使用工厂时,会话不会在每个单元测试中被拆除。我基本上使用一个大的会话来进行大量的单元测试。不是很理想。使用固定装置,我可以在每个单元测试中刷新一个会话。有没有办法使用 factoryboy pytest 做到这一点?

Try*_*yph 1

刚刚尝试了这里找到的一个解决方案,该解决方案可以很好地完成工作,而又不会太复杂或太脏:将每个工厂包装到一个固定装置中,该固定装置配有其他功能范围的固定session装置。

这对你来说可能是这样的:

@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
Run Code Online (Sandbox Code Playgroud)