Pytest - 常用插件

3. Pytest - 常用插件

插件列表網址:https://plugincompat.herokuapp.com 包含很多插件包,大家可依據工作的需求選擇使用。

3.1 測試報告

  • 應用場景

    自動化測試腳本最終執行是通過還是不通過,需要通過測試報告進行體現。

  • 安裝

    $ pip3 install pytest-html 
    
  • 使用

    在配置文件中的命令行參數中增加 --html=用戶路徑/report.html

  • 示例

    pytest.ini
    
    addopts = -s --html=report/report.html
    
  • 結果

    在項目目錄下會對一個 report 文件夾,裏面有個 report.html 即爲測試報告

3.2 控制函數執行順序

  • 應用場景

    現實生活中,如果想下訂單,必須先登錄,我們可以通過插件的形式來控制函數執行的順序。

  • 安裝

    $ pip3 install pytest-ordering 
    
  • 使用

    1. 標記於被測試函數,@pytest.mark.run(order=x)
    2. 根據order傳入的參數來解決運行順序
    3. order值全爲正數或全爲負數時,運行順序:值越小,優先級越高
    4. 正數和負數同時存在:正數優先級高
  • 示例

    import pytest
    
    class TestLogin:
    	def test_hello_001(self):
    		print("test_hello_001")
    	@pytest.mark.run(order=1)
      
    	def test_hello_002(self):
    		print("test_hello_002")
        
    	@pytest.mark.run(order=2)
    	def test_hello_003(self):
    		print("test_hello_003")
    
  • 結果

    scripts/test_login.py test_hello_002 # 先運行2
    
    .test_hello_003 # 再運行3
    
    .test_hello_001
    

3.3 失敗重試

  • 應用場景

    自動化測試腳本可能會使用到網絡,如果網絡不好可能最終會使腳本不通過。像這種情況可能並不是腳本本身的問題,僅僅是因爲網絡忽快忽慢,那麼我們可以使用失敗重試的插件,當失敗後嘗試再次運行。一般情況最終成功可以視爲成功,但最好進行進行排查時候是腳本問題。

  • 安裝

    pip3 install pytest-rerunfailures 
    
  • 使用

    在配置文件中的命令行參數中增加 --reruns n

  • 示例

    pytest.ini

    addopts = -s --reruns 3
    

    test_login.py

    class TestLogin:
    
    	def test_a(self): # test開頭的測試函數
    		print("------->test_a")
    		assert 1 # 斷言成功
    	
    	def test_b(self):
    		print("------->test_b")
    		assert 0 # 斷言失敗
    
  • 結果

    scripts/test_login.py ------->test_a
    .------->test_b
    R------->test_b
    R------->test_b
    R------->test_b
    F
    

R 表示重試

  • 注意點

    重試時,如果腳本通過,那麼後續不再重試

    .test_hello_003 # 再運行3
    .test_hello_001
    

如果你期望加上出錯重試的等待時間,請使用如下命令(reruns-delay是等待時間):

pytest --reruns 5 --reruns-delay 1

如果你只想對某幾個測試用例應用重試策略,你可以使用裝飾器:

@pytest.mark.flaky(reruns=5, reruns_delay=2)

例如:

@pytest.mark.flaky(reruns=5, reruns_delay=2)
def test_example():
    import random
    assert random.choice([True, False])

其它參數

pytest --maxfail=10 #失敗超過10次則停止運行
pytest -x test_demo.py #出現失敗則停止
發佈了25 篇原創文章 · 獲贊 1 · 訪問量 648
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章