Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest: How to pass a class parameter to setup_class

Tags:

python

pytest

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?

like image 236
user2945303 Avatar asked Nov 01 '13 22:11

user2945303


1 Answers

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

like image 106
prmtl Avatar answered Oct 29 '22 15:10

prmtl