Pytest 忽略具有多个参数化的某些参数

问题描述 投票:0回答:1

我想知道是否有任何方法可以跳过下面示例中的参数对:

@pytest.mark.parametrize("foo", [1, 2, 3])
@pytest.mark.parametrize("bar", [4, 5, 6])

这样运行时,总共会有 9 次运行 (1,4; 1,5; 1,6;, 2,4; 2,5; 2;6, 3,4; 3,5; 3 ,6)。我想要完成的是从

foo
运行 1 和 2,并使用
bar
中的每个参数,并在从
bar
运行 3 时忽略
foo
中的 4,以便理想情况下忽略参数对 3,4如果它根本没有出现在测试输出中。

有什么方法可以在 pytest 中实现这一点吗?我知道我可以使用类似的东西:

if foo == 3 and bar == 4:
    pytest.skip("Something")

但是我想知道是否有一种更干净的方法,因为当我想忽略几个参数对时,这可能会变得混乱

python testing automated-tests pytest
1个回答
0
投票

你可以这样做:

import pytest
from itertools import product


@pytest.mark.parametrize(
    "foo, bar",
    [x for x in product([1, 2, 3], [4, 5, 6]) if x not in {(3, 4)}]
)
def test_something_2(foo, bar):
    assert True

您根本不会在输出中看到

(3,4)
的测试:

$ pytest -v

============================= test session starts ==============================
platform linux -- Python 3.11.8, pytest-8.1.1, pluggy-1.4.0 -- /home/lkellogg/tmp/python/.venv/bin/python
cachedir: .pytest_cache
rootdir: /home/lkellogg/tmp/python
collecting ... collected 17 items / 9 deselected / 8 selected

test_things.py::test_something_2[1-4] PASSED                             [ 12%]
test_things.py::test_something_2[1-5] PASSED                             [ 25%]
test_things.py::test_something_2[1-6] PASSED                             [ 37%]
test_things.py::test_something_2[2-4] PASSED                             [ 50%]
test_things.py::test_something_2[2-5] PASSED                             [ 62%]
test_things.py::test_something_2[2-6] PASSED                             [ 75%]
test_things.py::test_something_2[3-5] PASSED                             [ 87%]
test_things.py::test_something_2[3-6] PASSED                             [100%]

======================= 8 passed, 9 deselected in 0.01s ========================

您当然可以将跳过对的列表移动到一个变量中,如果列表增长到超出单个项目,这可能会更干净:

import pytest
from itertools import product

ignored_pairs = {(3, 4)}


@pytest.mark.parametrize(
    "foo, bar",
    [x for x in product([1, 2, 3], [4, 5, 6]) if x not in ignored_pairs]
)
def test_something_2(foo, bar):
    assert True
© www.soinside.com 2019 - 2024. All rights reserved.