1. 程式人生 > >Pytest系列(13)- 重複執行用例外掛之pytest-repeat的詳細使用

Pytest系列(13)- 重複執行用例外掛之pytest-repeat的詳細使用

如果你還想從頭學起Pytest,可以看看這個系列的文章哦!

https://www.cnblogs.com/poloyy/category/1690628.html

 

前言

  • 平常在做功能測試的時候,經常會遇到某個模組不穩定,偶然會出現一些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

 

重複測試直到失敗(重點!)

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

 

小栗子

def test_example():
    import random
    flag = random.choice([True, False])
    print(flag)
    assert flag

 

執行命令

  pytest -s --count 5 -x 13repeat.py

 

執行結果

 

 

 

@pytest.mark.repeat(count)

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

@pytest.mark.repeat(5)
def test_repeat():
    print("測試用例執行")

 

執行命令

pytest -s 13repeat.py

 

執行結果

 

 

 

--repeat-scope

命令列引數

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

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

案例一:class

class Test_repeat:
    def test_repeat3(self):
        print("測試用例執行333")

class Test_repeat2:
    def test_repeat3(self):
        print("測試用例執行444")

執行命令

pytest -s --count=2 --repeat-scope=class 13repeat.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

執行結果

 

 

相容性問題

pytest-repeat不能與unittest.TestCase測試類一起使用。無論--count設定多少,這些測試始終僅執行一次,並顯示警告

&n