How to share the same instance for all methods of a pytest test class

雨燕双飞 提交于 2021-02-18 06:47:27

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/45371832/how-to-share-the-same-instance-for-all-methods-of-a-pytest-test-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!