一晓避、前言
平常在做功能測(cè)試的時(shí)候簇捍,經(jīng)常會(huì)遇到某個(gè)模塊不穩(wěn)定,偶然會(huì)出現(xiàn)一些bug俏拱,對(duì)于這種問題我們會(huì)針對(duì)此用例反復(fù)執(zhí)行多次暑塑,最終復(fù)現(xiàn)出問題來
自動(dòng)化運(yùn)行用例時(shí)候,也會(huì)出現(xiàn)偶然的bug锅必,可以針對(duì)單個(gè)用例事格,或者針對(duì)某個(gè)模塊的用例重復(fù)執(zhí)行多次
二、環(huán)境前提
Python 2.7搞隐、3.4+或PyPy
py.test 2.8或更高版本
三驹愚、安裝插件
pip3 install pytest-repeat -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
四、快速入門
結(jié)合之前講到的失敗重跑劣纲、輸出html報(bào)告插件來敲命令行
兩種方式皆可逢捺,等號(hào)或空格
count=2
count 2
命令行如下:
pytest --html=report.html --self-contained-html -s --reruns=5 --count=2 10fixture_request.py
五、重復(fù)測(cè)試直到失旕尽(-x)
- 如果需要驗(yàn)證偶現(xiàn)問題劫瞳,可以一次又一次地運(yùn)行相同的測(cè)試直到失敗,這個(gè)插件將很有用
- 可以將pytest的 -x 選項(xiàng)與pytest-repeat結(jié)合使用绷柒,以強(qiáng)制測(cè)試運(yùn)行程序在第一次失敗時(shí)停止
py.test --count=1000 -x test_file.py
def test_example():
import random
flag = random.choice([True, False])
print(flag)
assert flag
執(zhí)行命令: pytest -s --count 5 -x 13repeat.py
六志于、代碼中用@pytest.mark.repeat(count)
如果要在代碼中將某些測(cè)試用例標(biāo)記為執(zhí)行重復(fù)多次,可以使用 @pytest.mark.repeat(count)
@pytest.mark.repeat(5)
def test_repeat():
print("測(cè)試用例執(zhí)行")
執(zhí)行命令: pytest -s 13repeat.py
七废睦、命令行--repeat-scope
命令行參數(shù)
作用:可以覆蓋默認(rèn)的測(cè)試用例執(zhí)行順序伺绽,類似fixture的scope參數(shù)
- function:默認(rèn),范圍針對(duì)每個(gè)用例重復(fù)執(zhí)行郊楣,再執(zhí)行下一個(gè)用例
- class:以class為用例集合單位憔恳,重復(fù)執(zhí)行class里面的用例,再執(zhí)行下一個(gè)
- module:以模塊為單位净蚤,重復(fù)執(zhí)行模塊里面的用例钥组,再執(zhí)行下一個(gè)
- session:重復(fù)整個(gè)測(cè)試會(huì)話,即所有測(cè)試用例的執(zhí)行一次今瀑,然后再執(zhí)行第二次
例子1:class
class Test_repeat:
def test_repeat3(self):
print("測(cè)試用例執(zhí)行333")
class Test_repeat2:
def test_repeat3(self):
print("測(cè)試用例執(zhí)行444")
執(zhí)行命令:
pytest -s --count=2 --repeat-scope=class 13repeat.py
例子2:module
def test_repeat1():
print("測(cè)試用例執(zhí)行111")
def test_repeat2():
print("測(cè)試用例執(zhí)行222")
class Test_repeat:
def test_repeat3(self):
print("測(cè)試用例執(zhí)行333")
執(zhí)行命令:
pytest -s --count=2 --repeat-scope=module 13repeat.py
兼容性問題
pytest-repeat不能與unittest.TestCase測(cè)試類一起使用程梦。無論--count設(shè)置多少,這些測(cè)試始終僅運(yùn)行一次橘荠,并顯示警告