在 pytest 文档的以下示例中:
函数setup_function
应该为其他函数设置一些数据,比如test_data
。因此,如果我编写函数 test_data
,我将必须像这样调用 setup_function
:
def test_data():
setup_function(....)
<Test logic here>
teardown_function(....)
那么唯一的区别是名称约定?
我不明白它到底是如何帮助我创 build 置数据的。我可以编写相同的代码,如下所示:
def test_data():
my_own_setup_function(....)
<Test logic here>
my_own_teardown_function(....)
由于无法告诉 pytest 自动将设置函数链接到测试函数,因此它会为其创 build 置数据 - 函数 setup_function
的参数 function
不会如果我不需要函数指针,那对我并没有真正的帮助......那么为什么要无缘无故地创建名称约定呢?
据我了解,设置函数参数 function
仅在我需要使用函数指针时才对我有帮助 - 这是我很少需要的东西。
最佳答案
如果您想为一个或多个测试设置细节,您可以使用“普通”pytext 固定装置。
import pytest
@pytest.fixture
def setup_and_teardown_for_stuff():
print("\nsetting up")
yield
print("\ntearing down")
def test_stuff(setup_and_teardown_for_stuff):
assert 1 == 2
要记住的是,yield 之前的所有操作都在测试之前运行,yield 之后的所有操作都在测试之后运行。
tests/unit/test_test.py::test_stuff
setting up
FAILED
tearing down
关于python - Pytest 设置和拆卸函数 - 与自己编写的函数相同吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51984719/