I am using pytest's parametrize annotations to pass params into a class. I'm able to use the parameters in the test methods, however, I can't figure out how to use the parameters in the setup_class method.
import pytest
params = ['A','B','C']
@pytest.mark.parametrize('n', params)
class TestFoo:
def setup_class(cls):
print ("setup class:TestFoo")
# Do some setup based on param
def test_something(self, n):
assert n != 'D'
def test_something_else(self, n):
assert n != 'D'
I tried adding 'n' as a parameter like the test methods, like this:
def setup_class(cls, n):
print ("setup class:TestFoo")
# Do some setup based on param
Which results in an error:
self = <Class 'TestFoo'>
def setup(self):
setup_class = xunitsetup(self.obj, 'setup_class')
if setup_class is not None:
setup_class = getattr(setup_class, 'im_func', setup_class)
setup_class = getattr(setup_class, '__func__', setup_class)
> setup_class(self.obj)
E TypeError: setup_class() takes exactly 2 arguments (1 given)
Is there some other way of using the parameter in the setup_class method?
You can't.
First, setup_class
is called only once per class, even if there is parametrize
fixture used - class is set up only once.
Second, it is not designed to take any other params than cls
. It will not accept params from paramterize
and other fixtures.
As a solution, you could use a parametrized fixture with "class" scope:
import pytest
params = ['A', 'B', 'C']
@pytest.fixture(
scope="class",
params=params,
)
def n(request):
print('setup once per each param', request.param)
return request.param
class TestFoo:
def test_something(self, n):
assert n != 'D'
def test_something_else(self, n):
assert n != 'D'
For more info look at http://docs.pytest.org/en/latest/fixture.html#fixture-parametrize
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With