使用 pytest 有一种方法可以单独在特定的测试函数/方法上运行清理代码。我知道我们可以这样做来运行每个测试函数。但在这里我想放置一些特定于单个测试函数的清理逻辑。
我可以把清理代码放在测试的最后。但如果测试失败,则不会进行清理。
请您参考如下方法:
使用您的清理代码创建一个 fixture ,并通过将 fixture 用作测试的参数或通过使用 pytest.mark.usefixtures 显式标记测试,将其仅注入(inject)到一个测试中装饰器。
import pytest
@pytest.fixture
def my_cleanup_fixture():
# Startup code
...
yield
# Cleanup code
...
@pytest.mark.usefixtures('my_cleanup_fixture')
def test_with_special_cleanup():
pass
my_cleanup_fixture 默认具有 function 作用域,因此启动和清理代码将为它注入(inject)的每个函数运行。
