首页 > 解决方案 > Pytest 设置和拆卸功能 - 与自写功能相同?

问题描述

在 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 自动将设置函数链接到测试函数,因此它会为其创建设置数据 -如果我不需要函数指针function,该函数的参数并不能真正帮助我......所以setup_function为什么要无缘无故地创建名称约定?

据我了解,setup 函数参数function仅在我需要使用函数指针时对我有帮助——这是我很少需要的。

标签: pythonpytest

解决方案


如果你想为一个或多个测试设置细节,你可以使用“普通”的 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

推荐阅读