如何在pytest-asyncio的setup和teardown中使用await?
实现pytest-asyncio的异步类级setup/teardown
你可以通过两种方式实现类级的异步初始化和清理逻辑,适配pytest-asyncio的测试流程:
方式一:使用类级异步Fixture
用pytest_asyncio.fixture定义一个作用域为class的异步fixture,在其中完成初始化和清理,测试类通过usefixtures注入后,所有测试方法可共享这个实例:
import pytest import pytest_asyncio from your_module import ClassUnderTest @pytest_asyncio.fixture(scope="class") async def class_under_test(): # 异步初始化被测类实例 instance = await ClassUnderTest.async_init() yield instance # 异步清理逻辑 await instance.async_cleanup() @pytest.mark.usefixtures("class_under_test") class TestClass: async def test_method1(self, class_under_test): result = await class_under_test.some_async_operation() assert result == expected_result async def test_method2(self, class_under_test): another_result = await class_under_test.another_async_operation() assert another_result is True
方式二:异步类级setup/teardown方法
pytest-asyncio 0.17+版本支持直接在测试类中定义异步的setup_class和teardown_class方法,无需额外装饰,框架会自动异步执行:
import pytest from your_module import ClassUnderTest class TestClass: @classmethod async def setup_class(cls): # 异步初始化类级被测实例 cls.class_under_test = await ClassUnderTest.async_init() @classmethod async def teardown_class(cls): # 异步清理逻辑 await cls.class_under_test.async_cleanup() async def test_method1(self): result = await self.class_under_test.some_async_operation() assert result == expected_result async def test_method2(self): another_result = await self.class_under_test.another_async_operation() assert another_result is True
注意事项
- 确保你的pytest-asyncio版本≥0.17,旧版本不支持异步类级setup/teardown方法
- 测试类中的所有测试方法必须定义为
async def,pytest-asyncio会自动识别并异步执行 - 两种方式都能保证初始化逻辑在所有测试方法执行前仅运行一次,清理逻辑在所有测试方法执行完成后运行一次,符合类级测试的需求
内容的提问来源于stack exchange,提问作者Wör Du Schnaffzig
相关产品推荐
相关产品推荐

