如果你還想從頭學起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設置多少,這些測試始終僅運行一次,並顯示警告