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

如何使用pytest测试async异步函数?运行报错与测试跳过问题求解

解决方法

问题根因

你遇到的两个问题分别是版本兼容问题和异步用例标记缺失:

  1. 最初的收集错误是anyio 3.3.4和pytest 6.2.5版本不兼容,anyio的pytest插件调用了pytest 7.x才支持的get_closest_marker方法导致报错。
  2. 安装pytest-asyncio后仍跳过用例,是因为没有给异步测试用例添加对应的识别标记,pytest无法判定该用例的执行方式。

具体解决步骤

方案1:保留现有pytest 6.x版本

  1. 执行命令降级anyio到兼容pytest 6.x的版本:
    pip install anyio==3.2.1
  2. 取消测试用例上方@pytest.mark.asyncio标记的注释,修改后的测试代码如下:
@pytest.fixture
def d_service():
    c = DService()
    return c

@pytest.mark.asyncio
async def test_get_file_list(d_service):
    files = await d_service.get_file_list('')
    print(files)
  1. 重新运行pytest命令即可正常执行测试:
    pytest -s tests\e2e_tests\test_d.py

方案2:升级pytest到7.x版本(更通用)

  1. 执行命令升级pytest到适配新版本anyio的版本:
    pip install pytest>=7.0.0
  2. 给测试用例添加@pytest.mark.asyncio标记后即可运行。
    如果不想每次给异步用例单独加标记,可以在项目根目录的pytest配置文件(pytest.ini/pyproject.toml)中添加全局配置,以pytest.ini为例:

[pytest]
asyncio_mode = auto
配置后所有async def开头的测试用例都会自动被识别为异步用例,无需单独加标记。如果该配置不生效,执行命令升级pytest-asyncio到最新版本即可:
pip install -U pytest-asyncio

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 15:15:04