如何为 pytest 测试类的所有方法共享相同的实例 [英] How to share the same instance for all methods of a pytest 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 对象在 0x7f99b729c9b0
test.TestXYZ object at 0x7f99b729c9b0
test.TestXYZ 对象在 0x7f99b7299b70
test.TestXYZ object at 0x7f99b7299b70
位于 0x7f99b7287eb8 的 testTestXYZ 对象
testTestXYZ object at 0x7f99b7287eb8
这表明在 TestXYZ 对象的 3 个不同实例上调用了 3 个方法.无论如何要改变这种行为并使 pytest 在同一个对象实例上调用所有 3 个方法.这样我就可以使用 self 来存储一些值.
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.
推荐答案
Sanju 在评论中给出了上述答案,我想引起对该答案的关注并提供一个示例.在下面的示例中,您使用类的名称来引用类变量,您也可以使用相同的语法来设置或操作值,例如在 test_x()
测试函数中设置 z
的值或更改 y
的值.
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
这篇关于如何为 pytest 测试类的所有方法共享相同的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!