一、pytest封装测试类
文件命名:以test_开头
测试类命名:以Test_开头
测试用例命名:以test_开头
二、前置/后置方法
前置方法:
setup
放在类外只对类外方法有效,每条测试方法执行前都执行一次,在setup_function后执行。放在类内只对类内方法有效,每条测试用例执行前都执行一次,在setup_method后执行。
setup_function
放在类外对类外测试方法有效,每条测试方法执行前都执行一次,在setup前执行。放在类内无效。
setup_method
放在类内对类内测试方法生效,每条测试方法执行前都执行一次,在setup前执行。放在类外无效。
setup_class
放在类内对类内测试方法生效,类内所有测试方法执行前执行一次,在setup/setup_function/setup_method前执行。放在类外无效。
setup_model
放类中无效,放类外且类外有函数用例或类内有函数用例时才生效,整个.py模块开始前和结束后各调用一次。
后置方法:
teardown
teardown_function
teardown_method
teardown_class
teardown_model
三、测试用例执行顺序控制
import pytest-ordering
在测试用例前添加装饰@pytest.mark.run(order=XX)
import pytest
class TestOrder:
@pytest.mark.run(order=3)
def test_case1(self):
print('test_case1')
@pytest.mark.run(order=1)
def test_case2(self):
print('test_case2')
@pytest.mark.run(order=2)
def test_case3(self):
print('test_case3')
if __name__=="__main__":
pytest.main(["-s","test_practice.py"])
四、测试用例跳过
1.直接跳过
测试方法前直接加:@pytest.mark.skip(“说明”)
2.条件跳过
设置条件:
例如: condition1 = '冒烟'
测试类前加条件,对该文件所有测试类生效。
测试类中加条件,仅对该测试类生效。
条件使用:
@pytest.mark.skipif(condition1 == '冒烟', reason='smoketest')
def test_case1(self):
print('test_case1')
说明:当condition1 == '冒烟'判定成功,test_case1跳过不执行。
3.样例代码
import pytest
condition1='class外部'
class TestSkip1:
condition2='class内部'
@pytest.mark.skip('直接跳过test_case1')
def test_case1(self):
print('test_case1')
@pytest.mark.skipif(condition1 == 'class外部', reason='外部条件class1内部生效')
def test_case2(self):
print('test_case2')
@pytest.mark.skipif(condition2 == 'class内部', reason='class1内部条件class1内部生效')
def test_case3(self):
print('test_case3')
def test_case4(self):
print('test_case4')
#内部标签整个模块内生效
class TestSkip2:
@pytest.mark.skipif(condition1 == 'class外部', reason='外部条件class2内部生效')
def test_case5(self):
print('test_case5')
@pytest.mark.skipif(condition1 == 'class外部', reason='外部条件外部方法生效')
def test_case6(self):
print('test_case6')
#内部标签外部不生效
# @pytest.mark.skipif(condition2 == 'class内部', reason='class1内部条件外部无法使用')
# def test_case7(self):
# print('test_case7')
if __name__=="__main__":
pytest.main(["-rs","test_practice.py"])
五、测试用例标签:
1.在pytest.ini文件中声明标签
[pytest] # 固定的section名
markers= # 固定的option名称
标签名1: 标签名的说明内容。
标签名2
标签名N
2.给测试用例加标签
方式一:@pytest.mark.已注册标签名
一个用例可以添加多个标签
方式二:pytestmark = [pytest.mark.已注册标签名]
可以加多个pytestmark = [pytest.mark.已注册标签名1,pytest.mark.已注册标签名2]
在类里面使用声明类内所有用例都会标记。
在模块(文件)里面标记,该文件所有用例都会打上该该标记。
3.使用标签过滤执行
pytest -m "Label" 路径或者文件
4.样例代码
import pytest
@pytest.mark.classLabel('classLabel')
class TestLabel1:
@pytest.mark.Label1('label1')
def test_case1(self):
print('test_case1')
@pytest.mark.Label2('label2')
def test_case2(self):
print('test_case2')
@pytest.mark.Label3('label3')
def test_case3(self):
print('test_case3')
@pytest.mark.Label