Pytest學習筆記6-自定義標記mark

前言

在pytest中,我們可以使用mark進行用例的自定義標記,通過不同的標記實現不同的運行策略

比如我們可以標記哪些用例是生產環境執行的,哪些用例是測試環境執行的,在運行程式碼的時候指定對應的mark即可

實例說明

舉個🌰

# test_demo.py
import pytest

@pytest.mark.production
def test_production():
    print("生產環境測試用例")


@pytest.mark.dev
def test_dev1():
    print("測試環境測試用例1")


@pytest.mark.dev
def test_dev2():
    print("測試環境測試用例2")


def testnoMark():
    print("沒有標記測試")

使用命令pytest -s -m dev test_demo.py執行

結果如下

image-20210629224049942

可以看到,只執行了兩條標記了dev的用例

處理warnings資訊

  • 創建一個pytest.ini文件

  • 然後在 pytest.ini 文件的 markers 中寫入你的 mark 標記, 冒號 「:」 前面是標記名稱,後面是 mark 標記的說明,可以是空字元串

  • 注意:pytest.ini需要和運行的測試用例同一個目錄,或在根目錄下作用於全局

    image-20210629224639064

規範使用mark標記

添加了pytest.ini文件之後 pytest 便不會再告警,但是如果我們在運行用例的時候寫錯了 mark 名,會導致 pytest 找不到用例,所以我們需要在 pytest.ini 文件中添加參數 「addopts = --strict-markers」來嚴格規範 mark 標記的使用

image-20210629232426057

添加該參數後,當使用未註冊的 mark 標記時,pytest會直接報錯:「 'xxx' not found in markers configuration option 」,不執行測試任務

image-20210629232320091

執行標記以外的用例

pytest -s -m "not dev" test_demo.py

結果如下

image-20210629225046830

執行多個自定義標記的用例

pytest -s -m "dev or production" test_demo.py

結果如下
image-20210629225222295

整理參考

小菠蘿的測試筆記