如何使用屬性標記測試函數

使用 pytest.mark 輔助工具,您可以輕鬆地設定測試函數的元資料。您可以在 API 參考 中找到內建標記的完整清單。或者,您可以使用 CLI 列出所有標記,包括內建和自訂標記 - pytest --markers

以下是一些內建標記

  • usefixtures - 對測試函數或類別使用固定裝置

  • filterwarnings - 篩選測試函數的特定警告

  • skip - 永遠略過測試函數

  • skipif - 如果符合特定條件,則略過測試函數

  • xfail - 如果符合特定條件,則產生「預期失敗」結果

  • parametrize - 對同一個測試函數執行多次呼叫。

建立自訂標記或將標記套用至整個測試類別或模組非常容易。這些標記可以用於外掛程式,而且通常用於使用 -m 選項在命令列中 選取測試

請參閱 使用自訂標記 以取得範例,這些範例也可以作為文件。

注意

標記只能套用至測試,對 固定裝置 沒有影響。

註冊標記

您可以像這樣在 pytest.ini 檔案中註冊自訂標記

[pytest]
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')
    serial

或像這樣在 pyproject.toml 檔案中註冊自訂標記

[tool.pytest.ini_options]
markers = [
    "slow: marks tests as slow (deselect with '-m \"not slow\"')",
    "serial",
]

請注意,標記名稱後 : 之後的任何內容都是一個選用的說明。

或者,您可以在 pytest_configure 鉤子中以程式方式註冊新的標記

def pytest_configure(config):
    config.addinivalue_line(
        "markers", "env(name): mark test to run only on named environment"
    )

已註冊的標記會顯示在 pytest 的說明文字中,並且不會發出警告(請參閱下一部分)。建議第三方外掛程式始終 註冊其標記

對未知標記引發錯誤

使用 @pytest.mark.name_of_the_mark 裝飾器套用的未註冊標記將始終發出警告,以避免因輸入錯誤的名稱而靜默地執行令人驚訝的事情。如前一部分所述,您可以透過在 pytest.ini 檔案中註冊它們或使用自訂 pytest_configure 鉤子來停用自訂標記的警告。

當傳遞 --strict-markers 命令列標記時,任何使用 @pytest.mark.name_of_the_mark 裝飾器套用的未知標記都會觸發錯誤。您可以透過將 --strict-markers 新增到 addopts 來在您的專案中強制執行此驗證

[pytest]
addopts = --strict-markers
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')
    serial