其他分享
首页 > 其他分享> > pytest 失败重试

pytest 失败重试

作者:互联网

1、介绍

当部分用例因为一些偶然因素运行失败时,可以使用失败重试机制,比如在平时在做接口测试的时候,经常会遇到网络抖动或者环境问题导致测试用例运行失败,而这个并不是我们想要的结果,我们想要重新运行失败的测试用例,这个就需要通过插件pytest-rerunfailures来实现了。

2、安装失败重试插件

pip install pytest-rerunfailures


3、使用

3.1、使用@pytest.mark.flaky()完成重试

场景:定位百度搜索按钮,xpath值错误时,会导致定位不到,会重复运行

@pytest.mark.flaky(rerun=1) # 失败重试后立即重跑一次
@pytest.mark.flaky(retun=1,runs_delay=2) # 失败重跑一次,在每次重试前都会等2s
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/4/15 4:05 下午
# @Author : Maynard
# @File : test_09rerunfailures.py
# @Software: PyCharm


import pytest
from selenium import webdriver


class TestBaidu():
def setup(self):
path = r'/Users/lafei/Downloads/chromedriver'
self.driver = webdriver.Chrome(executable_path=path)
self.driver.get('https://www.baidu.com')


# @pytest.mark.flaky(rerun=1) # 失败重试后立即重跑一次
@pytest.mark.flaky(retun=1,runs_delay=2) # 失败重跑一次,在每次重试前都会等2s
def test_baidu(self):
self.driver.find_element_by_xpath("//input[@id='kw']").send_keys('拉菲学测试')
# 如下代码"//input[@id='zu']" 定位特意写错,使得运行失败,正确定位为id='su'
self.driver.find_element_by_xpath("//input[@id='zu']").click()


if __name__ == '__main__':
pytest.main(['-s','test_09rerunfailures.py'])


运行结果:由于22行代码错误导致定位不到,所以在失败后2s后rerun一次

 

3.2、使用命令行完成重试

运行前记得把上面18行代码屏蔽,使用命令行完成重试

pytest test_09rerunfailures.py --reruns 3 --reruns-delay 2
# 重试最大次数为3次,每次失败后重试时间间隔2秒
运行结果:3次rerun

 

3.3、在main.py中完成重试

if __name__ == '__main__':
pytest.main(
[
'-s',
'test_09rerunfailures.py',
'--reruns=1', # 重试一次
'--reruns-delay=2' # 重试间隔时间为2s
]
)

4、总结

超过最大次数,则报异常;

reruns为次数,reruns_delay为间隔时间;

main函数运行前记得在参数前加上--,比如--reruns;

原文链接:https://blog.csdn.net/m0_47127594/article/details/115775126

标签:__,reruns,重试,pytest,失败,main
来源: https://www.cnblogs.com/superbaby11/p/16123695.html