使用测试固件的三种方式
方式1:在测试函数里通过参数,指定要使用的测试固件。
方式2:在测试函数里通过装饰器pytest.mark.usefixtures,声明要使用的测试固件。
conftest.py
import pytest
@pytest.fixture(name = "lg")
def login():
print('登录系统')
test_1.py
import pytest
@pytest.mark.usefixtures("lg")
def test_1():
方式3:将测试固件装饰器pytest.fixture的参数autouse设为True,测试函数会自动使用该测试固件。
conftest.py
import pytest @pytest.fixture(name='lg', autouse=True) def login(): print('登录系统')
test_1.py
def test_1():
print('测试test1')
三、多个测试固件的执行顺序
1、测试用例可以通过参数使用测试固件,测试固件也可以通过参数使用其他测试固件。按照传参顺序执行,此例:先执行fix1(),然后执行fix2(),最后执行test_1()。
import pytest
@pytest.fixture()
def fix1():
print('fix1')
@pytest.fixture()
def fix2(fix1):
print('fix2')
def test_1(fix2):
print('执行测试1')
2、测试用例可以调用多个测试固件,如果它们的作用域相同,则按照传参顺序执行;如果它们的作用域不同,则按照作用域级别,从高到低执行。此例:先执行fix2(),然后执行fix1(),最后执行test_1()。
import pytest
@pytest.fixture()
def fix1():
print('fix1')
@pytest.fixture(scope='module')
def fix2():
print('fix2')
def test_1(fix1, fix2):
print('执行测试1')
3、如果使用autouse参数,测试用例自动调用测试固件。作用域相同时,按函数名的编码从小到大执行;作用域不同时,按作用域的级别从高到低执行。此例:先执行fix1(),然后执行fix2(),最后执行test_1()。
import pytest
@pytest.fixture(autouse=True)
def fix2():
print('fixc')
@pytest.fixture(autouse=True)
def fix1():
print('fixb')
def test_1():
print('执行测试1')