python - Pytest 设置和拆卸函数 - 与自己编写的函数相同吗?

标签 python pytest

在 pytest 文档的以下示例中:

enter image description here

函数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/

相关文章:

python - 美丽汤 : How to grab the contents of an <a> tag thats within a <h1>?

Python 3 'else' 在这个循环中如何工作

python - PyCharm 重复 py.test 测试断言

python - VSCode Python 测试发现失败(2018 年 6 月)

pytest - 如何将测试标记为 "long"并跳过它们?

python - 如何为数据类实现 pytest.approx()

python - 如何使用数组制作 GIF

python - SQLAlchemy 中的条件添加语句

python - 获取当前类(class)的名称?

python - pytest 时禁用每个测试 "dots"