如何为pytest测试类的所有方法共享相同的实例

时间:2017-07-28 11:04:05

标签: python python-2.7 python-3.x pytest

我有一个简单的测试类

@pytest.mark.incremental
class TestXYZ:

    def test_x(self):
        print(self)

    def test_y(self):
        print(self)

    def test_z(self):
        print(self)

当我运行时,我得到以下输出:

test.TestXYZ对象位于0x7f99b729c9b0

test.TestXYZ对象位于0x7f99b7299b70

testTestXYZ对象位于0x7f99b7287eb8

这表示在3个不同的TestXYZ对象实例上调用了3个方法。反正有没有改变这种行为,并使pytest调用同一对象实例上的所有3个方法。这样我就可以使用self来存储一些值。

1 个答案:

答案 0 :(得分: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