Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

python - How to set class instance variable of a pytest class

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...