繁体   English   中英

在 Flask-SQLAlchemy 中隔离 py.test 数据库会话

[英]Isolating py.test DB sessions in Flask-SQLAlchemy

我正在尝试使用 Flask-SQLAlchemy 构建 Flask 应用程序; 我使用 pytest 来测试数据库。 问题之一似乎是在不同测试之间创建隔离的数据库会话。

我编写了一个最小的、完整的示例来突出问题,注意test_user_schema1()test_user_schema2()是相同的。

文件名: test_db.py

from models import User

def test_user_schema1(session):
    person_name = 'Fran Clan'
    uu = User(name=person_name)
    session.add(uu)
    session.commit()

    assert uu.id==1
    assert uu.name==person_name

def test_user_schema2(session):
    person_name = 'Stan Clan'
    uu = User(name=person_name)
    session.add(uu)
    session.commit()

    assert uu.id==1
    assert uu.name==person_name

如果数据库在我的测试之间真正隔离,则两个测试都应该通过。 但是,最后一次测试总是失败,因为我还没有找到正确回滚数据库会话的方法。

sqlalchemy_session_fail

conftest.py根据我在Alex Michael 的博客文章中看到的内容使用以下内容,但此夹具代码中断,因为它显然没有隔离夹具之间的数据库会话。

@pytest.yield_fixture(scope='function')
def session(app, db):
    connection = db.engine.connect()
    transaction = connection.begin()

    #options = dict(bind=connection, binds={})
    options = dict(bind=connection)
    session = db.create_scoped_session(options=options)

    yield session

    # Finalize test here
    transaction.rollback()
    connection.close()
    session.remove()

出于这个问题的目的,我构建了一个 gist ,其中包含重现它所需的所有内容; 你可以用git clone https://gist.github.com/34fa8d274fc4be240933.git克隆它。

我正在使用以下软件包...

Flask==0.10.1
Flask-Bootstrap==3.3.0.1
Flask-Migrate==1.3.0
Flask-Moment==0.4.0
Flask-RESTful==0.3.1
Flask-Script==2.0.5
Flask-SQLAlchemy==2.0
Flask-WTF==0.11
itsdangerous==0.24
pytest==2.6.4
Werkzeug==0.10.1

两个问题:

  1. 为什么现状会被打破? 这个相同的 py.test 固定装置似乎对其他人有用。
  2. 我该如何解决这个问题才能正常工作?

Alex Michael 的博客文章中介绍的方法不起作用,因为它不完整。 根据有关加入会话sqlalchemy 文档,Alex 的解决方案仅在没有回滚调用时才有效。 另一个区别是,与 Alex 博客上的作用域会话相比,sqla 文档中使用了 vanilla Session对象。

在flask-sqlalchemy 的情况下,范围会话会在请求拆卸时自动删除。 调用session.remove会在session.remove发出回滚。 要支持测试范围内的回滚,请使用SAVEPOINT

import sqlalchemy as sa


@pytest.yield_fixture(scope='function')
def db_session(db):
    """
    Creates a new database session for a test. Note you must use this fixture
    if your test connects to db.

    Here we not only support commit calls but also rollback calls in tests.
    """
    connection = db.engine.connect()
    transaction = connection.begin()

    options = dict(bind=connection, binds={})
    session = db.create_scoped_session(options=options)

    session.begin_nested()

    # session is actually a scoped_session
    # for the `after_transaction_end` event, we need a session instance to
    # listen for, hence the `session()` call
    @sa.event.listens_for(session(), 'after_transaction_end')
    def restart_savepoint(sess, trans):
        if trans.nested and not trans._parent.nested:
            session.expire_all()
            session.begin_nested()

    db.session = session

    yield session

    session.remove()
    transaction.rollback()
    connection.close()

不过,您的数据库必须支持SAVEPOINT

1.

根据会话基础 - SQLAlchemy 文档

commit()用于提交当前事务。 它总是预先发出 flush() 来将任何剩余状态刷新到数据库; 这与“自动冲洗”设置无关。 ....

所以sessionfixture函数中的transaction.rollback()不会生效,因为事务已经提交了。


2.

将设备的范围更改为function而不是session以便每次都清除 db。

@pytest.yield_fixture(scope='function')
def app(request):
    ...

@pytest.yield_fixture(scope='function')
def db(app, request):
    ...

顺便说一句,如果您使用内存中的sqlite数据库,则不需要删除db文件,而且速度会更快:

DB_URI = 'sqlite://'  # SQLite :memory: database

...

@pytest.yield_fixture(scope='function')
def db(app, request):
    _db.app = app
    _db.create_all()
    yield _db
    _db.drop_all()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM