如何根据测试参数正确跳过测试?

2024-05-19 20:27:18 发布

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

我有一个小测试,它使用@pytest.parametrize

import pytest

class TestBla:
    @pytest.mark.parametrize('arg', (True, False))
    def test(self, arg):
        assert arg 

我想跳过False案例,而不是运行并失败,因此我在测试中添加了以下装置:

@pytest.fixture(autouse=True)
def skipper(self, request):
    if request.getfixturevalue('arg') is False:
        pytest.skip()

它非常有效:pytest -s test_skips.py跳过False并传递True

  • 我的问题是:这个fixture依赖于具有'arg'参数的函数如果有人更改了它的名称怎么办?我可以让它更健壮吗

  • 之所以在夹具中而不是在测试本身中执行此跳过,是为了使测试尽可能短,并将所有其他逻辑移到外部这是个坏主意吗?

顺便说一句,我今天知道了


Tags: testimportselffalsetruepytestrequestdef
1条回答
网友
1楼 · 发布于 2024-05-19 20:27:18

要使事情更清晰,您可以做的另一件事是使用特定的标记进行决策,然后从conftest.py中的pytest_runtest_setup hook方法查询标记:

@pytest.mark.supported_browsers('chrome', 'firefox')
def test_try(self):
    # test logic

然后在conftest.py中:

def pytest_runtest_setup(item):
    current_browser = Environment.get().current_browser
    if _has_marker(item=item, marker_name='supported_browsers'):
        supported_browsers_marker_list = _get_marker(item, marker_name='supported_browsers')
        supported_browsers = supported_browsers_marker_list[0].args
        if current_browser not in supported_browsers:
            pytest.skip(f'This test does not support this type browser.')
            return


def _has_marker(item, marker_name: str) -> bool:
    return len(list(item.iter_markers(name=marker_name))) > 0


def _get_marker(item, marker_name) -> typing.Optional[typing.List]:
    if _has_marker(item=item, marker_name=marker_name):
        return list(item.iter_markers(name=marker_name))
    else:
        return None

更多信息可在此处找到: https://docs.pytest.org/en/latest/writing_plugins.html

相关问题 更多 >