登录
首页 >  文章 >  python教程

Python3.10异步测试教程:pytest-asyncio实战指南

时间:2026-05-29 13:21:58 154浏览 收藏

本文深入解析了在 Python 3.10+ 环境下使用 pytest-asyncio 进行异步测试的关键实践与高频陷阱,直击“协程从未被 await”和“事件循环已关闭”等令人头疼的运行时错误——这些并非代码逻辑错误,而是由事件循环生命周期管理不当、插件版本不兼容、装饰器缺失或 fixture 设计失当所致;文章不仅明确了必须显式添加 `@pytest.mark.asyncio` 装饰器、正确配置 `asyncio_mode="auto"`、合理设计异步 fixture 等硬性规范,还提供了重置 event loop、规避 loop 复用冲突、结合 lint 工具预防疏漏等实战级解决方案,助你构建稳定、可维护的异步测试体系。

如何在Python 3.10以上版本测试异步代码_通过pytest-asyncio插件实现

pytest-asyncio 是目前最主流的异步测试方案,但 Python 3.10+ 的协程行为变化和插件版本兼容性容易导致 RuntimeWarning: coroutine 'test_xxx' was never awaitedEvent loop is closed 这类错误——根本原因不是代码写错了,而是事件循环生命周期没对齐。

确认 pytest-asyncio 版本与 Python 3.10+ 兼容

旧版 pytest-asyncio<0.21.0 在 Python 3.10+ 上默认使用已弃用的 asyncio.get_event_loop(),会触发 DeprecationWarning 甚至崩溃。必须升级:

  • pip install -U pytest-asyncio>=0.21.0(推荐 0.23.0+)
  • 检查是否启用了 asyncio_mode = auto(新版默认),而非过时的 auto 模式需显式配置
  • 如果项目用 pyproject.toml,确保有:
    [tool.pytest.ini_options]
    asyncio_mode = "auto"

给 async 测试函数加 @pytest.mark.asyncio 装饰器

不加这个标记,pytest 会把 async def test_xxx() 当普通函数执行,协程对象不会被 await,直接报 was never awaited。它不是可选的,是强制的。

  • 正确写法:
    import pytest
    <p>@pytest.mark.asyncio
    async def test_fetch_data():
    result = await some_async_func()
    assert result == "ok"</p>
  • 不能只靠函数名含 async 或文件名带 _async —— pytest 不自动识别
  • 若想全局启用(不加装饰器),可在 pytest.ini 中设 asyncio_mode = auto,但仅对函数名匹配 ^test 且含 async def 生效;实际项目中仍建议显式加 @pytest.mark.asyncio,避免隐式行为出错

避免在 fixture 中混用 sync/async 初始化逻辑

常见陷阱:用 @pytest.fixture 定义一个返回协程对象的 fixture,但没用 @pytest.fixturescope="function" + autouse=True 组合,或忘了 await 它。

  • 同步 fixture 不能直接调 await
    @pytest.fixture
    def bad_fixture():
        return asyncio.sleep(0.1)  # 返回协程对象,但没 await → 后续用的地方会报错
  • 正确方式是用 @pytest.fixture + async def + @pytest.mark.asyncio(注意:fixture 本身不支持 @pytest.mark.asyncio,得换思路):
    @pytest.fixture
    async def good_fixture():
        return await some_async_setup()
    <p>@pytest.mark.asyncio
    async def test_with_fixture(good_fixture):
    assert await good_fixture == "ready"</p>
  • 更稳妥做法:用 asyncio.run() 包一层(仅限简单场景,因会新建 event loop):
    @pytest.fixture
    def db_client():
        return asyncio.run(setup_db())  # ⚠️ 不推荐用于嵌套 await 场景

处理全局 event loop 关闭导致的 RuntimeError

Python 3.10+ 默认在主线程 exit 时关闭 event loop,而 pytest 的多个 test session 可能复用 loop,引发 RuntimeError: Event loop is closed

  • conftest.py 中重置 loop(推荐):
    import asyncio
    import pytest
    <p>@pytest.fixture(autouse=True)
    def reset_event_loop():
    asyncio.set_event_loop(asyncio.new_event_loop())</p>
  • 或者禁用 pytest 的 loop 复用(较重):pytest --asyncio-mode=strict,此时每个 test 都新建 loop
  • 如果测试中手动调了 asyncio.get_event_loop().close(),务必确认这是必要操作——多数情况下不该主动 close

最易被忽略的是:即使所有测试都标了 @pytest.mark.asyncio,只要有一个测试函数里漏了 await 某个协程调用,整个 session 的 event loop 就可能提前终止,后续测试全挂。建议用 pytest-asyncio--asyncio-mode=auto 配合严格 lint(如 pylintunnecessary-awaitmissing-await 规则)来兜底。

今天关于《Python3.10异步测试教程:pytest-asyncio实战指南》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>