Pytest學習筆記6——自定義用例順序


  引言

  unittest框架和pytest框架編寫的測試用例執行順序,默認根據ACSII碼的順序加載測試用例,數字與字母的順序為:0~9,A~Z,a~z。

  1.對於類來說,class TestAxx 會優先於class TestBxx被執行。

  2.對於方法來說,test_aaa()方法會有優先於test_bbb()被執行。

  對於測試目錄與測試文件來說,unittest同樣是按照這個規則來加載測試用例的。

  背景

  我們寫接口測試用例的時候,可以按上下接口順序給它命名test_01...test_02...test_03...等等。

  這樣寫的弊端是用例執行順序是: test_01<test_02<test_03<test_04<test_05...

  如果我想test_04在test_03前面呢? 有人會說,直接將test_04的代碼,寫到test_03里面去,相當於交換上下的位置,這樣是可以。

  如果是剛開始寫是可以,可是后期變動維護起來顯然是不方便。

  這樣就有人寫了個插件來解決了這個問題,插件:pytest-ordering。

  下載地址:github 上有個 pytest-ordering 插件可以控制用例的執行順序,github插件地址https://github.com/ftobia/pytest-ordering

  安裝

pip install pytest-ordering

  實例分析

  默認執行順序

import pytest


def test_01():
    print("打開瀏覽器")

def test_02():
    print("輸入url")

def test_03():
    print("輸入賬號")

def test_04():
    print("輸入密碼")

def test_05():
    print("勾選記住用戶")

def test_06():
    print("單擊登錄")

  運行結果:

  在測試用例目錄下輸入

pytest -vs test.py

  

 

  使用插件執行順序

  使用 pytest-ordering 插件后改變測試用例順序

import pytest

@pytest.mark.run(order=1)
def test_01():
    print("打開瀏覽器")
@pytest.mark.run(order=2)
def test_02():
    print("輸入url")
@pytest.mark.run(order=4)
def test_03():
    print("輸入賬號")
@pytest.mark.run(order=3)
def test_04():
    print("輸入密碼")

@pytest.mark.last
def test_05():
    print("勾選記住用戶")

def test_06():
    print("單擊登錄")

  運行結果:

  還是輸入命令:

pytest -vs test.py

 

 

  出現這個警告不要慌,在項目目錄下新建pytest.ini文件,在文件輸入以下內容:

 

 

  再次運行即可:

 

   這樣就實現了自定義測試用例的執行順序。

  總結

  這個知識點在多數場景都會用到,pytest-ordering插件基本上就是這樣了。

  另外,對測試開發,自動化測試,全棧測試相關技術感興趣的朋友,可以加入到群里學習和探索交流,進群方式,掃下方二維碼。

 


免責聲明!

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



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