pytest7-多个fixtures执行顺序

举例:

import pytest

order = []


@pytest.fixture(scope='session')
def s1():
    order.append("s1")


@pytest.fixture(scope='module')
def m1():
    order.append('m1')


@pytest.fixture()
def f1(f3):
    order.append('f1')


@pytest.fixture()
def f3():
    order.append('f3')


@pytest.fixture(autouse=True)
def a1():
    order.append('a1')


@pytest.fixture()
def f2():
    order.append('f2')


def test_order(f1, m1, f2, s1):
    assert order == ["s1", "m1", "a1", "f3", "f1", "f2"]

输出结果:1 passed  #即test_doder.py测试用例通过

理论:

session > module > class > function

@pytest.fixture(scope="session"):多个文件调用一次,可以跨.py,每个.py就是module

@pytest.fixture(scope="module"):module级别的fixture在当前.py模块里,只会在用例第一次调用前执行一次

@pytest.fixture(scope="class"):class级别的fixture,在每个类里,只会在第一次调用前执行一次

@pytest.fixture(scope="function"):function级别,每个函数都会调用(默认)

def fixture(scope="function", params=None, autouse=False, ids=None, name=None):

    :arg scope: the scope for which this fixture is shared, one of
                ``"function"`` (default), ``"class"``, ``"module"``,
                ``"package"`` or ``"session"``.

                ``"package"`` is considered **experimental** at this time.
fixtures.py源码

特别地:平常写自动化用例会写一些前置的fixture操作,用例需要用到就直接传该函数的参数名称就行了。当用例很多的时候,每次都传这个参数,会比较麻烦。
fixture里面有个参数autouse,默认是Fasle没开启的,可以设置为True开启自动使用fixture功能,这样用例就不用每次都去传参了

猜你喜欢

转载自www.cnblogs.com/wang-mengmeng/p/11710135.html