pytest大保健系列
一、前言
1.需求情景:
- 做功能測試的時候,經常會遇到某個子產品不穩定,偶然會出現一些bug,對于這種問題我們會針對此用例反複執行多次,直到複現出這個問題來
- 自動化運作用例時候,也會出現偶然的bug,可以針對單個用例,或者針對某個子產品的用例重複執行多次
- 該用例是不管失敗與否用例都跑多次,與失敗重跑不同,失敗重跑隻會在失敗的時候重新嘗試多次
2.使用前提
- Python 2.7、3.4+或PyPy
- py.test 2.8或更高版本
- pytest-repeat不能與unittest.TestCase測試類一起使用。無論--count設定多少,這些測試始終僅運作一次,并顯示警告
3.pip安裝
pip3 install pytest-repeat -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
4.指令描述
支援全局用例重複執行,也支援單個用例重複執行
指令行參數(所有用例有效):--count=2 或 --count 2
裝飾器參數(單個用例有效):@pytest.mark.repeat(2)
二、指令行 所有用例都執行
import pytest
def test_case1():
print("執行測試用例1")
assert 1 + 1 == 2
def test_case2():
print("執行測試用例2")
assert 1 + 3 == 6
1.基本使用 重複執行
pytest --count=2 -s demo.py

2.重複執行結合 pytest 的 -x 參數 ,遇到錯誤立即停止執行
- 如果需要驗證偶發bug,可以一次又一次地運作相同的測試用例,直到失敗重制就停止
pytest --count=2 -x -s txt.py
3.重複執行 結合 失敗重跑
pytest --count=2 --reruns 3 -s txt.py
三、裝飾器 單個用例重複執行
1.基本用法 @pytest.mark.repeat(5)
import pytest
@pytest.mark.repeat(2)
def test_case1():
print("執行測試用例1")
assert 1 + 1 == 2
執行:pytest --count=3 -s demo.py
四、--repeat-scope 參數 自定義重複執行的機關
作用:可以覆寫預設的測試用例執行順序,類似fixture的scope參數
- function:預設,範圍針對每個用例重複執行,再執行下一個用例
- class:以class為用例集合機關,重複執行class裡面的用例,再執行下一個
- module:以子產品為機關,重複執行子產品裡面的用例,再執行下一個
- session:重複整個測試會話,即所有測試用例的執行一次,然後再執行第二次
案例一:class
class Test_repeat:
def test_2(self):
print("測試用例執行222")
def test_3(self):
print("測試用例執行333")
class Test_repeat2:
def test_4(self):
print("測試用例執行444")
執行指令
pytest -s --count=2 --repeat-scope=class demo.py
執行結果
案例二:module
def test_repeat1():
print("測試用例執行111")
def test_repeat2():
print("測試用例執行222")
class Test_repeat:
def test_repeat3(self):
print("測試用例執行333")
執行指令
pytest -s --count=2 --repeat-scope=module 13repeat.py
執行結果