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?
question from:
https://stackoverflow.com/questions/66058039/how-to-set-class-instance-variable-of-a-pytest-class 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…