在 pytest 文档中的以下示例中:
该函数setup_function应该为其他一些函数设置一些数据,比如test_data。所以如果我编写函数,test_data我将不得不setup_function像这样调用:
def test_data():
setup_function(....)
<Test logic here>
teardown_function(....)
Run Code Online (Sandbox Code Playgroud)
所以唯一的区别是名称约定?
我不明白究竟是如何帮助我创建设置数据的。我可以像这样编写相同的代码:
def test_data():
my_own_setup_function(....)
<Test logic here>
my_own_teardown_function(....)
Run Code Online (Sandbox Code Playgroud)
由于没有办法告诉 pytest 自动将设置函数链接到测试函数,它会为其创建设置数据 -如果我不需要函数指针function,函数的参数setup_function并没有真正帮助我......所以为什么要无缘无故地创建名称约定?
据我所知,setup 函数参数function仅在我需要使用函数指针时对我有帮助——这是我很少需要的。
Leo*_*eon 15
如果您想为一个或多个测试设置细节,您可以使用“普通”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
Run Code Online (Sandbox Code Playgroud)
要记住的是,yield 之前的所有操作都在测试之前运行,yield 之后的所有操作都在测试之后运行。
tests/unit/test_test.py::test_stuff
setting up
FAILED
tearing down
Run Code Online (Sandbox Code Playgroud)
回答
看来您的问题归结为:pytest 文档中描述的setup_function和的目的/好处是什么?teardown_function
使用这些函数的好处是您不必调用它们;都setup_function和teardown_function将前和(分别)在每次试验后自动运行。
关于必须传递函数指针的观点,这在 pytest>=3.0 中不是必需的。从文档:
从 pytest-3.0 开始,函数参数是可选的。
所以你不需要将函数指针传递给setup_function和teardown_function函数;您可以简单地将它们添加到下面示例中所述的测试文件中,然后它们将被执行。
例子
例如,如果您有一个如下所示的test_setup_teardown.py文件:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def setup_function():
print('setting up')
def test_1():
print('test 1')
assert 1 == 2
def teardown_function():
print('tearing down')
Run Code Online (Sandbox Code Playgroud)
并且您使用 pytest(类似pytest test_setup_teardown.py)运行该文件,pytest 将输出:
---- Captured stdout setup ----
setting up
---- Captured stdout call ----
test 1
---- Captured stdout teardown ----
tearing down
Run Code Online (Sandbox Code Playgroud)
换句话说,pytest 自动调用setup_function,然后运行测试(失败),然后运行teardown_function. 这些函数的好处是能够指定运行所有测试之前和之后发生的事情。