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

如何解决PyTest的Pytester无法复用pytest-asyncio插件的问题?

问题描述

用PyTest 7.3.1 + Python3.8测试仓库里依赖pytest-asyncio的fixture,测试函数分在不同模块:

  • 第一次跑测试正常
  • 第二次不管先跑哪个,必出插件加载问题:
    • 先跑test_fixture1,test_fixture2会报fixture2从未被等待的警告
    • 先跑test_fixture2,test_fixture1找不到event_loop fixture

相关代码如下:

conftest.py

from pytest import fixture

@fixture(scope="session")
def fixture1(
    event_loop,  # 依赖pytest_asyncio的隐式fixture
):
    return event_loop

@fixture(scope="session", autouse=True)
async def fixture2():
    pass

test_fixture1.py

def test_fixture1(pytester):
    pytester.makepyfile(
        """\
        from conftest import fixture1

        def test_simple(event_loop, fixture1):
            assert event_loop is fixture1
        """
    )
    result = pytester.runpytest()

test_fixture2.py

def test_fixture2(pytester):
    pytester.makepyfile(
        """\
        from conftest import fixture2

        def test_simple():
            pass
        """
    )
    result = pytester.runpytest()

试过在runpytest里显式加插件,但pytester环境还是识别不了。

解决办法

1. 给pytester的每次运行强制加pytest-asyncio插件

pytester的隔离环境不会自动继承主环境的插件配置,必须每次运行都明确指定加载:

方法1:调用runpytest时传参数

直接修改两个测试模块里的runpytest调用,加上-p pytest_asyncio:

# test_fixture1.py改完后
def test_fixture1(pytester):
    pytester.makepyfile(
        """\
        from conftest import fixture1

        def test_simple(event_loop, fixture1):
            assert event_loop is fixture1
        """
    )
    result = pytester.runpytest("-p", "pytest_asyncio")
# test_fixture2.py改完后
def test_fixture2(pytester):
    pytester.makepyfile(
        """\
        from conftest import fixture2

        def test_simple():
            pass
        """
    )
    result = pytester.runpytest("-p", "pytest_asyncio")

方法2:在pytester环境里加pytest配置文件

每个测试函数开头加一段创建pytest.ini的代码,让环境默认加载插件:

# 放在每个测试函数的makepyfile前面
pytester.makeini("""
[pytest]
addopts = -p pytest_asyncio
""")

2. 解决async fixture的调度问题

fixture2是async类型的fixture,哪怕是autouse的,也需要pytest-asyncio来处理异步调度,没加载插件的话就会出现“未被等待”的警告,所以上面的插件加载是必须的。

3. 彻底隔离测试环境

pytester的缓存清理可能没处理干净插件的全局状态,用pytester.isolate()强制隔离每个测试的环境:

def test_fixture1(pytester):
    with pytester.isolate():
        pytester.makepyfile(...)
        result = pytester.runpytest("-p", "pytest_asyncio")

4. 检查版本兼容性

确保pytest-asyncio版本和PyTest 7.3.1匹配,直接装适配的版本:

pip install pytest-asyncio>=0.21.0

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 14:24:52