首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用pytest的异步装置

使用pytest的异步装置
EN

Stack Overflow用户
提问于 2018-04-20 15:53:31
回答 4查看 25.4K关注 0票数 22

如何定义异步fixture并在异步测试中使用它们?

下面的代码都在同一个文件中,非常失败。是否测试运行者直接调用了fixture,而不是等待它?

代码语言:javascript
复制
@pytest.fixture
async def create_x(api_client):
    x_id = await add_x(api_client)
    return api_client, x_id

async def test_app(create_x, auth):
    api_client, x_id = create_x
    resp = await api_client.get(f'my_res/{x_id}', headers=auth)
    assert resp.status == web.HTTPOk.status_code

生产

代码语言:javascript
复制
==================================== ERRORS ====================================
_____________ ERROR at setup of test_app[pyloop] ______________

api_client = <aiohttp.test_utils.TestClient object at 0x7f27ec954f60>

    @pytest.fixture
    async def create_x(api_client):
>       x_id = await add_x(api_client)
...
... cannot show the full trace and pathnames sorry
...    

in __await__
    ret = yield from self._coro /home/mbb/.pyenv/versions/3.6.3/envs/mr/lib/python3.6/site-packages/aiohttp/test_utils.py:245: in request
    method, self.make_url(path), *args, **kwargs /home/mbb/.pyenv/versions/mr/lib/python3.6/site-packages/aiohttp/helpers.py:104: in __iter__
    ret = yield from self._coro /home/mbb/.pyenv/versions/mr/lib/python3.6/site-packages/aiohttp/client.py:221: in _request
    with timer:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <aiohttp.helpers.TimerContext object at 0x7f27ec9875c0>

    def __enter__(self):
        task = current_task(loop=self._loop)

        if task is None:
>           raise RuntimeError('Timeout context manager should be used '
                               'inside a task') E           RuntimeError: Timeout context manager should be used inside a task

/home/mbb/.pyenv/versions/mr/lib/python3.6/site-packages/aiohttp/helpers.py:717: RuntimeError
=========================== 1 error in 1.74 seconds ============================ Process finished with exit code 0

我知道我也许能做到

代码语言:javascript
复制
@pytest.fixture
def create_x(loop, api_client):
    x_id = loop.run_until_complete(add_x(api_client))
    return api_client, x_id

但我想知道是否存在一种更简单/最优雅的方式。我在pytest、pytest-asyncio、pytest-aiohttp的项目页面中都找不到清晰而简单的示例/解释。

我使用的是Python 3.6.3、pytest 3.4.2、pytest-asyncio 0.8.0和pytest-aiohttp 0.3.0

非常感谢您的帮助

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-04-20 19:21:11

您只需将测试标记为异步

代码语言:javascript
复制
@pytest.mark.asyncio
async def test_app(create_x, auth):
    api_client, x_id = create_x
    resp = await api_client.get(f'my_res/{x_id}', headers=auth)
    assert resp.status == web.HTTPOk.status_code

这告诉pytest在事件循环中运行测试,而不是直接调用它。

可以将这些设备标记为正常

代码语言:javascript
复制
@pytest.fixture
async def create_x(api_client):
    x_id = await add_x(api_client)
    return api_client, x_id
票数 48
EN

Stack Overflow用户

发布于 2019-08-07 04:25:10

PyTest本身并不支持协程函数,因此您需要为其安装额外的框架

  • pytest-aiohttp
  • pytest-asyncio
  • pytest-trio
  • pytest-tornasync

如果你使用pytest-aiohttp,你的问题就这样解决了。

代码语言:javascript
复制
import asyncio
import pytest

from app import db


url = 'postgresql://postgres:postgres@localhost:5432'


@pytest.fixture(scope='session')
def loop():
    return asyncio.get_event_loop()


@pytest.fixture(scope='session', autouse=True)
async def prepare_db(loop):
    async with db.with_bind(f'{url}/postgres') as engine:
        await engine.status(db.text('CREATE DATABASE test_db'))

    await db.set_bind(f'{url}/test_db')
    await db.gino.create_all()

    yield
    await db.bind.close()

    async with db.with_bind(f'{url}/postgres') as engine:
        await engine.status(db.text('DROP DATABASE test_db'))

主要思想是使用异步fixtures将使用的同步loop-fixture

票数 12
EN

Stack Overflow用户

发布于 2021-11-14 22:06:37

将此代码放在conftest.py中,以标记所有异步函数:

代码语言:javascript
复制
import inspect
import pytest

def pytest_collection_modifyitems(config, items):
    for item in items:
        if inspect.iscoroutinefunction(item.function):
            item.add_marker(pytest.mark.asyncio)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49936724

复制
相关文章

相似问题

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