PyTest: Fixture Class setup and teardown


In case you are using test classes then you can use another 2 pairs of functions, well actually methods, to setup and teardown the environment. In this case it is much easier to pass values from the setup to the test functions and to the teardown function, but we need to write the whole thing in OOP style.

Also note, the test functions are independent. They all see the atributes set in the setup_class, but the test functions cannot pass values to each other.


examples/pytest/test_class.py
class TestClass():
    def setup_class(self):
        print("setup_class called once for the class")
        print(self)
        self.db = "mydb"
        self.test_counter = 0

    def teardown_class(self):
        print(f"teardown_class called once for the class {self.db}")

    def setup_method(self):
        self.test_counter += 1
        print(f"  setup_method called for every method {self.db} {self.test_counter}")
        print(self)

    def teardown_method(self):
        print(f"  teardown_method called for every method {self.test_counter}")


    def test_one(self):
        print("    one")
        assert True
        print("    one after")

    def test_two(self):
        print("    two")
        assert False
        print("    two after")

    def test_three(self):
        print("    three")
        assert True
        print("    three after")