当pytest要执行一个测试函数,这个测试函数还请求了fixture函数,那么这时候pytest就要先确定fixture的执行顺序了。
影响因素有三:
scope,就是fixture函数的作用范围,比如scope='class'。dependencies,可能会存在fixture请求了别的fixture,所以产生了依赖关系,也要考虑进去。autouse,如果autouse=True,那么在作用范围内,这个fixture是最先调用的。
所以,像fixture函数或测试函数的名称、定义的位置、定义的顺序以及请求fixture的顺序,除了巧合之外,对执行顺序没有任何影响。
对于这些巧合情况,虽然pytest会尽力保持每次运行的顺序都一样,但是也难免会有意外。所以,如果我们想控制好顺序,最安全的方法还是
依赖上述三点,并且要弄清依赖关系。
一、使用范围更大的fixture函数优先执行
更大范围(比如session)的fixture会在小范围(比如函数或类)之前执行。
代码示例:
import pytest
@pytest.fixture(scope="session")
def order():
return []
@pytest.fixture
def func(order):
order.append("function")
@pytest.fixture(scope="class")
def cls(order):
order.append("class")
@pytest.fixture(scope="module")
def mod(order):
order.append("module")
@pytest.fixture(scope="package")
def pack(order):
order.append("package")
@pytest.fixture(scope="session")
def sess(order):
order.append("session")
class TestClass:
def test_order(self, func, cls, mod, pack, sess, order):
assert order == ["session", "package", "module", "class", "function"]
运行结果:
test_module1.py . [100%]
============================== 1 passed in 0.01s ==============================
Process finished with exit code 0
既然运行通过,那么这些fixture函数的运行顺序就是列表里的顺序["session", "package", "module", "

最低0.47元/天 解锁文章
695

被折叠的 条评论
为什么被折叠?



