GitLab CI运行pytest提示缺失pytest-asyncio致异步测试跳过
问题描述
我正在参考aiohttp chat sample实现自有版本的聊天应用,所用技术栈如下:
- Python 3.10
- poetry 作为依赖管理工具
- pytest 作为测试框架
当前已安装的开发依赖配置:
[tool.poetry.dev-dependencies] pytest = "^7.1.2" pytest-aiohttp = "^1.0.4"
本地执行命令查看虚拟环境站点包目录,确认pytest-asyncio已安装,本地跑测试不会被跳过:
$ ls .venv/lib/python3.10/site-packages/ | grep -i 'pytest_asyncio' pytest_asyncio pytest_asyncio-0.19.0.dist-info
但在GitLab CI流水线中运行测试时出现如下告警,唯一的测试用例被跳过:
=============================== warnings summary =============================== tests/test_chat.py::test_msg_sending /builds/danieletentoni/[MASKED]/.venv/lib/python3.10/site-packages/_pytest/python.py:181: 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))) tests/test_chat.py::test_msg_sending /builds/danieletentoni/[MASKED]/.venv/lib/python3.10/site-packages/_pytest/runner.py:136: RuntimeWarning: coroutine 'client' was never awaited item.funcargs = None # type: ignore[attr-defined] Enable tracemalloc to get traceback where the object was allocated. See https://docs.pytest.org/en/stable/how-to/capture-warnings.html#resource-warnings for more info. -- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html ======================== 1 skipped, 2 warnings in 0.10s ========================
告警提示async def函数无原生支持已被跳过,需要安装pytest-asyncio等异步框架适配插件。
排查解决步骤
- 先核对CI环境的实际依赖安装情况
本地存在pytest-asyncio是因为旧版pytest-aiohttp会将其作为传递依赖自动安装,但CI环境很可能因为锁文件未同步提交、依赖安装参数错误、旧缓存污染导致该包缺失。直接在CI的依赖安装步骤后添加poetry run pip list | grep pytest命令,打印所有pytest相关包,先确认CI环境中pytest-asyncio是否真的安装成功。 - 显式声明pytest-asyncio为开发依赖
不要依赖传递依赖安装测试核心插件,直接在pyproject.toml的dev-dependencies配置块中添加pytest-asyncio = "^0.19.0",本地执行poetry lock --no-update更新锁文件后一并提交到仓库,从根源消除隐式依赖带来的本地与CI环境差异。 - 检查pytest配置与测试用例标记
确认pyproject.toml中的pytest配置没有禁用asyncio插件,同时检查异步测试用例是否添加了@pytest.mark.asyncio装饰器。如果不想给每个异步测试手动加标记,可以直接在配置中开启自动检测规则:[tool.pytest.ini_options] asyncio_mode = "auto" - 排查CI虚拟环境路径与缓存问题
如果前面几步都没有解决问题,就检查CI是否使用了错误的虚拟环境路径,或者加载了旧的缓存站点包。在CI执行测试前运行poetry env info命令,确认当前运行pytest的虚拟环境和依赖安装的目标路径一致,必要时清空CI中的旧依赖缓存,全量重装依赖后再运行测试。
这类本地运行正常、CI执行报错的问题,90%都是隐式依赖导致的环境差异:本地安装的pytest-aiohttp版本刚好附带pytest-asyncio传递依赖,但CI安装时因为锁文件不一致、软件源版本差异漏装了该包,显式声明依赖基本可以直接解决问题。
内容的提问来源于stack exchange,提问作者Daniele Tentoni
相关产品推荐
相关产品推荐

