Keep variables inside test class for next test in pytest

Viewed 513

I would like to structure my pytests in a class to test a pipeline where I load and modify the data. To do so I created something like the below example. But the second test fails because self.data is still None.

class TestClass:
    data = None

    def test_load_data(self):
        self.data = [1, 2, 3]
        assert isinstance(self.data, list)

    def test_modify_data(self):
        self.data.append(4)
        assert len(self.data) is 4

Why is this not working and how do I pass the content of one test to another?

1 Answers

So if you have the same problem, this is how I solved it according to the comment of @MrBean Bremen:

class TestClass:
    data = None

    def test_load_data(self):
        self.__class__.data = [1, 2, 3]
        assert isinstance(self.data, list)

    def test_modify_data(self):
        self.__class__.data.append(4)
        assert len(self.data) is 4

Make sure that you think about if it really is best practice for you, to reuse and change variables over multiple tests.

Related