conftest.py 文件源码

python
阅读 27 收藏 0 点赞 0 评论 0

项目:python-web-boilerplate 作者: svenstaro 项目源码 文件源码
def dbtransaction(app, request, request_ctx, monkeypatch):
    """Temporary DB transaction.

    Use this if you want to operate on the real database but don't want changes to actually affect
    it outside of this test. This works using SQLAlchemy transactions.

    Transactions made outside of the session scope are not rolled back.
    """
    with app.app_context():
        connection = db.engine.connect()
        transaction = connection.begin()

        # Patch Flask-SQLAlchemy to use our connection
        monkeypatch.setattr(db, 'get_engine', lambda *args: connection)

        # Explicitly remove the session so that we'll get a new session every time we go here.
        db.session.remove()

        def teardown():
            # Since we are not committing things to the database directly when
            # testing, initially deferred constraints are not checked. The
            # following statement makes the DB check these constraints. We are
            # executing this command AFTER the tests and NOT BEFORE, because
            # within a transaction the DB is allowed to take temporarily
            # invalid state. Read
            # https://www.postgresql.org/docs/current/static/sql-set-constraints.html
            # for details.

            try:
                connection.execute('SET CONSTRAINTS ALL IMMEDIATE')
            except InternalError:
                # This is the case when we are doing something in the tests
                # that we expect it to fail by executing the statement above.
                # In this case, the transaction will be in an already failed
                # state, executing further SQL statements are ignored and doing
                # so raises an exception.
                pass

            transaction.rollback()
            connection.close()
        request.addfinalizer(teardown)

        return db
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号