python - 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
仅在我需要使用函数指针时对我有帮助——这是我很少需要的。
解决方案
如果你想为一个或多个测试设置细节,你可以使用“普通”的 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
推荐阅读
- sql-server - 在 SQL Server 中使用计数
- r - R:使用零宽度前瞻提取二元组
- python-3.x - 从目录及其所有子目录中移出所有文件
- html - 顶部菜单的边距移动内容
- c++ - 新字符 [] 的 C++ 问题
- arm64 - ldp指令的速度是否取决于缓存?
- testrail - 如何使用测试用例 ID(TestRail Java 客户端)批量更新测试运行结果?
- php - Mockery::mock 与 createMock
- c - C 字符串问题。输入整数 N 和字符串,我想在第 N 个位置打印出字符。(如果 N>strlen(str))
- netbeans - 8.2版本的困难