如何使用屬性標記測試函數¶
通過使用 pytest.mark
輔助函數,您可以輕鬆地在測試函數上設定元數據。您可以在 API 參考 中找到內建標記的完整列表。或者您可以使用 CLI 列出所有標記,包括內建和自訂標記 - pytest --markers
。
以下是一些內建標記
usefixtures - 在測試函數或類別上使用 fixtures
filterwarnings - 過濾測試函數的某些警告
skip - 始終跳過測試函數
skipif - 如果滿足特定條件,則跳過測試函數
xfail - 如果滿足特定條件,則產生「預期失敗」結果
parametrize - 對同一個測試函數執行多次調用。
創建自訂標記或將標記應用於整個測試類別或模組非常容易。這些標記可以被 plugins 使用,並且通常也用於使用 -m
選項在命令行上選擇測試。
有關範例(也可用作文檔),請參閱 使用自訂標記。
注意
標記只能應用於測試,對 fixtures 沒有任何影響。
註冊標記¶
您可以在 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 hook 中以程式方式註冊新標記
def pytest_configure(config):
config.addinivalue_line(
"markers", "env(name): mark test to run only on named environment"
)
註冊的標記會出現在 pytest 的幫助文本中,並且不會發出警告(請參閱下一節)。建議第三方 plugins 始終註冊其標記。
對未知標記引發錯誤¶
使用 @pytest.mark.name_of_the_mark
裝飾器應用的未註冊標記始終會發出警告,以避免由於名稱拼寫錯誤而靜默地執行令人驚訝的操作。如上一節所述,您可以通過在 pytest.ini
檔案中註冊自訂標記或使用自訂 pytest_configure
hook 來禁用自訂標記的警告。
當傳遞 --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