如何使用pytest禁用测试?

2024-03-29 02:18:50 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一系列测试:

def test_func_one():
    ...

def test_func_two():
    ...

def test_func_three():
    ...

是否有一个装饰器或类似的东西可以添加到函数中,以防止pytest仅运行该测试?结果可能看起来像

@pytest.disable()
def test_func_one():
    ...

def test_func_two():
    ...

def test_func_three():
    ...

Tags: 函数testpytestdef装饰onethreefunc
3条回答

当您想跳过^{}中的测试时,可以使用skipskipif装饰符标记测试

跳过测试

@pytest.mark.skip(reason="no way of currently testing this")
def test_func_one():
    ...

跳过测试的最简单方法是使用skip装饰器标记它,该装饰器可以传递一个可选的reason

也可以通过调用pytest.skip(reason)函数在测试执行或设置期间强制跳过。当无法在导入期间评估跳过条件时,这非常有用

def test_func_one():
    if not valid_config():
        pytest.skip("unsupported configuration")

跳过基于条件的测试

@pytest.mark.skipif(sys.version_info < (3, 6), reason="requires python3.6 or higher")
def test_func_one():
    ...

如果要基于条件跳过,则可以使用skipif。在前面的示例中,当在早于Python3.6的解释器上运行时,将跳过测试函数

最后,如果您想跳过测试,因为您确信它正在失败,您也可以考虑使用^{}标记来指示您期望测试失败。

Pytest有skip和skipif修饰符,类似于Python单元测试模块(它使用skipskipIf),可以在文档here中找到

链接中的示例可在此处找到:

@pytest.mark.skip(reason="no way of currently testing this")
def test_the_unknown():
    ...

import sys
@pytest.mark.skipif(sys.version_info < (3,3),
                    reason="requires python3.3")
def test_function():
    ...

第一个示例总是跳过测试,第二个示例允许您有条件地跳过测试(当测试依赖于平台、可执行版本或可选库时非常好)

例如,如果我想检查是否有人为测试安装了库pandas

import sys
try:
    import pandas as pd
except ImportError:
    pass

@pytest.mark.skipif('pandas' not in sys.modules,
                    reason="requires the Pandas library")
def test_pandas_function():
    ...

{a1}将完成以下工作:

@pytest.mark.skip(reason="no way of currently testing this")
def test_func_one():
    # ...

reason参数是可选的,但最好指定跳过测试的原因)

还有^{}允许在满足某些特定条件时禁用测试


这些装饰器可以应用于方法、函数或类

skip all tests in a module,请定义一个全局pytestmark变量:

# test_module.py
pytestmark = pytest.mark.skipif(...)

相关问题 更多 >