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

使用pytest-asyncio时类级fixture出现ScopeMismatch错误求助

解决pytest异步类作用域Fixture的ScopeMismatch错误

错误原因

你遇到的ScopeMismatch是因为类作用域的异步fixture依赖了函数作用域的event_loop。pytest-asyncio默认提供的event_loop fixture是函数级别的,而你的setup_teardown是类级别的——pytest不允许作用域大的fixture依赖作用域小的fixture,因此触发了这个错误。

解决方案

自定义一个类作用域的event_loop fixture,让它和你的setup_teardown fixture作用域匹配,就能解决冲突。

完整可运行代码

import asyncio
import pytest
from pytest_asyncio import EventLoopFixture


# 自定义类作用域的事件循环fixture
@pytest.fixture(scope="class")
def event_loop(request) -> EventLoopFixture:
    loop = asyncio.new_event_loop()
    yield loop
    # 测试类结束后关闭事件循环
    loop.close()


# 类作用域的初始化fixture
@pytest.fixture(scope="class")
async def setup_teardown(request):
    request.cls.test_number = '123'
    yield
    # 这里可以添加测试类结束后的清理逻辑,比如关闭资源等


@pytest.mark.usefixtures("setup_teardown")
class Test_BaseFunctional():
    # 每个异步测试方法添加asyncio标记
    @pytest.mark.asyncio
    async def test_my_number(self):
        assert self.test_number == '123'

额外简化方案(针对pytest-asyncio 0.21.0+版本)

如果你的pytest-asyncio版本足够新,可以直接给测试类的asyncio标记指定作用域,无需自定义event_loop fixture:

import pytest


@pytest.fixture(scope="class")
async def setup_teardown(request):
    request.cls.test_number = '123'
    yield


@pytest.mark.asyncio(scope="class")
@pytest.mark.usefixtures("setup_teardown")
class Test_BaseFunctional():
    async def test_my_number(self):
        assert self.test_number == '123'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 13:25:20