1. 程式人生 > 其它 >pytest(14):重複執行用例外掛之pytest-repeat的詳細使用

pytest(14):重複執行用例外掛之pytest-repeat的詳細使用

前言

  • 平常在做功能測試的時候,經常會遇到某個模組不穩定,偶然會出現一些bug,對於這種問題我們會針對此用例反覆執行多次,最終復現出問題來
  • 自動化執行用例時候,也會出現偶然的bug,可以針對單個用例,或者針對某個模組的用例重複執行多次

環境前提

  • 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

快速入門

結合之前講到的失敗重跑、輸出html報告外掛來敲命令列

兩種方式皆可,等號或空格

  • count=2
  • count 2
pytest --html=report.html --self-contained-html  -s --reruns=5 --count=2 10fixture_request.py

重複測試直到失敗(重點!)*與上文講的returns主要的區別就是一個是出現錯誤return直到通過,另一個是重複執行直到出現錯誤

  • 如果需要驗證偶現問題,可以一次又一次地執行相同的測試直到失敗,這個外掛將很有用
  • 可以將pytest的-x選項與pytest-repeat結合使用,以強制測試執行程式在第一次失敗時停止

py.test --count=1000 -x test_file.py

舉例

class Test_AA():
def test_re(self):

j=1
print(1)
assert j==1
def test_re2(self):
i=1
print(i)
assert i==1

命令列執行:pytest -s --count=5 test_report.py

@pytest.mark.repeat(count)

如果要在程式碼中將某些測試用例標記為執行重複多次,可以使用@pytest.mark.repeat(count)

class Test_AA():
@pytest.mark.repeat(5)
def test_re(self):

j=1
print(1)
assert j==1

命令列執行:pytest -s test_report.py

--repeat-scope

命令列引數

作用:可以覆蓋預設的測試用例執行順序,類似fixture的scope引數

  • function:預設,範圍針對每個用例重複執行,再執行下一個用例
  • class:以class為用例集合單位,重複執行class裡面的用例,再執行下一個
  • module:以模組為單位,重複執行模組裡面的用例,再執行下一個
  • session:重複整個測試會話,即所有測試用例的執行一次,然後再執行第二次

程式碼:

import pytest
import random

class Test_AA():
# @pytest.mark.repeat(5)
def test_re(self):

j=1
print(1)
assert j==1
def test_re2(self):
i=1
print(i)
assert i==1
class Test_BB():
def test_reb(self):

j=2
print(j)
assert j==2

def test_reb2(self):
i=1
print(i)
assert i==1

執行命令

  pytest -s --count=2 --repeat-scope=class test_A.py