跳过具有特定参数值的测试

跳过具有特定参数值的测试

本文介绍了Pytest 跳过具有特定参数值的测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些想要参数化的测试,但有些测试应该只应用于参数的一个值.下面举一个具体的例子,我想将参数onetwo应用到test_A,但只提供参数onetest_B.

I have tests that I want to parameterize, but there are certain tests that should only be applied to one value of the parameters. To give a specific example, below, I would like to apply parameters one and two to test_A, but only supply parameter one to test_B.

当前代码

@pytest.fixture(params=['one', 'two'])
def data(request):

    if request.param == 'one'
         data = 5
    return data

def test_A(data):

    assert True

def test_B(data):

    assert True

预期结果

我基本上想要看起来像这样的东西,但我不知道如何在 pytest 中正确编码:

I basically want something that looks like this, but I can't figure out how to code this properly in pytest:

@pytest.fixture(params=['one', 'two'])
def data(request):

    data = 5
    return data

def test_A(data):

    assert True

@pytest.skipif(param=='two')
def test_B(data):

    assert True

推荐答案

根据您的答案,您可以检查输入并调用 pytest.skip() 如果您不希望测试运行.

Building on your answer, you can check the input and call pytest.skip() if you don't want the test to run.

您可以在测试中进行检查:

You can do the check in the test:

def test_A(data):
    assert True

def test_B(data):
    if data.param == 'two':
        pytest.skip()
    assert 'foo' == 'foo'

或者你可以在子类中重新定义测试装置:

Or you could redefine the test fixture in a subclass:

class TestA:
    def test_A(self, data):
        assert True

class TestB:
    @pytest.fixture
    def data(self, data):
        if data.param == 'two':
            pytest.skip()
        return data

    def test_B(self, data):
        assert 'foo' == 'foo'

另一个小建议:您的 Data 类可以替换为命名元组,即

One other minor suggestion: your Data class can be replaced with a namedtuple, i.e.

import collections
Data = collections.namedtuple('Data', 'data, param')

这篇关于Pytest 跳过具有特定参数值的测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:38