问题
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
回答1:
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')
回答2:
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'
来源:https://stackoverflow.com/questions/45676648/pytest-skip-test-with-certain-parameter-value