簡體   English   中英

如何使用協程作為pytest固定裝置?

[英]How to use coroutine as a pytest fixture?

是否可以將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

顯然,此固定裝置無法按預期工作,因為它被稱為功能而不是協程。 有辦法解決嗎?

經過研究,我得出了以下解決方案:

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魔術將其清理干凈。 我發現此幻燈片非常有用。

編輯:我發現上述方法有局限性。 您不能更改get_db_connection固定裝置的范圍,因為它使用io_loop固定裝置和“功能”范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM