如何使用 pytest 仅为特定测试运行清理代码?

pra*_*pan 7 python pytest

使用 pytest,有一种方法可以单独在特定的测试函数/方法上运行清理代码。我知道我们可以这样做来运行每个测试函数。但在这里我想放置一些特定于单个测试函数的清理逻辑。

我可以在测试结束时放置清理代码。但如果测试失败,则不会进行清理。

Ale*_*ing 6

使用清理代码创建一个固定装置,并通过使用固定装置作为测试的参数或使用装饰器显式标记测试,将其仅注入到一个测试中pytest.mark.usefixtures

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
Run Code Online (Sandbox Code Playgroud)

my_cleanup_fixture默认情况下具有作用域function,因此启动和清理代码将为注入的每个函数运行。