Skip to main content
 首页 » 编程设计

python之pytest中fixture的重复使用

2024年10月01日16zlslch

我正在学习 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) 

在这个例子中,foo() fixture 被使用了两次,一次被 foobar() 使用,另一次被 foobaz() 使用。如果我为单个测试多次重复使用同一个 fixture ,是否会调用一次 fixture 函数并缓存其结果?或者每次使用它时都会调用它?在我设计的例子中,返回值是静态的,所以没有问题。我可以想象返回值更加动态的许多情况,我需要保证在所有使用它的地方都有完全相同的实例。

请您参考如下方法:

pytest fixture 的生命周期可以通过 scope 参数来控制。基本上有四个作用域 function, class, module, session。默认范围是 function,这是您的设备正在使用的范围。

在 function 范围的情况下,将为每个使用 fixture 的测试函数调用 fixture 。

class 作用域 fixture 在整个测试周期中每个测试类被调用一次,module 作用域 fixture 也是如此(每个测试模块一次)。

session 范围内的 fixture 在每个测试 session 中被调用一次。

可获得更多适用于不同范围的阅读 Material 和示例 fixtures和 fixture function