Search code examples
pythonpytest

Pytest - How to pass an argument to setup_class?


I have some code as shown below. I am getting a too few args error when I run it. I am not calling setup_class explicitly, so not sure how to pass any parameter to it. I tried decorating the method with @classmethod, but still see the same error.

The error that I am seeing is this - E TypeError: setup_class() takes exactly 2 arguments (1 given)

One point to note - If I do not pass any parameter to the class, and pass only cls, then I am not seeing the error.

Any help is greatly appreciated.

I did review these questions question #1 and question #2prior to posting. I did not understand the solutions posted to these questions, or how they would work.

class A_Helper:
    def __init__(self, fixture):
        print "In class A_Helper"

    def some_method_in_a_helper(self):
        print "foo"

class Test_class:
    def setup_class(cls, fixture):
        print "!!! In setup class !!!"
        cls.a_helper = A_Helper(fixture)

    def test_some_method(self):
        self.a_helper.some_method_in_a_helper()
        assert 0 == 0

Solution

  • You get this error because you are trying to mix two independent testing styles that py.test supports: the classical unit testing and pytest's fixtures.

    What I suggest is not to mix them and instead simply define a class scoped fixture like this:

    import pytest
    
    class A_Helper:
        def __init__(self, fixture):
            print "In class A_Helper"
    
        def some_method_in_a_helper(self):
            print "foo"
    
    @pytest.fixture(scope='class')
    def a_helper(fixture):
        return A_Helper(fixture)
    
    class Test_class:
        def test_some_method(self, a_helper):
            a_helper.some_method_in_a_helper()
            assert 0 == 0