pytest内建fixture request

request fixture 提供了很多方法和属性,例如:

  • request.node: 当前测试的节点对象,通常是一个 Function 或 Item 对象。
  • request.function: 当前测试函数。
  • request.cls: 当前测试类(如果测试是一个方法)。
  • request.config: 当前 pytest 配置对象。
  • request.fixturenames: 一个列表,包含当前测试需要的所有 fixture 名称。
  • request.param: 如果测试是通过 @pytest.mark.parametrize 装饰器参数化的,这个属性会包含当前测试的参数值。
  • request.session: 当前 pytest 会话对象。
class TestA:
    def test_fix(self, request):
        print(request.node)
        print(request.function)
        print(request.cls)
        print(request.config)
        print(request.fixturenames)
        # print(request.param) 需要结合参数化来使用
        print(request.session)

request.param使用举例

import pytest


# 定义一个接受参数的 fixture,它使用 request.param 来获取参数值  
@pytest.fixture
def example_fixture(request): 
    # 根据 param 执行一些设置或计算  
    return request.param * 2  # 假设我们将参数值翻倍并返回  


# 使用 @pytest.mark.parametrize 和 indirect=True 来间接参数化 fixture  
@pytest.mark.parametrize("example_fixture", [1, 2, 3], indirect=True)
def test_example(example_fixture):
    # 在这里,example_fixture 的值是由 fixture 返回的,并且是 request.param 的两倍  
    assert isinstance(example_fixture, int)
    assert example_fixture % 2 == 0  # 断言 example_fixture 是偶数
import pytest


# 使用 params 参数直接参数化 fixture
@pytest.fixture(params=[1, 2, 3])
def example_fixture(request):
    # request.param 将包含 params 列表中的当前值
    return request.param * 2


def test_example(example_fixture):
    # 在这里,my_fixture 的值将分别是 2, 4, 6(因为 params 是 [1, 2, 3],且每个值都乘以了 2)
    assert example_fixture % 2 == 0  # 断言 my_fixture 是偶数

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值