【问题标题】:How to use coroutine as a pytest fixture?如何使用协程作为 pytest 夹具?
【发布时间】:2016-12-28 11:06:19
【问题描述】:

是否可以将 pytest 固定装置编写为龙卷风协程?例如,我想编写一个用于创建数据库的夹具,如下所示:

from tornado import gen
import pytest

@pytest.fixture
@gen.coroutine
def get_db_connection():
    # set up
    db_name = yield create_db()
    connection = yield connect_to_db(db_name)

    yield connection

    # tear down
    yield drop_db(db_name)


@pytest.mark.gen_test
def test_something(get_db_connection):
    # some tests

很明显,这个fixture不能像预期的那样工作,因为它是作为一个函数调用的,而不是作为协程调用的。有办法解决吗?

【问题讨论】:

    标签: python tornado pytest


    【解决方案1】:

    经过一番研究,我得出了这个解决方案:

    from functools import partial
    from tornado import gen
    import pytest
    
    @pytest.fixture
    def get_db_connection(request, io_loop): # io_loop is a fixture from pytest-tornado
        def fabric():
            @gen.coroutine
            def set_up(): 
                db_name = yield create_db()
                connection = yield connect_to_db(db_name)
                raise gen.Return(connection)
            @gen.coroutine
            def tear_down():
                yield drop_db(db_name)
            request.addfinalizer(partial(io_loop.run_sync, tear_down))
            connection = io_loop.run_sync(set_up)
            return connection
    
        return fabric
    
    
    @pytest.mark.gen_test
    def test_something(get_db_connection):
        connection = get_db_connection()  # note brackets
    

    我敢肯定,使用一些 pylint 魔法可以做得更干净。 我发现this slides 非常有用。

    编辑:我发现上述方法有一个限制。您无法更改 get_db_connection 夹具的范围,因为它使用 io_loop 夹具和范围“功能”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多