Python中使用pytest.markskip()跳过测试用例的方法
发布时间:2023-12-28 08:29:47
在Python中使用pytest.mark.skip()可以跳过特定的测试用例。该装饰器函数可以应用于测试函数或测试类上,以跳过执行指定的测试。
下面是一个使用pytest.mark.skip()跳过测试用例的示例:
import pytest
@pytest.mark.skip(reason="Skipped test example")
def test_skip_example():
assert 1 + 1 == 3
@pytest.mark.skipif(sys.version_info < (3, 9), reason="Requires Python 3.9+")
def test_skipif_example():
assert 2 ** 3 == 8
@pytest.mark.skip("Not implemented yet")
def test_skip_reason_example():
assert "pytest" in "Pytest example"
@pytest.mark.parametrize("test_input, expected", [
("hello", "HELLO"),
("world", "WORLD"),
pytest.param("pytest", "PYTEST", marks=pytest.mark.skip(reason="Skip parametrized test"))
])
def test_parametrized_example(test_input, expected):
assert test_input.upper() == expected
上述示例中,我们使用了不同的方式来跳过测试用例:
1. 在test_skip_example函数上使用了@pytest.mark.skip()装饰器,指定了跳过此测试用例的原因。
2. 在test_skipif_example函数上使用了@pytest.mark.skipif装饰器,该装饰器可根据指定的条件跳过测试用例。在示例中,如果Python版本低于3.9,则跳过此测试用例。
3. 在test_skip_reason_example函数上使用了@pytest.mark.skip装饰器,并提供了跳过此测试用例的自定义原因。
4. 在test_parametrized_example函数上使用了@pytest.mark.parametrize装饰器,该装饰器用于参数化测试。在此示例中,我们使用了pytest.param来设置某个特定参数化测试跳过的原因。
在运行测试时,pytest将会忽略所有被标记为跳过的测试用例,并将它们显示为跳过状态。
这是一个运行上述示例的输出示例:
============================= test session starts ============================== platform linux -- Python 3.9.7, pytest-6.2.4, py-1.11.0, pluggy-1.0.0 rootdir: /home/user/my_project collected 4 items test_example.py .......... [100%] ============================= 6 passed, 4 deselected in 0.01s ==============================
可以看到,4个示例中的3个已被跳过,因为它们被装饰器标记为跳过。
使用pytest.mark.skip()或其他类似的装饰器函数,可以轻松地跳过不符合特定条件或仍未实现的测试用例。
