pytest前后置处理有2种方法
一、通过setup/teardown实现
添加setup和teardown方法,作用于每个方法执行前后
添加setup_class/teardown_class方法,作用于每个类执行前后
import pytest
class Test_C():
def setup(self): # 方法前置
print('\n-----函数开始-----', end='')
def teardown(self): # 方法后置
print('\n-----函数结束-----', end='')
def setup_class(self): # 类前置
print('\n-----类开始-----', end='')
def teardown_class(self): # 类后置
print('\n-----类结束-----', end='')
def test_f01(self):
assert 1 == 1
def test_f02(self):
assert 2 == 2
if __name__ == '__main__':
pytest.main(['test_fixture.py', '-sv'])
运行结果为
二、通过fixture装饰器实现
1、用法:@pytest.fixture(scope=’’, params=’’, autouse=’’, ids=’’, name=’’)
scope:表示被@pytest.fixture标记的级别(值为 function, class, ……)
params:参数化,支持列表[],元组(),字典列表[{},{}],字典元组({},{})
autouse=True:自动使用,默认值为False
ids:当使用params参数化时,给每个值设置一个变量名
name:表示给被@pytest.fixture标记的函数名取一个别名
2、示例:
import pytest
# 声明以下函数(fun)是setup/teardown函数,作用于方法,并自动使用
@pytest.fixture(scope='function', autouse=True)
def fun():
print('\n-----测试开始-----')
yield
print('\n-----测试结束-----')
class Test_C():
def test_f01(self):
assert 1 == 1
def test_f02(self):
assert 2 == 2
if __name__ == '__main__':
pytest.main(['test_fixture.py', '-sv'])
运行结果为
3、如果想指定前后置作用于某个方法,则去掉autouse=True,并在指定方法中传入前后置函数
import pytest
# 声明以下函数(fun)是setup/teardown函数,作用于方法,不自动使用
@pytest.fixture(scope='function')
def fun():
print('\n-----测试开始-----')
yield
print('\n-----测试结束-----')
class Test_C01():
def test_f01(self):
assert 1 == 1
def test_f02(self,fun): # 该方法中传了前后置函数(fun),作用于该方法(test_f02)
assert 2 == 2
if __name__ == '__main__':
pytest.main(['test_fixture.py', '-sv'])
运行结果为:
结果和预期一致,前后置只作用于了指定方法 test_f02。
4、前后置方法只作用于类的话,直接改scope参数即可
import pytest
# 声明以下函数是setup/teardown函数,作用于类,并自动使用
@pytest.fixture(scope='class', autouse=True)
def fun():
print('\n-----测试开始-----')
yield
print('\n-----测试结束-----')
class Test_C01():
def test_f01(self):
assert 1 == 1
def test_f02(self):
assert 2 == 2
class Test_C02():
def test_f03(self):
assert 3 == 3
if __name__ == '__main__':
pytest.main(['test_fixture.py', '-sv'])
运行结果为:
结果和预期一致,前后置作用于了每个类。