8

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.

Rahul
  • 177
  • 1
  • 3
  • 12
  • 3
    You can not have `__init__` in test class, so that rules out object variables with `self`, you can make use of class variables to share data across tests or global variables or much better is to have class level fixtures. – Sanju Jul 28 '17 at 11:46
  • @Sanju , yes __init__ is not allowed in test classes. But in my case test_x() will generate some values which will be used by test_y() and test_z(), so i was trying to save it in the self. Is that not possible ? – Rahul Jul 28 '17 at 12:04
  • 3
    As I said before use class variables if you want to share the data. Instead of using self , acces it with class name i.e use `TestXYZ.x` instead of `self.x`, assuming x is the variable you want to use to share data between tests. – Sanju Jul 28 '17 at 14:14
  • assign them to global variables and go from there – Got To Figure Mar 01 '18 at 15:24
  • @Adminy yes I assign them to global variables, but then that beats the purpose of having these tests in a class. – Rahul Mar 27 '18 at 09:33

1 Answers1

6

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
wingr
  • 2,460
  • 24
  • 12