5.pytest重跑测试用例
自动化一般都会在测试环境或者其他非线上的环境,由于环境的不稳定可能会导致测试用例莫名其妙的失败,是用例的稳定性大打折扣。这个时候加入失败重跑机制,能够在一定范围内提高测试用例的稳定性,做出更多的产出。
接口自动化测试用以建议可以加入这种失败重跑,而对于UI接口接口自动化,失败重跑的话,意义不大,因为往往当用例的失败的时候,要么是由于界面元素没加载出来,要么是用例的逻辑有问题,要么是意外的弹窗影响,这个时候应该让错误尽早的抛出来,好尽快的修复,而不是在哪儿一个劲的重试,没啥用。UI自动化应该做好显式和隐式等待。
pytest-rerunfailures
pytest-rerunfailures是属于pytest的插件,通常用来执行用例失败后重新执行。
安装: pip install pytest-rerunfailures
源码:https://github.com/pytest-dev/pytest-rerunfailures
其中pytest-rerunfailures有2种用法,一种是装饰器的方法,另一种是命令行参数的方法。
装饰器
首先介绍下,如何通过装饰器的方法进行用例失败重跑。
格式: @pytest.mark.flaky(reruns=3, reruns_delay=2)
使用方法和前面介绍的一些基本相似通过pytest.mark的形式加上flakey方法。我们看到其中有2个参数,其中reruns表示失败后执行几次,reruns_delay表示失败后等待几秒后,在重新执行
装饰器的方法不仅可以加到用例上,也可以加入到类上。
装饰器在用例上
import pytest
import random
class Test01:
@pytest.mark.flaky(reruns=3, reruns_delay=2)
def test_01(self):
a = random.randint(0, 3)
print('---用例01---')
print(a)
assert a == 2
def test_02(self):
print('---用例02---')
assert 1 == 1
if __name__ == '__main__':
pytest.main(['-vs'])
通过下图可以看到,我们执行用例1一共执行了3次,第一次设置的随机值为1和断言2不一致,进行重新跑,第2次随机值为0和断言2也不一样,第3次的时候断言相同了,用例通过
装饰器在类上
import pytest
import random
@pytest.mark.flaky(reruns=3, reruns_delay=2)
class Test01:
def test_01(self):
a = random.randint(0, 2)
print('---用例01---')
print('用例01中的a:%s'%a)
assert a == 2
def test_02(self):
c = random.randint(0, 2)
print('---用例02---')
print('用例02中的c:%s'%c)
assert c == 1
if __name__ == '__main__':
pytest.main(['-vs'])
通过下方执行结果可以很清楚的看到,我们class下的用例都进行了失败重跑。
命令行参数
上述方法介绍了如何通过装饰器的方法进行用例失败重跑,下面介绍如何通过命令行的参数进行失败重跑。
格式: pytest --reruns 3 --reruns-delay 2 或 pytest -vs --reruns=3 --reruns-delay=2
参数详解:其中reruns空格3 表示失败重新运行3次,reruns-delay空格2 表示重新执行需要等待2秒。这里也可以使用等于来进行表示
import pytest
import random
class Test01:
def test_01(self):
a = random.randint(0, 2)
print('---用例01---')
print('用例01中的a:%s'%a)
assert a == 2
def test_02(self):
c = random.randint(0, 2)
print('---用例02---')
print('用例02中的c:%s'%c)
assert c == 1
if __name__ == '__main__':
pytest.main(['-vs'])
通过下图执行结果可以看出来,失败重跑已经生效。
注意事项:装饰器的方法和命令行的方法不能一起使用,不然的话会报错!!!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义