我想在我的测试套件中的每个测试之前和之后运行额外的设置和拆卸检查。我查看了固定装置,但不确定它们是否是正确的方法。我需要在每次测试之前运行设置代码,并且需要在每次测试之后运行拆卸检查。
我的用例是检查没有正确清理的代码:它会留下临时文件。在我的设置中,我将检查文件,在拆解中我还将检查文件。如果有额外的文件,我希望测试失败。
最佳答案
py.test 固定装置是实现您的目的的技术上足够的方法。
你只需要像这样定义一个fixture:
@pytest.fixture(autouse=True)
def run_around_tests():
# Code that will run before your test, for example:
files_before = # ... do something to check the existing files
# A test function will be run at this point
yield
# Code that will run after your test, for example:
files_after = # ... do something to check the existing files
assert files_before == files_after
通过使用 autouse=True
声明您的 fixture ,它将为同一模块中定义的每个测试函数自动调用。
也就是说,有一个警告。在设置/拆卸时断言是一种有争议的做法。我的印象是 py.test 的主要作者不喜欢它(我也不喜欢它,所以这可能会影响我自己的看法),所以你在前进时可能会遇到一些问题或粗糙的边缘。
关于python - 在 py.test 中的每个测试之前和之后运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22627659/