pytest中fixture的重复使用

Cod*_*ice 6 python fixtures pytest

我正在学习 pytest,特别是它与 xUnit setUp() 和 tearDown() 范例不同的装置。假设我有以下测试:

import pytest


@pytest.fixture()
def foo():
    return 'foo'


@pytest.fixture()
def bar():
    return 'bar'


@pytest.fixture()
def baz():
    return 'baz'


@pytest.fixture()
def foobar(foo, bar):
    return foo + bar


@pytest.fixture()
def foobaz(foo, baz):
    return foo + baz


def test(foobar, foobaz):
    print('test')
    print(foobar)
    print(foobaz)
Run Code Online (Sandbox Code Playgroud)

在这个例子中,foo()fixture 被使用了两次,一次 byfoobar()又一次 by foobaz()。如果我在一次测试中多次重用同一个夹具,夹具函数是否被调用一次并缓存其结果?还是每次使用时都调用它?在我人为的例子中,返回值是静态的,所以没有问题。我可以想象很多情况,其中返回的值更具动态性,我需要保证在任何使用它的地方都有完全相同的实例。

San*_*nju 5

pytest 夹具的寿命可以通过参数来控制scope。基本上有四个范围function, class, module, session。默认范围是function您的灯具正在使用的范围。

在作用域的情况下function,将为使用该夹具的每个测试函数调用该夹具。

在整个测试周期中,每个class测试类调用一次作用域固定装置,因此作用域module固定装置(每个测试模块调用一次)。

session每个测试会话都会调用一次作用域固定装置。

更多关于不同范围的阅读和示例可用于夹具夹具功能