升级pytest-asyncio至0.23.2遇类作用域事件循环错误求助
问题原因
pytest-asyncio 0.23.x版本新增了事件循环作用域自动推断逻辑:当测试模块中存在类作用域的fixture、或类作用域的参数化规则时,会自动将事件循环的作用域设为class。但你的测试模块里有模块级定义的类作用域fixture(比如test_projects_state),再加上conftest.py中通过pytest_generate_tests设置了类作用域的参数化,导致pytest-asyncio误判整个模块需要类作用域的事件循环,可模块本身并非所有代码都属于类(比如模块级的fixture定义),最终触发该错误。
解决方案
以下几种方式可解决该问题:
1. 显式指定事件循环作用域
在conftest.py中添加自定义的event_loop fixture,强制使用类作用域:
import asyncio import pytest_asyncio @pytest_asyncio.fixture(scope="class") def event_loop(): loop = asyncio.new_event_loop() yield loop loop.close()
2. 通过配置文件全局设置
在项目根目录的pytest.ini中添加配置,全局指定事件循环作用域为class:
[pytest] asyncio_event_loop_scope = class
3. 调整fixture定义位置
将模块级的类作用域fixture(比如test_projects_state)移到对应的测试类内部,确保fixture和测试代码同属一个类:
@pytest.mark.usefixtures( "cli", "logged_user", "reset_examples", ) @pytest.mark.random_order(disabled=True) class TestExamples(object): @pytest.fixture(scope="class") def test_projects_state(self, request): """Simple fixture to store tests' state in a class.""" class TestProjectTest(object): def __init__(self): self.project = None request.cls.state = TestProjectTest() async def test_1_post_project( self, some_code: some_type, cli: AsyncClient ): # 测试代码 pass
内容的提问来源于stack exchange,提问作者Koti
相关产品推荐
相关产品推荐

