pytest:如何不运行参数化类方法的所有测试组合?

2024-04-29 10:34:53 发布

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

我有一个测试类,在所有方法中都有参数化。我还想用其他变量参数化一些方法。然而,我不想运行所有的组合(因为它们中的一些总是会失败)

考虑如下:

@pytest.mark.parametrize("base_url", ["api/v1/actions/", "api/v1/quotes/"])
class TestAPIResponse:

    @pytest.mark.parametrize("api_verbose_name", ["ação", "declaração"])
    def test_example(self, api_client, base_url, api_verbose_name):
        ...

使用此配置,我们有4个测试:

  1. base_url = "api/v1/actions/"api_verbose_name = "ação"
  2. base_url = "api/v1/quotes/"api_verbose_name = "declaração"
  3. base_url = "api/v1/actions/"api_verbose_name = "declaração"
  4. base_url = "api/v1/quotes/"api_verbose_name = "ação"

如何使test_example仅运行上述第3和第4个测试

现在我正在通过一个helper函数获取api_verbose_name

def get_api_verbose_name(base_url: str) -> str:
    if "quotes" in base_url:
        api_verbose_name = "declaração"
    if "actions" in base_url:
        api_verbose_name = "ação"

    return api_verbose_name


@pytest.mark.parametrize("base_url", ["api/v1/actions/", "api/v1/quotes/"])
class TestAPIResponse:
    
    def test_example(self, api_client, base_url):
        api_verbose_name = get_api_verbose_name(base_url=base_url)
        ...

。。。但这似乎不是我理想的方式

我可以在没有这个helper函数的情况下执行这组测试吗


Tags: nametestactionsapiurlverbosebasepytest
1条回答
网友
1楼 · 发布于 2024-04-29 10:34:53

稍微偏离@AnthonySottile所说的,如果您知道要跳过的端点,可以在对pytest.mark.parametrize的调用中标记它。下面的示例显示了如何利用^{}实现这一点

import pytest


def example(base, api):
    return f"{base}{api}"


@pytest.mark.parametrize("base_url", ["api/v1/actions/", "api/v1/quotes/"])
class TestAPI:
    @pytest.mark.parametrize("api_verbose_name", 
        ["ação", pytest.param("declaração", marks=pytest.mark.skip)]
    )
    def test_example(self, base_url, api_verbose_name):
        result = example(base_url, api_verbose_name)
        assert result == f"{base_url}{api_verbose_name}"

当我们运行测试时,我们可以看到只有两个测试收集了四个测试,因为其余的都被跳过了

collected 4 items                                                                                                                                               

test_foo.py ..ss                                                                                                                                          [100%]

================================================================= 2 passed, 2 skipped in 0.02s ==================================================================

相关问题 更多 >