pytest 的 request fixture:实现个性化测试需求

本文详细介绍了 pytest 中的 request fixture,通过实战示例展示了如何利用 request fixture 实现数据库环境的切换,包括配置解析、数据库连接的初始化和清理。文章还探讨了 request fixture 的常见属性和方法,以及如何使用它们来获取测试用例和配置信息。
摘要由CSDN通过智能技术生成

前言

深入理解 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.ini

[pytest]
markers =
    p0: 冒烟
    p1: 功能
  • 15
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值