Pytest學習(七) - skip、skipif的使用

前言

做爲一個java黨,我仍是以爲pytest和testng很像,有時候真的會感受到代碼語言在某種程度上是相通的,那麼今天來講說這兩個知識點。html

skipskipif,見名知意,就是跳過測試唄,直白的說就是用於不想執行的代碼,標記後,標記的代碼不執行。java

skip的用法

使用示例:@pytest.mark.skip(reason="不想執行的緣由,執行時會輸出reason內容")python

一、標記在函數方法上

示例代碼以下:windows

# 標記在函數上
@pytest.mark.skip(reason="標記在函數上,被標記函數不會被執行!!")
def test_case2():
    print("我是測試用例2,但我不會執行")

運行結果以下:
函數

二、標記在類中的函數方法上

示例代碼以下:測試

class TestClass1(object):

    def test_case3(self):
        print("我是用例3")

    # 標記在類中的函數上
    @pytest.mark.skip(reason="標記在類中的函數上,一樣也不會執行哦!")
    def test_case4(self):
        print("我是測試用例4,但我不會執行")

運行結果以下:
3d

三、標記在類上

示例代碼以下:code

@pytest.mark.skip(reason="標記在類上,整個類及類中的方法都不會執行!")
class TestClass2(object):
    def test_case5(self):
        print("我是用例5")

運行結果以下:
orm

小結:htm

  • @pytest.mark.skip 能夠加在函數上,類上,類方法上
  • 若是加在類上面,類裏面的全部測試用例都不會執行

四、在測試用例執行期間強制跳過

以簡單的for循環爲例,執行到第三個的時候,跳出,示例代碼以下:

def test_case6():
    for i in range(50):
        print(f"輸出第 【{i}】個數")
        if i == 3:
            pytest.skip("我跑不動了,不輸出了")

運行結果以下:

總結:
能夠理解爲這時的跳過測試就和循環的break同樣,這時再也不用註解的形式了。

五、在模塊級別跳過測試

語法:pytest.skip(msg="",allow_module_level=False),當 allow_module_level=True 時,能夠設置在模塊級別跳過整個模塊,示例代碼以下:

# -*- coding: utf-8 -*-
# @Time    : 2020/11/12 20:30
# @Author  : longrong.lang
# @FileName: test_skip.py
# @Software: PyCharm
# @Cnblogs :https://www.cnblogs.com/longronglang
import sys

import pytest

if sys.platform.startswith("win"):
    pytest.skip("當 allow_module_level=True 時,能夠設置在模塊級別跳過整個模塊",allow_module_level=True)


@pytest.fixture(autouse=True)
def dataTable():
    print("數據初始化成功")


def test_case1():
    print("我是用例1")

運行結果以下:

六、但願有條件地跳過某些測試用例

語法:@pytest.mark.skipif(條件表達式, reason="")
示例代碼以下:

@pytest.mark.skip(sys.platform.startswith("win"),reason="windows系統不執行哦")
def test_case7():
    print("我是用例6")

運行結果以下:

七、跳過標記的使用

好處

  • 方便用例的統一管理維護
  • 可在不一樣模塊標記

須要將 pytest.mark.skip 和 pytest.mark.skipif 賦值給一個標記變量,用變量(註解變量)進行標記,示例代碼以下:

skip = pytest.mark.skip("skip的標記變量,標記的函數或類不執行")
skipif = pytest.mark.skipif("skipif的標記變量,標記的函數或類不執行")


@skip
def test_case8():
    print("測試用例8")


class TestClass(object):
    @skipif
    def test_case9(self):
        print("測試用例9")

運行結果以下:

八、缺乏某些導入跳過的測試

語法:pytest.importorskip( modname: str, minversion: Optional[str] = None, reason: Optional[str] = None )
參數列表

  • modname:模塊名
  • minversion:版本號
  • reasone:跳過緣由,默認不給也行

示例代碼以下:

importskip = pytest.importorskip("importskip", minversion="0.3",reason="此處是導入失敗,跳過的測試")


@importskip
def test_10():
    print('測試用例10')

運行結果以下:

系列參考文章:
https://www.cnblogs.com/poloyy/category/1690628.html

相關文章
相關標籤/搜索