Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share 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 the 3 methods are called on 3 different instances of TestXYZ object. Is there anyway to change this behavior and make pytest call all the 3 methods on the same object instance. So that I can use the self to store some values.

like image 224
Rahul Avatar asked Jul 28 '17 11:07

Rahul


1 Answers

Sanju has the answer above in the comment and I wanted to bring attention to this answer and provide an example. In the example below, you use the name of the class to reference the class variables and you can also use this same syntax to set or manipulate values, e.g. setting the value for z or changing the value for y in the test_x() test function.

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
like image 177
wingr Avatar answered Nov 12 '22 11:11

wingr