前言

在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執行

結果如下

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

處理warnings資訊

  • 建立一個pytest.ini檔案

  • 然後在 pytest.ini 檔案的 markers 中寫入你的 mark 標記, 冒號 “:” 前面是標記名稱,後面是 mark 標記的說明,可以是空字串

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

規範使用mark標記

添加了pytest.ini檔案之後 pytest 便不會再告警,但是如果我們在執行用例的時候寫錯了 mark 名,會導致 pytest 找不到用例,所以我們需要在 pytest.ini 檔案中新增引數 “addopts = --strict-markers”來嚴格規範 mark 標記的使用

新增該引數後,當使用未註冊的 mark 標記時,pytest會直接報錯:“ 'xxx' not found in markers configuration option ”,不執行測試任務

執行標記以外的用例

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

結果如下

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

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

結果如下

整理參考

小菠蘿的測試筆記