阅读(3355) (1)

pytest fixture-自动适配fixture

2022-03-18 13:52:08 更新

有时,您可能希望拥有一个(甚至几个)​​fixture​​,您知道所有的测试都将依赖于它。​​autouse fixture​​是使所有测试自动请求它们的一种方便的方法。这可以减少大量的冗余请求,甚至可以提供更高级的​​fixture​​使用。

我们可以将​​autouse =True​​传递给​​fixture​​的装饰器,从而使一个​​fixture​​成为​​autouse fixture​​。下面是一个如何使用它们的简单例子:

# contents of test_append.py
import pytest


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


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


@pytest.fixture(autouse=True)
def append_first(order, first_entry):
    return order.append(first_entry)


def test_string_only(order, first_entry):
    assert order == [first_entry]


def test_string_and_int(order, first_entry):
    order.append(2)
    assert order == [first_entry, 2]

在本例中,​​append_first fixture​​是一个自动使用的​​fixture​​。因为它是自动发生的,所以两个测试都受到它的影响,即使没有一个测试请求它。但这并不意味着他们不能提出要求,只是说没有必要。