gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 01:32:07 24 4
gpt4 key购买 nike

我有一个简单的测试类

@pytest.mark.incremental
class TestXYZ:

def test_x(self):
print(self)

def test_y(self):
print(self)

def test_z(self):
print(self)

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

0x7f99b729c9b0 处的 test.TestXYZ 对象

0x7f99b7299b70 处的 test.TestXYZ 对象

0x7f99b7287eb8 处的 testTestXYZ 对象

这表示在 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

关于python - 如何为pytest测试类的所有方法共享同一个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45371832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com