Pytest 系列(七)常用外掛之測試用例相關
一、失敗重跑 pytest-rerunfailures
要求:python 3.5+、pytest 5.0+
安裝:pip install pytest-rerunfailures
文件:https://pypi.org/project/pytest-rerunfailures/
使用方法:在命令列或 pytest.ini 配置檔案 addopts 中新增選項:--reruns n(重新執行n次數),--reruns-delay m(等待m秒開始下次重新執行)
(1)命令列:pytest --reruns 3 --reruns-delay 5
(2)pytest.ini 檔案:addopts = --reruns 3 --reruns-delay 5
若要指定單個測試用例在失敗時重新執行,需要在測試用例新增 flaky 裝飾器,如:@pytest.mark.flaky(reruns=n, reruns_delay=m)
@pytest.mark.flaky(reruns=2, reruns_delay=3)
def test_01():
assert 0
二、用例執行順序 pytest-ordering
預設情況下,pytest 根據測試方法從上到下執行用例,可以通過第三方外掛 pytest-ordering 來改變測試順序。
安裝:pip install pytest-ordering
文件:https://pypi.org/project/pytest-ordering/
使用方法:在需要調整執行順序的測試函式上標記 @pytest.mark.run(order=x)order 值越小,優先順序越高;執行順序按照如下排序:0 > 正數 > 未使用run修飾的 > 負數。
import pytest @pytest.mark.run(order=3) def test_01(): print("test_01") assert 1 @pytest.mark.run(order=2) def test_02(): print("test_02") assert 1 @pytest.mark.run(order=-1) def test_03(): print("test_03") assert 1 # 以上用例將按照 test_02 -> test_01 -> test_03 順序執行
三、重複執行 pytest-repeat
安裝:pip install pytest-repeat
使用方法:在命令列或 pytest.ini 配置檔案 addopts 中新增選項:
-
--count n(重複執行n次數),
-
--repeat-scope 可以覆蓋預設的測試用例執行順序,類似 fixture 的scope引數
-
function:預設,範圍針對每個用例重複執行,再執行下一個用例
-
class:以class為用例集合單位,重複執行class裡面的用例,再執行下一個
-
module:以模組為單位,重複執行模組裡面的用例,再執行下一個
-
session:重複整個測試會話,即所有測試用例的執行一次,然後再執行第二次
(1)命令列:pytest --count 5
(2)pytest.ini 檔案:addopts = --count 5
通常與 pytest 的 -x 搭配使用,重複測試直到失敗,常用於驗證一些偶先的問題
命令列執行: pytest --count=10 -x test_demo.py
# test_demo.py 檔案
import pytest
@pytest.mark.repeat(10)
# 將指定測試用例標記為執行重複多次
def test_01():
assert 1
四、多重斷言 pytest-assume
assert斷言可以寫多個斷言,但一個失敗,後面的斷言將不再執行,可以使用 pytest-assume 來進行斷言,即使斷言失敗,後面的斷言還是會繼續執行,比 assert 更高效
安裝:pip install pytest-assume
import pytest
def test_01():
pytest.assume(1==1)
pytest.assume(2==2)
pytest.assume(1==0)
pytest.assume(3==3)
print("測試完成")