Skip to content Skip to sidebar Skip to footer

Pytest Teardown_class Is Being Run Too Soon

The Python 'teardown_class' is not behaving as I expect it to. Below is a summary of my code: @classmethod def setup_class(cls): cls.create_table(table1) cls.create_table(t

Solution 1:

Your classmethod misses the cls param:

@classmethoddefcreate_table(some_arg_here):
    """Some code here that creates the table"""

Change it to

@classmethoddefcreate_table(cls, some_arg_here):

I modified your code and added some prints:

classTestClass:

    @classmethoddefsetup_class(cls):
        print("Setting up")
        cls.create_table('table1')
        cls.create_table('table2')
        cls.create_table('table3')

    @classmethoddefcreate_table(cls, some_arg_here):
        print("Creating:", some_arg_here)
        """Some code here that creates the table"""deftest_foo(self):
        print('Running test_foo')
        """Some test code here"""    @classmethoddefteardown_class(cls):
        print("Tearing down")
        """Perform teardown things"""

If you run it with -s you will get the following result:

test.py Setting up
Creating: table1Creating: table2Creating: table3
Running test_foo
.Tearing down

As you can see, everything works as expected. The setup_class is called, tables are created (all 3), test method runs and then teardown_class kicks in.

If you add a function test_bar() you will get:

test.py Setting up
Creating: table1Creating: table2Creating: table3
Running test_foo
.Running test_bar
.Tearing down

Seems also to be fine to me..

Do you have some more hints for your assumption something is wrong?

Solution 2:

I was able to find the solution. I recreated the create_table function as an inner function, inside of the setup function.

@classmethoddefsetup_class(cls):
    defcreate_table(some_arg_here):
       """Some code here that creates the table"""

    create_table(table1)
    create_table(table2)
    create_table(table3)

deftest_foo(self):
    """Some test code here"""@classmethoddefteardown_class(cls):
    """Perform teardown things"""

And now it runs as I expect it to, in this sequence:

  1. Run create_table once for table1 param
  2. Run create_table once for table2 param
  3. Run create_table once for table3 param
  4. Run test_foo
  5. Run teardown_class

It seems that any/every time a function that is outside of setup is called from setup, it causes the teardown function to run directly after the code in the outer function runs, and that was the issue I was facing.

Post a Comment for "Pytest Teardown_class Is Being Run Too Soon"