[英]Pytest - how to link a specific setup and teardown functions to a specific test function?
[英]Pytest setup and teardown functions - same as self written functions?
在 pytest 文档中的以下示例中:
函数setup_function
应该为其他一些函数设置一些数据,比如test_data
。 因此,如果我编写函数test_data
我将不得不像这样调用setup_function
:
def test_data():
setup_function(....)
<Test logic here>
teardown_function(....)
所以唯一的区别是名称约定?
我不明白究竟是如何帮助我创建设置数据的。 我可以像这样编写相同的代码:
def test_data():
my_own_setup_function(....)
<Test logic here>
my_own_teardown_function(....)
由于无法告诉 pytest 自动将设置函数链接到测试函数,它会为其创建设置数据 - 如果我不需要函数指针,函数setup_function
的参数function
并没有真正帮助我...... . 那么为什么要无缘无故地创建命名约定呢?
据我了解,设置函数参数function
仅在我需要使用函数指针时对我有帮助——这是我很少需要的。
回答
看来您的问题归结为: 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')
并且您使用 pytest 运行该文件(类似于pytest test_setup_teardown.py
),pytest 将输出:
---- Captured stdout setup ----
setting up
---- Captured stdout call ----
test 1
---- Captured stdout teardown ----
tearing down
换句话说,pytest 自动调用setup_function
,然后运行测试(失败),然后运行teardown_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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.