pytest-用例跳过skip以及预期xfail
前言
当有一些测试用例因为知道肯定是fail掉的,或者还未写完。这时候要执行除它之外的所有测试用例,那么我们就可以选择跳过该用例,pytest同样提供了修饰器(pytest.mark.skip)帮助跳过选定的测试用例
skip修饰器
修饰器:@pytest.mark.skip
无条件跳过用例,在需要跳过的测试用例或者测试类上添加,即可对该测试用例或者测试类进行跳过
测试用例跳过示例代码:
import pytest class Test_01: @pytest.mark.skip def test_01(self): print('跳过的测试用例') def test_02(self): print('用例二执行')
输出:
test_01测试用例添加skip修饰器后,执行被跳过,test_02正常执行
测试类跳过示例代码:
import pytest @pytest.mark.skip class Test_01: def test_01(self): print('跳过的测试用例') def test_02(self): print('用例二执行') def test_03(): print('类外用例三')
输出结果:
可以看到Test_01测试类中的测试用例均被跳过,但类外用例test_03仍旧正常执行
同时skip也提供了reason参数,可以对跳过的用例进行补充说明详细信息,以及跳过原因
reason参数添加备注示例代码:
import pytest class Test_01: @pytest.mark.skip(reason='该用例因fail跳过') def test_01(self): print('跳过的测试用例') def test_02(self): print('用例二执行') def test_03(): print('类外用例三')
输出结果:
pytest.skip也可以加在测试函数内进行跳过,例如登陆时,如果有账号没有在数据库中,那我们也可以直接跳过该用例,不执行该测试用例
pytest.skip示例代码:
import pytest data = [{'usr':'admin','pwd':'1111'}, {'usr':'root','pwd':'1234'}] @pytest.fixture(params=data) def login(request): yield request.param class Test_01: def test_01(self,login): if login['usr'] == 'admin' and login['pwd']=='1111': print('用户名存在数据库') print('执行登陆操作') else: pytest.skip(f'用户名{login["usr"]}不在数据库中')
输出结果:
skipif装饰器
pytest同时也支持条件判断跳过,pytest.mark.skipif(condition,reason='跳过原因'),condition为跳过条件,为True就跳过
注意:skipif必须要带上跳过的详细信息,要不然会报错
import pytest class Test_01: @pytest.mark.skipif(1==1,reason='满足跳过条件此用例跳过') def test_01(self): print('用例一执行') def test_02(self): print('用例二执行')
输出结果:
测试用例test_01满足跳过条件,所以执行跳过,并打印跳过原因
同时skipif也支持设置在测试类上,满足跳过条件,测试类下所有用例均跳过
skipif测试类跳过实力代码:
import pytest @pytest.mark.skipif(1==1,reason='满足跳过条件此用例跳过') class Test_01: def test_01(self): print('跳过的测试用例') def test_02(self): print('用例二执行') def test_03(): print('类外用例三')
输出结果:
xfail装饰器
当一个用例运行不太稳定,但不想跳过,仍需进行执行时,可以使用xfail,表示预期执行结果是fail,不会影响其余测试用例的执行,如果用例执行成功,那么打印的结果是xpass,如果执行失败,则打印xfail,同样可以用reason进行
xfail示例代码:
import pytest import random class Test_01: @pytest.mark.xfail(reason='不稳定') def test_01(self): print('用例一执行') assert random.randint(0,2) == 1 def test_02(self): print('用例二执行') def test_03(): print('类外用例三')
输出结果:
多次运行,可以看到当随机到1时,该测试用例结果为xpass,当随机到其他数值时,会显示结果xfail,而不是直接报error
以上就是pytest中能够跳过测试用例的装饰器,在项目中,可以根据自己的需求来选择对应的装饰器使用