【pytest官方文档】解读fixtures - 4. 一次请求多个fixtures、fixtures被多次请求

本文介绍pytest框架中fixture的高级使用技巧,包括如何在一个测试函数或fixture中请求多个fixture,以及如何在同一测试函数中多次请求同一fixture并利用其缓存特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

跟着节奏继续来探索fixtures的灵活性。

一、一个测试函数/fixture一次请求多个fixture

在测试函数和fixture函数中,每一次并不局限于请求一个fixture。他们想要多少就可以要多少。
下面是另一个简单的例子:

import pytest


# Arrange
@pytest.fixture
def first_entry():
    return "a"


# Arrange
@pytest.fixture
def second_entry():
    return 2


# Arrange
@pytest.fixture
def order(first_entry, second_entry):
    # 这是一个fixture函数,请求了2个其他的fixture函数
    return [first_entry, second_entry]


# Arrange
@pytest.fixture
def expected_list():
    return ["a", 2, 3.0]


def test_string(order, expected_list):
    # 这是一个测试函数,请求了2个不同的fixture函数
    # Act
    order.append(3.0)

    # Assert
    assert order == expected_list

可以看出,在fixture函数order中,请求了2个其他的fixture函数,分别是:first_entrysecond_entry
在测试函数test_string中,请求了2个不同的fixture函数,分别是:orderexpected_list

二、每个测试函数可以多次请求fixtures(返回值被缓存)

在同一个测试函数中,fixture也可以被请求多次。但是在这个测试函数中,pytest在第一次执行fixture函数之后,不会再次执行它们。
如果第一次执行fixture函数有返回值,那么返回值会被缓存起来。

import pytest


# Arrange
@pytest.fixture
def first_entry():
    return "a"


# Arrange
@pytest.fixture
def order():
    return []


# Act
@pytest.fixture
def append_first(order, first_entry):
    # 在这里order第一次被请求,返回一个列表[]
    # 接着,order空列表增加了first_entry的返回值,此时的order变成了["a"],被缓存起来
    return order.append(first_entry)


def test_string_only(append_first, order, first_entry):
    # 在测试函数里,order第二次被请求,但是并不会拿到空列表[],而且拿到了被缓存起来的["a"]
    # 所以断言order == [first_entry],其实就是 ["a"] == ["a"],测试通过
    # Assert
    assert order == [first_entry]

从示例中可以看出:

  1. 在fixture函数append_first中,order第一次被请求,返回一个列表[],被缓存起来。
  2. 接着,order.append(first_entry)[]中增加了first_entry的返回值,所以,此时的order变成了["a"]
  3. 最后,在测试函数test_string_only中,order第二次被请求,但是并不会拿到空列表[],而且拿到了被缓存起来的["a"]
    这样的话,最后的断言assert order == [first_entry]就会成功。

反过来,如果同一个fixture在一个测试函数中每次都去请求一次,那上面的测试函数必然失败。
因为,这样一来,虽然在append_first中的返回值仍然是["a"],但是在test_string_only中,
又去重新请求了一次order,拿到的其实是空列表[],所以最后断言会失败。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值