Pytest學習筆記(四) skip跳過測試用例
阿新 • • 發佈:2020-12-09
在執行測試用例時,有些用例可能不需要執行,這時可以用skip來跳過用例:
1、skip始終跳過該測試用例
如下三個用例,標記用例2不執行
import pytest def test_001(): assert 1 == 1 @pytest.mark.skip(reason="此條用例暫不執行") def test_002(): assert 1 == 1 def test_003(): assert 1 == 1
執行 pytest -vrs,結果如下:
如上,使用skip裝飾器標記是跳過測試用例的最簡單方法。
也可以在測試執行或setup期間,通過呼叫pytest.skip(reason)函式強制跳過該用例:
def test_function(): if not valid_config(): pytest.skip("不支援該配置")
還可以在模組級別跳過整個模組:pytest.skip(reason,allow_module_level=True)
import sys import pytest if not sys.platform.startswith("win"): pytest.skip("跳過只支援Windows平臺的用例",allow_module_level=True)
2、skipif 指定條件下跳過測試用例
滿足指定條件時則跳過用例的執行,如下當Python版本小於3.9時跳過測試用例
import pytest import sys @pytest.mark.skipif(sys.version_info < (3, 9), reason="需要Python3.9版本以上") def test_002(): assert 1 == 1
注意:skipif方法必須指定reason,否則會報錯
我們還可以定義一個變數,根據變數返回為True或False來判斷是否跳過用例,如下:
import pytest import sys minversion = pytest.mark.skipif( sys.version_info < (3, 9), reason="需要Python3.9版本以上" ) @minversion def test_002(): assert 1 == 1
在另一個檔案中還可以匯入這個變數來重複引用
from api.test_case import minversion @minversion def test_003(): assert 5 == 5
跳過整個檔案的所有測試用例
import pytest import sys # 當前檔案下的測試用例需要滿足這個條件才能被執行 pytestmark = pytest.mark.skipif(sys.version_info < (3, 9), reason="需要Python3.9版本以上") def test_001(): assert 1 == 1 def test_002(): assert 8 == 8