以下先决条件才能使用pytest-rerunfailures
pip3 install pytest-rerunfailures -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
https://github.com/pytest-dev/pytest-rerunfailures
https://pypi.org/project/pytest-rerunfailures/#description
命令行参数:–reruns n(重新运行次数),–reruns-delay m(等待运行秒数)
装饰器参数:reruns=n(重新运行次数),reruns_delay=m(等待运行秒数)
1、要重新运行所有测试失败的用例,使用 --reruns 命令行选项,并指定要运行测试的最大次数:
pytest --reruns 5 -s
运行失败的 fixture 或 setup_class 也将重新执行
2、也可以这样用
pytest --reruns 5 --reruns-delay 1
但是condition并没有这个命令行,它变成了–only-rerun
$ 遇到AssertionError错误就重跑
$ pytest --reruns 5 --only-rerun AssertionError
# 遇到AssertionError或者ValueError 就重跑
$ pytest --reruns 5 --only-rerun AssertionError --only-rerun ValueError
示例
def test_a():
assert int('a') # 会产生一个ValueError
#执行
pytest -sv --reruns 2 --reruns-delay 1 --only-rerun ValueError test_demo.py
结果

–only-rerun的意思很明确,只有遇到ValueError才重跑
同样的代码,换个参数–rerun-except,除了ValueError才会重跑,遇到ValueError并不重跑
pytest -sv --reruns 2 --reruns-delay 1 --rerun-except ValueError test_demo.py

要将单个测试用例添加flaky装饰器 @pytest.mark.flaky(reruns=5) ,并在测试失败时自动重新运行,需要指定最大重新运行的次数
示例:
import pytest
@pytest.mark.flaky(reruns=5)
def test_example():
import random
assert random.choice([True,False,False])
执行结果

同样,也可以指定重新运行的等待时间
import pytest
@pytest.mark.flaky(reruns=5,reruns_delay=2)
def test_example():
import random
assert random.choice([True,False,False])
执行结果

如果指定了用例的重新运行次数,则在命令行添加 --reruns 对这些用例是不会生效的
不可以和fixture装饰器一起使用: @pytest.fixture()