You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Poetry构建Python项目时Pytest异步测试警告问题

解决pytest异步测试警告问题

问题场景

使用Poetry构建Python项目,编写了如下异步测试代码:

import httpx
import respx


@respx.mock
async def test_async_decorator():
    async with httpx.AsyncClient() as client:
        route = respx.get("https://example.org/")
        response = await client.get("https://example.org/")
        assert route.called
        assert response.status_code == 200

运行poetry run pytest或pytest时,出现警告导致测试被跳过:

test_gsx.py::test_async_decorator
  /Users/krishna/Library/Caches/pypoetry/virtualenvs/geoserverx-Yc0Bl2cH-py3.11/lib/python3.11/site-packages/_pytest/python.py:183: PytestUnhandledCoroutineWarning: async def functions are not natively supported and have been skipped.
  You need to install a suitable plugin for your async framework, for example:
    - anyio
    - pytest-asyncio
    - pytest-tornasync
    - pytest-trio
    - pytest-twisted
    warnings.warn(PytestUnhandledCoroutineWarning(msg.format(nodeid)))

-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html

项目的pyproject.toml开发依赖已包含pytest-asyncio和anyio:

[tool.poetry.group.dev.dependencies]
pytest = "^7.1.2"
respx = "^0.20.1"
mypy = "^0.960"
black = "^22.3.0"
isort = "^5.10.1"
pytest-asyncio = "^0.21.0"
anyio = {extras = ["trio"], version = "^3.3.4"}

解决方案

  • 检查插件加载状态
    运行poetry run pytest --trace-config查看已加载的插件列表,确认pytest_asyncio在输出中。如果未加载,执行poetry install --sync重新同步依赖,确保插件安装到虚拟环境中。

  • 升级依赖版本
    旧版本的pytest(7.1.2)和pytest-asyncio(0.21.0)在Python 3.11下可能存在兼容性问题。修改pyproject.toml中的依赖版本:

    pytest = "^7.4.0"
    pytest-asyncio = "^0.23.0"
    

    然后执行poetry update pytest pytest-asyncio完成升级。

  • 添加pytest异步模式配置
    在pyproject.toml中添加pytest配置,显式启用pytest-asyncio的自动识别模式:

    [tool.pytest.ini_options]
    asyncio_mode = "auto"
    
  • 确保使用正确的虚拟环境
    避免直接运行全局的pytest,始终使用poetry run pytest来执行测试,确保调用的是虚拟环境中安装的pytest及插件。

  • 调整装饰器顺序并显式标记异步测试
    在测试函数上添加@pytest.mark.asyncio装饰器,并放在@respx.mock之前,确保pytest能识别这是异步测试:

    import httpx
    import respx
    import pytest
    
    @pytest.mark.asyncio
    @respx.mock
    async def test_async_decorator():
        async with httpx.AsyncClient() as client:
            route = respx.get("https://example.org/")
            response = await client.get("https://example.org/")
            assert route.called
            assert response.status_code == 200
    

内容的提问来源于stack exchange,提问作者krishna lodha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 07:38:11