通過使用 ?pytest.mark
? 助手,您可以輕松地在測試函數(shù)上設(shè)置元數(shù)據(jù),或者,您可以使用 ?CLI - pytest --markers
? 列出所有標(biāo)記,包括內(nèi)置標(biāo)記和自定義標(biāo)記。
以下是一些內(nèi)置標(biāo)記:
usefixtures
?——在測試函數(shù)或類上使用fixturefilterwarnings
?—過濾測試函數(shù)的某些警告skip
?—總是跳過一個測試函數(shù)skipif
?-如果滿足某個條件,則跳過某個測試函數(shù)Xfail
?——如果滿足某個條件,則產(chǎn)生一個“預(yù)期失敗”的結(jié)果parametrize
?——對同一個測試函數(shù)執(zhí)行多個調(diào)用創(chuàng)建自定義標(biāo)記或?qū)?biāo)記應(yīng)用于整個測試類或模塊很容易。 這些標(biāo)記可以被插件使用,并且通常用于在命令行上使用 ?-m
? 選項(xiàng)選擇測試。
標(biāo)記只能應(yīng)用于測試,對?fixture
?沒有影響。
您可以像這樣在 ?pytest.ini
? 文件中注冊自定義標(biāo)記:
[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",
]
請注意,標(biāo)記名稱后 : 之后的所有內(nèi)容都是可選描述。
或者,您可以在 ?pytest_configure
? 鉤子中以編程方式注冊新標(biāo)記:
def pytest_configure(config):
config.addinivalue_line(
"markers", "env(name): mark test to run only on named environment"
)
注冊的標(biāo)記出現(xiàn)在pytest的幫助文本中,不會發(fā)出警告。建議第三方插件總是注冊它們的標(biāo)記。
使用 ?@pytest.mark.name_of_the_mark
? 裝飾器應(yīng)用的未注冊標(biāo)記將始終發(fā)出警告,以避免由于輸入錯誤的名稱而默默地做一些令人驚訝的事情。 如上一節(jié)所述,您可以通過在 ?pytest.ini
? 文件中注冊自定義標(biāo)記或使用自定義 ?pytest_configure
? 鉤子來禁用自定義標(biāo)記的警告。
傳遞 ?--strict-markers
? 命令行標(biāo)志時,使用 ?@pytest.mark.name_of_the_mark
? 裝飾器應(yīng)用的任何未知標(biāo)記都將觸發(fā)錯誤。 您可以通過將 ?--strict-markers
?添加到 ?addopts
?來在項(xiàng)目中強(qiáng)制執(zhí)行此驗(yàn)證:
[pytest]
addopts = --strict-markers
markers =
slow: marks tests as slow (deselect with '-m "not slow"')
serial
更多建議: