用属性标记测试函数

通过使用 pytest.mark helper您可以轻松地在测试函数上设置元数据。您可以在中找到内置标记的完整列表 API Reference . 也可以使用CLI列出所有标记,包括内置和自定义- pytest --markers .

以下是一些内置标记:

  • usefixtures -在测试函数或类上使用fixture

  • filterwarnings -过滤测试函数的某些警告

  • skip -总是跳过测试函数

  • skipif -如果满足某个条件,则跳过测试函数

  • xfail -如果满足某个条件,则产生“预期失败”结果。

  • parametrize -对同一测试函数执行多个调用。

很容易创建自定义标记或将标记应用于整个测试类或模块。这些标记可以被插件使用,也常用于 select tests 在命令行上 -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 钩子:

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

注册标记出现在Pytest的帮助文本中,不会发出警告(请参见下一节)。建议始终使用第三方插件 register their markers .

在未知标记上引发错误

未注册的标记应用于 @pytest.mark.name_of_the_mark decorator将始终发出警告,以避免由于键入错误的名称而默默地做一些令人惊讶的事情。如前一节所述,您可以通过将自定义标记注册到 pytest.ini 文件或使用自定义 pytest_configure 钩子。

--strict-markers 传递了命令行标志,任何未知标记都将应用于 @pytest.mark.name_of_the_mark decorator将触发一个错误。您可以通过添加 --strict-markersaddopts

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