How to use the same instance for all methods of a pytest test class

I have a simple test class

@pytest.mark.incremental
class TestXYZ:

    def test_x(self):
        print(self)

    def test_y(self):
        print(self)

    def test_z(self):
        print(self)

      

When I run this, I get the following output:

test.TestXYZ object at 0x7f99b729c9b0

test.TestXYZ object at 0x7f99b7299b70

testTestXYZ object at 0x7f99b7287eb8

This indicates that 3 methods are being called on 3 different instances of the TestXYZ object. Anyway, to change this behavior and force pytest to call all 3 methods on the same object instance. So I can use self to store some values.

+3


source to share


1 answer


Sanju has the answer above in the comment and I wanted to draw attention to this answer and give an example. In the example below, you are using a class name to refer to class variables, and you can also use this syntax to set or manipulate values, eg. by setting the value for z

or changing the value for y

in the test function test_x()

.



class TestXYZ():
    # Variables to share across test methods
    x = 5
    y = 10

    def test_x(self):
        TestXYZ.z = TestXYZ.x + TestXYZ.y # create new value
        TestXYZ.y = TestXYZ.x * TestXYZ.y # modify existing value
        assert TestXYZ.x == 5

    def test_y(self):
        assert TestXYZ.y == 50

    def test_z(self):
        assert TestXYZ.z == 15

      

0


source







All Articles