首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用@pytest.fixture(scope=“模块”)和@pytest.mark.asyncio

使用@pytest.fixture(scope=“模块”)和@pytest.mark.asyncio
EN

Stack Overflow用户
提问于 2019-05-21 10:47:45
回答 2查看 6.3K关注 0票数 10

我认为下面的示例是一个非常常见的用例:

  1. 创建一次到数据库的连接,
  2. 传递此连接以测试哪些插入数据
  3. 将连接传递到验证数据的测试。

更改@pytest.fixture(scope="module")的范围将导致ScopeMismatch: You tried to access the 'function' scoped fixture 'event_loop' with a 'module' scoped request object, involved factories

另外,test_inserttest_find协同器不需要event_loop参数,因为通过传递连接已经可以访问循环。

有什么办法解决这两个问题吗?

代码语言:javascript
运行
复制
import pytest

@pytest.fixture(scope="function")  # <-- want this to be scope="module"; run once!
@pytest.mark.asyncio
async def connection(event_loop):
    """ Expensive function; want to do in the module scope. Only this function needs `event_loop`!
    """
    conn await = make_connection(event_loop)
    return conn


@pytest.mark.dependency()
@pytest.mark.asyncio
async def test_insert(connection, event_loop):  # <-- does not need event_loop arg
    """ Test insert into database.

        NB does not need event_loop argument; just the connection.
    """
    _id = 0
    success = await connection.insert(_id, "data")
    assert success == True


@pytest.mark.dependency(depends=['test_insert'])
@pytest.mark.asyncio
async def test_find(connection, event_loop):  # <-- does not need event_loop arg
    """ Test database find.

        NB does not need event_loop argument; just the connection.
    """
    _id = 0
    data = await connection.find(_id)
    assert data == "data"
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-05-21 12:33:13

解决方案是重新定义带有模块作用域的event_loop夹具。将其包含在测试文件中。

代码语言:javascript
运行
复制
@pytest.fixture(scope="module")
def event_loop():
    loop = asyncio.get_event_loop()
    yield loop
    loop.close()
票数 18
EN

Stack Overflow用户

发布于 2020-08-19 17:53:47

github中也提出了类似的ScopeMismatch问题,用于pytest-异步(链接)。解决方案(以下)适用于我:

代码语言:javascript
运行
复制
@pytest.yield_fixture(scope='class')
def event_loop(request):
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56236637

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档