1

I followed the answer here and solved my problem of accessing class instance variables in a pytest class by setting them through autouse fixtures.

Code:

import pytest

@pytest.fixture(autouse=True, scope='class')
def setup(request):
    request.cls.number = 4
    request.cls.id = 0


class TestResources(object):

    def test_01(self):
        a = self.number * 4
        assert a == 16
        self.id = a

    def test_02(self):
        assert self.id == 16
        print(self.id)

However, I can access a class varaible set through such method, but can not set another value to it through a test?

In above example, test_02 fails with below assertion error because test_01 fails to set self.a = 16.

E       assert 0 == 16
E        +  where 0 = <test_a.TestResources object at 0x7f918e83da30>.id

I found a workaround where I can add request to the test_01 params and set it again as below, but that kind of beats the purpose of having a class.

    def test_01(self, request):
        a = self.number * 4
        assert a == 16
        request.cls.id = a

Is there a better way to do this?

MohitC
  • 4,541
  • 2
  • 34
  • 55
  • You are setting the _instance_ variable `id` instead of the class variable. You need `self.__class__.id = a` instead. – MrBean Bremen Feb 05 '21 at 05:55
  • @MrBeanBremen, thats what I intend to do, set the class instance variable.. this is how you would do in regular python class right? – MohitC Feb 05 '21 at 09:43
  • There are class variables and instance variables - so I'm not sure what you mean by "class instance variable". What I wrote is the way to set a class variable given an instance (e.g. `self`). – MrBean Bremen Feb 05 '21 at 09:48
  • I mean the instance varaible which you can directly access with `self`, like in this case I am trying to do `self.a`. The fixtures are able to set variables correctly, tests are able to access it using `self` but tests are not able to modify them using `self.` notation. – MohitC Feb 05 '21 at 09:51
  • Ah ok, I misunderstood. No, you can't do this, because for each test, a new instance is created, so you cannot use `self` to transfer data between tests. This can only be done using fixtures or class variables. – MrBean Bremen Feb 05 '21 at 09:54

0 Answers0