微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

跟着节奏继续来探索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,拿到的其实是空列表[],所以最后断言会失败。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐