1. 程式人生 > 實用技巧 >Pytest 系列(八)分散式執行

Pytest 系列(八)分散式執行

常用外掛之分散式執行測試用例 pytest-xdist

原則:

  • 用例之間是獨立的,用例之間沒有依賴關係,用例可以完全獨立執行【獨立執行】

  • 用例執行沒有順序,隨機順序都能正常執行【隨機執行】

  • 每個用例都能重複執行,執行結果不會影響其他用例【不影響其他用例】

  • pytest-xdist 通過一些獨特的測試執行模式擴充套件了 pytest

  • 測試執行並行化:如果有多個CPU或主機,可以將它們用於組合的測試執行。

  • --looponfail:在子程序中重複執行測試。 每次執行之後,pytest都會等到專案中的檔案更改後再執行之前失敗的測試。 重複此過程,直到所有測試通過,然後再次執行完整執行。

  • 跨平臺覆蓋:您可以指定不同的Python解釋程式或不同的平臺,並在所有這些平臺上並行執行測試。

安裝:pip install pytest-xdist==1.34.0

使用方法:在命令列或 pytest.ini 配置檔案 addopts 中新增選項 -n、--dist deng

示例:

# test_demo_01.py 
from time import sleep   
def test_01():   
      sleep(2)         
      assert 1 
def test_02():   
      sleep(2)         
      assert 1    

# test_demo_02.py 
from time import sleep 
def test_03():   
      sleep(2)     
      assert 1 
def test_02():  
      sleep(2)     
      assert 1     

# 正常使用 pytest 執行需要 8 秒以上 # 使用 pytest -n auto 執行測試則只需要 4 秒多
  • -n auto:可以自動檢測到系統的CPU核數;使用auto等於利用了所有CPU來跑用例,CPU佔用率會特別高

  • --dist=loadscope:pytest-xdist預設是無須執行的,可以通過 --dist 引數來控制順序

如果存在 scope = session 的 fixture,分散式執行將會多次呼叫該 fixture,此時可以通過鎖定檔案進行程序間通訊來實現只執行一次該 fixture:

import pytest 
from filelock import FileLock   
@pytest.fixture(scope="session", autouse=True) 
def login():   
      print("====登入!===")         
      with FileLock("session.lock"):       
            token = "123456"     
      yield token         
      print("====退出!====")