Pytest學習筆記11-重複執行用例外掛pytest-repeat
阿新 • • 發佈:2021-07-14
前言
我們在平時做測試的時候,經常會遇到一些偶現的bug,通常我們會多次執行來複現此類bug,那麼在自動化測試的時候,如何多次執行某個或某些用例呢,我們可以使用pytest-repeat這個外掛來幫助我們重複的去執行用例
pytest-repeat外掛
外掛安裝
pip命令安裝
pip install pytest-repeat
使用例項
上程式碼
def test_demo1():
print("執行測試用例1")
def test_demo2():
print("執行測試用例2")
使用命令 pytest -s --count 5 test_demo.py
執行
執行結果如下
可以看到,用例被重複執行了5次
重複測試直到失敗
當我們驗證偶現的問題時,需要不停的重複執行用例,直到用例失敗
可以將pytest的 -x 選項與pytest-repeat結合使用,以強制測試執行程式在第一次失敗時停
上程式碼
def test_example():
import random
flag = random.randint(1,100)
print(flag)
assert flag != 8
使用命令 pytest --count 5 -x test_demo.py
執行
執行結果如下
可以看到,在運行了55次後,用例執行失敗
標記要重複多次的測試
如果要在程式碼中將某些測試用例標記為執行重複多次,可以使用 @pytest.mark.repeat(count)
上程式碼
import pytest
def test_repeat1():
print("測試用例1執行")
@pytest.mark.repeat(5)
def test_repeat2():
print("測試用例2執行")
def test_repeat3():
print("測試用例3執行")
使用命令 pytest -s test_demo.py
執行
執行結果如下
可以看到,用例2被執行了5次
--repeat-scope
作用:類似於pytest fixture的scope引數,--repeat-scope也可以設定引數: session
module
,class
或者function
(預設值)
- function:預設,範圍針對每個用例重複執行,再執行下一個用例
- class:以class為用例集合單位,重複執行class裡面的用例,再執行下一個
- module:以模組為單位,重複執行模組裡面的用例,再執行下一個
- session:重複整個測試會話,即所有測試用例的執行一次,然後再執行第二次
重複執行class中的用例
上程式碼
class Test1:
def test_repeat1(self):
print("測試用例執行1")
class Test2:
def test_repeat2(self):
print("測試用例執行2")
使用命令 pytest -s --count=2 --repeat-scope=class test_demo.py
執行
執行結果如下
可以看到,兩個測試類都執行了2次
重複執行module中的用例
上程式碼
class Test1:
def test_repeat1(self):
print("測試用例執行1")
class Test2:
def test_repeat2(self):
print("測試用例執行2")
def test_repeat3():
print("測試用例執行3")
使用命令 pytest -s --count=2 --repeat-scope=module test_demo.py
執行
執行結果如下
注意
pytest-repeat不能與unittest.TestCase測試類一起使用。無論--count設定多少,這些測試始終僅執行一次,並顯示警告