py.test跳过取决于参数

时间:2017-12-20 21:58:28

标签: python unit-testing pytest

我希望通过所有可能的参数组合调用它来详尽地测试函数:

@pytest.mark.parametrize("a", [1, 2])
@pytest.mark.parametrize("b", [1, 2, 3, 4])
@pytest.mark.parametrize("c", [1, 2, 3])
@pytest.mark.parametrize("d", [1, 2])
def test_func_variations(a, b, c, d):
    assert func(a, b, c, d) == a*b*c+d

虽然其中一些组合没有意义。有没有一种简单的方法可以跳过py.test的这些组合,例如也有这样的逻辑:

def test_func_variations(a, b, c, d):
    if (a == 1 and b in (2, 3)) or (a == 2 and c == 3):
        skip_me()
    assert func(a, b, c, d) == a*b*c+d

2 个答案:

答案 0 :(得分:4)

好的,这很简单:

@pytest.mark.parametrize("a", [1, 2])
@pytest.mark.parametrize("b", [1, 2, 3, 4])
@pytest.mark.parametrize("c", [1, 2, 3])
@pytest.mark.parametrize("d", [1, 2])
def test_func_variations(a, b, c, d):
    if (a == 1 and b in (2, 3)) or (a == 2 and c == 3):
        pytest.skip("invalid parameter combination")
    assert func(a, b, c, d) == a*b*c+d

答案 1 :(得分:-1)

尽管在测试中运行“if”条件是有效的,但更正确的解决方案是指出预期在 XFail 上失败的“组合”。见https://github.com/pytest-dev/pytest/discussions/8304

但是,目前pytest不支持。