How to use Factory Boy with SQLAlchemy session (Lazy Loaded) correctly?

Rem*_* L. 2 sqlalchemy nosetests flask factory-boy

I just run into a problem with my testsuite. I am using a setup with nosetests, SQLAlchemy, Flask and Factory-Boy

I have the following code:

def _create_fixtures(self):
    self.user = UserFactory()
    pprint(db.query(User).all())
    db.add(self.user)
    pprint(db.query(User).all())
Run Code Online (Sandbox Code Playgroud)

witch returns following:

[<User #1>, <User #2>]
[<User #1>, <User #2>]
Run Code Online (Sandbox Code Playgroud)

My UserFactory looks like this:

class UserFactory(Factory):
    FACTORY_FOR = User
    FACTORY_SESSION = db
    email = Sequence(lambda n: 'user{0}@wohnortfinder.com'.format(n))
    password = "password"
    username = Sequence(lambda n: 'user{0}'.format(n))
Run Code Online (Sandbox Code Playgroud)

(yes I am using the normal Factory and not he SQLAlchemy factory, cause this didn't work either)

Why isn't my Factory Object stored to db? It doesn't raise an error, it just doesn't save. I mean even when the current transaction is not committed yet, the query later should queries the actual transaction, shouldn't it?

Oddly when I manually commit the session, it raises an error.

InvalidRequestError: No transaction is begun.
Run Code Online (Sandbox Code Playgroud)

Even though I began a transaction when creating the session object.

def init_engine(uri, **kwargs):
    global engine
    engine = create_engine(uri, **kwargs)
    Base.metadata.create_all(engine)
    db.begin()
    return engine


engine = None

db = scoped_session(lambda: create_session(bind=engine))
Run Code Online (Sandbox Code Playgroud)

any idea why this is not working?

Thanks for your thoughts

And*_*gee 7

您可以在不设置 SQLAlchemy 会话的情况下定义 factory_boy 工厂,然后通过分配给_meta工厂类的属性在初始化 Flask 应用程序和使用工厂之间进行设置:

db_session = set_up_a_db_session_somehow()
MyFactoryClass._meta.sqlalchemy_session = db_session
Run Code Online (Sandbox Code Playgroud)

这似乎适用于范围会话。