Pytest 支持 classical xunit style setup and teardown在模块/类/方法/函数级别(除了 pytests dependency injection mechanism )。功能级别setup and teardown functions are invoked for every test function在模块中。如何为特定测试功能定义设置和拆卸功能?
最佳答案
import pytest
@pytest.fixture
def resource():
resource = foo()
yield resource
resource.cleanup()
def test_feature(resource):
assert bar(resource) == 27
使用 fixture 进行设置和清理是比
try...finally
更好的方法在问题评论中建议,即使没有代码重用目标:您的单个测试专注于断言适当的条件,而不是资源清理。
关于python - 如何在 pytest 中为特定方法或函数定义设置和拆卸函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46562835/