17、pytest自动使用fixture

官方实例

# content of test_autouse_fixture.py
import pytest@pytest.fixture
def first_entry():return "a"@pytest.fixture
def order():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]

解读与实操

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

我们可以通过向fixture的装饰器传递autouse=True来使fixture成为autouse fixture。

在这个例子中,append_first fixture是一个自定义fixture,因为它是自动请求的,所有两个测试都受到它的影响,即使两个测试都没有请求它。

在这里插入图片描述

场景应用

需要在某个模块或某个类上,整体加个延时操作时,可以使用一个autouse fixture。