pytest之多進程運行測試用例(pytest-xdist)


背景:

  我們日常的工作當中進行自動化測試編寫的測試用例會非常多,測試用例一個一個的執行所需要花費的時間會很長,你想象一下如果開發改動一塊代碼,我們需要回歸一下,這時候執行一下自動化用例需要花費一小時或者好幾個小時的時間,這是我們無法容忍的,為了解決這個問題,我們采用pytest的插件pytest-xdist來進行多進程的並發執行測試用例,大大的縮短測試用例的執行時間,提高效率。

並發運行測試用例:

1.安裝pytest-xdist

pip install pytest-xdist

2.多進程並發執行測試用例

pytest test_add.py -n NUM    # NUM表示並發的進程數

舉例:

項目結構如下:

 

 代碼參考:

# file_name: test_a.py

import pytest
import time


def test_a_01():
    print("----------------->>> test_a_01")
    time.sleep(1)
    assert 1


def test_a_02():
    print("----------------->>> test_a_02")
    time.sleep(1)
    assert 1


def test_a_03():
    print("----------------->>> test_a_03")
    time.sleep(1)
    assert 1


def test_a_04():
    print("----------------->>> test_a_04")
    time.sleep(1)
    assert 1


if __name__ == '__main__':
    pytest.main(["-s", "test_a.py"])

 

# file_name: test_b.py


import pytest
import time


def test_b_01():
    print("----------------->>> test_b_01")
    time.sleep(1)
    assert 1


def test_b_02():
    print("----------------->>> test_b_02")
    time.sleep(1)
    assert 1


def test_b_03():
    print("----------------->>> test_b_03")
    time.sleep(1)
    assert 1


def test_b_04():
    print("----------------->>> test_b_04")
    time.sleep(1)
    assert 1


if __name__ == '__main__':
    pytest.main(["-s", "test_b.py"])

 

正常運行以上代碼,耗時:8.09s

 

 設置並行運行數量為4,耗時:3.48s,大大的縮短了測試用例的執行時間。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM