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



我有一个简单的测试类

@pytest.mark.incremental
class TestXYZ:
def test_x(self):
print(self)
def test_y(self):
print(self)
def test_z(self):
print(self)

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

测试。TestXYZ 对象在0x7f99b729c9b0

测试。TestXYZ 对象在 0x7f99b7299b70

testTestXYZ 对象在 0x7f99b7287eb8

这表明在 TestXYZ 对象的 3 个不同实例上调用了 3 个方法。无论如何都可以更改此行为并使pytest在同一对象实例上调用所有3个方法。这样我就可以使用 self 来存储一些值。

Sanju 在上面的评论中有答案,我想提请注意这个答案并提供一个例子。在下面的示例中,您可以使用类的名称来引用类变量,也可以使用相同的语法来设置或操作值,例如,在test_x()测试函数中设置z的值或更改y的值。

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

最新更新