前言
在深入理解 pytest-repeat 插件的工作原理这篇文章中,我们看到pytest_repeat源码中有这样一段
@pytest.fixture
def __pytest_repeat_step_number(request):
marker = request.node.get_closest_marker("repeat")
count = marker and marker.args[0] or request.config.option.count
......
看到参数为request,我们知道fixture装饰的函数入参,只能是其他fixture,所以这里request一定也是fixture。那它到底怎么用呢?这篇文章将详细介绍,并通过实战项目加深理解。
request fixture
The request fixture is a special fixture providing information of the requesting test function.这是pytest官方文档的介绍,意思就是请求fixture是一个特殊的fixture,提供请求测试函数的信息。
源码直达,感兴趣的朋友可以查看源码FixtureRequest
request.node
当前测试用例的节点对象,表示当前执行的测试用例。可以使用该对象获取测试用例的名称、文件路径、测试类等信息。
import pytest
@pytest.fixture
def my_fixture(request):
node = request.node
print(f"Current test case: {node.name}")
print(f"Test file path: {node.fspath}")
print(f"Test class: {node.getparent}")
def test_demo(my_fixture):
pass
输出结果为:
Current test case: test_demo
Test file path: /Users/pxl/test_dir/test_demo.py
Test class: <bound method Node.getparent of <Function test_demo>>
fixture 使用了 request 参数,并通过 request.node 获取了当前测试用例的相关信息。具体来说,我们打印了当前测试用例的名称、文件路径和测试类名称。
request.config
前运行的配置对象,表示当前 Pytest 的配置信息。可以使用该对象获取命令行参数、配置文件设置等信息。
pytest.i

本文详细介绍了 pytest 中的 request fixture,通过实战示例展示了如何利用 request fixture 实现数据库环境的切换,包括配置解析、数据库连接的初始化和清理。文章还探讨了 request fixture 的常见属性和方法,以及如何使用它们来获取测试用例和配置信息。
最低0.47元/天 解锁文章
306

被折叠的 条评论
为什么被折叠?



