Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytest skip test with certain parameter value

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.

Current Code

@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

Desired Results

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
like image 765
ZachTurn Avatar asked Aug 14 '17 14:08

ZachTurn


2 Answers

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'

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

import collections
Data = collections.namedtuple('Data', 'data, param')
like image 185
Frank T Avatar answered Sep 18 '22 15:09

Frank T


I found a working solution, but I also welcome more solutions as this feels a tad "hacky":

class Data:

    def__init__(self, data, param):
        self.data = data
        self.param = param

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

    data = 5
    return Data(data, request.param)

def test_A(data):

    assert True

def test_B(data):

    if data.param == 'two':
        assert True
    else:
        assert 'foo' == 'foo'
like image 45
ZachTurn Avatar answered Sep 19 '22 15:09

ZachTurn