pytest的運行方式及如何控制測試用例的執行


一、pytest的運行方式

# file_name: test_add.py

import pytest  # 導入pytest包


def test_add01():  # test開頭的測試函數
    print("----------------->>> test_add01")
    assert 1 # 斷言成功


def test_add02():
    print("----------------->>> test_add02")
    assert 0 # 斷言失敗


if __name__ == '__main__':
    pytest.main(["-s", "test_add.py"])  # 調用pytest的main函數執行測試

1.1 測試類主函數模式運行:

pytest.main(["-s", "test_add.py"])

 

1.2 命令行模式運行:

pytest 文件路徑 / 測試文件名

例如:pytest ./test_add.py

 

二、控制測試用例的執行

2.1 在第N個測試用例失敗后,結束測試用例執行

pytest -X    # 第1次失敗就停止測試

pytest --maxfail=2    # 出現2個失敗就終止測試

 

2.2 執行測試模塊

pytest test_add.py

 

2.3 執行測試目錄

pytest ./pytest_study/

 

2.4 通過關鍵字表達式過濾執行

pytest -k "keyword and not other keyword"

這條命令會去匹配"文件名、類名、方法名"符合表達式的的測試用例!

舉例:

# file_name: test_add.py

import pytest


def test_add01():
    print("----------------->>> test_add01")
    assert 1


def test_add02():
    print("----------------->>> test_add02")
    assert 0


def test_add03():
    print("test_add03")
    assert 1


def test_add04_abc():
    print("test_add04_abc")
    assert 1

執行命令:pytest  -k "test and not abc" -s ./pytest_study/test_add.py   (這個命令表示執行文件名、類名、方法名中關鍵字包含test但是不包含abc的用例)

從執行結果中可以看到,只有方法test_add04_abc()沒有被執行!

 

2.5 通過node id指定測試用例運行

  node id由模塊文件名、分隔符、類名、方法名、參數構成,舉例如下:

  運行模塊中指定方法或用例:

pytest test_mod.py::TestClass::test_func

 

2.6 通過標記表達式執行

pytest -m fast    # fast代表標記的名稱,可自定義

這條命令會執行被裝飾器 @pytest.mark.fast 裝飾的所有測試用例

 舉例:

# file_name: test_add.py


import pytest


@pytest.mark.slow
def test_add01():
    print("----------------->>> test_add01")
    assert 1


@pytest.mark.slow
def test_add02():
    print("----------------->>> test_add02")
    assert 0


@pytest.mark.fast
def test_add03():
    print("----------------->>> test_add03")
    assert 1

上面代碼中方法test_add01()和test_add02()被標記為slow,test_add03()被標記為fast

執行命令:pytest -m fast ./pytest_study/test_add.py -s  (這個命令執行標記為fast的用例)

從上面的執行結果中可以看到,只有被標記為fast的用例test_add03()被執行了!


免責聲明!

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



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