前言
当服务器不稳定,偶尔出现波动、本地网络偶尔出现不稳定等情况,导致用例执行失败,这种情况大家都觉得用例标记失败不太合理,想要在用例执行失败后延时一些时间再次进行执行,如果超过3次仍然失败,则表明用例执行失败;所以就需要失败重跑功能。
pytest-rerunfailures 安装
- 前提条件:
pytest (>=5.3)
和python >=3.6
- 安装:
pip install pytest-rerunfailures
- 查看安装版本:
pip show pytest-rerunfailures
pytest-rerunfailures 使用
- 命令行参数: --reruns n(重新运行次数)–reruns-delay m(等待运行秒数)
- 使用装饰器: @pytest.mark.flaky(reruns=5, reruns_delay=2)
在命令行参数进行用例失败重跑
示例:
# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time :2021/7/8 23:22
# @Author : king
# @File :test_rerun.py
# @Software :PyCharm
# @blog :https://blog.csdn.net/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
import pytest
def add(a, b):
return a + b
def test_rerun():
assert add(1, 2) == 4
if __name__ == '__main__':
pytest.main()
在命令行输入: pytest -v --reruns 2 --reruns-delay 5 test_rerun.py
失败用例重试2次,每次延时5秒
使用装饰器的方式进行失败用例重跑
示例:
# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time :2021/7/8 23:22
# @Author : king
# @File :test_rerun.py
# @Software :PyCharm
# @blog :https://blog.csdn.net/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
import pytest
def add(a, b):
return a + b
@pytest.mark.flaky(reruns=2, reruns_delay=5)
def test_rerun():
assert add(1, 2) == 4
if __name__ == '__main__':
pytest.main()
在命令行输入: pytest -v test_rerun.py
失败用例重试2次,每次延时5秒
命令行参数和装饰器同时存在
说明:如果用例装饰器方式设置了重新运行次数,则在命令行添加–reruns对这些用例不会生效
示例:
# !/usr/bin/python3
# _*_coding:utf-8 _*_
""""
# @Time :2021/7/8 23:22
# @Author : king
# @File :test_rerun.py
# @Software :PyCharm
# @blog :https://blog.csdn.net/u010454117
# @WeChat Official Account: 【测试之路笔记】
"""
import pytest
def add(a, b):
return a + b
@pytest.mark.flaky(reruns=1, reruns_delay=5)
def test_rerun():
assert add(1, 2) == 4
if __name__ == '__main__':
pytest.main()
在命令行输入: pytest -v --reruns 3 --reruns-delay 5 test_rerun.py
失败用例重试3次,每次延时5秒
兼容性
官网说明:https://pypi.org/project/pytest-rerunfailures/
Compatibility
- This plugin may not be used with class, module, and package level fixtures.
- This plugin is not compatible with pytest-xdist’s –looponfail flag.
- This plugin is not compatible with the core –pdb flag.
翻译:
- 这个插件不可以和
class, module, package
级别的fixture装饰器一起使用 - 这个插件与
pytest-xdist
的--looponfail
标志不兼容 - 这个插件与核心
--pdb
标志不兼容
总结
- pytest-rerunfailures插件可以通过命令行参数
--reruns 2 --reruns-delay 5
进行使用,这个对于所有用例生效 - pytest-rerunfailures插件使用装饰器装饰在用例上面,只对装饰的用例有效
- 当时同时使用装饰器和命令行参数时,装饰器参数优先级高
- 注意插件的兼容性
以上为内容纯属个人理解,如有不足,欢迎各位大神指正,转载请注明出处!
如果觉得文章不错,欢迎关注微信公众号,微信公众号每天优先推送相关测试技术文章