单元测试重用 class 继承自 dict 的实例

Unittest reuse class instance inheriting from dict

我遇到了一个奇怪的问题,即 unittest 正在重复使用相同的 class 实例(如果它是从字典继承的)。

我的实际 class 不直接继承自 dict,而是继承自 MutableMapping,行为相同。

import unittest


class MyClass(dict):
    pass


class TestMyClass(unittest.TestCase):
    def test_myclass_1(self):
        mc = MyClass()
        print(id(mc))

    def test_myclass_2(self):
        mc = MyClass()
        print(id(mc))

    def test_myclass_3(self):
        mc = MyClass()
        print(id(mc))

    def test_myclass_4(self):
        mc = MyClass()
        print(id(mc))

那么当运行这个时候,我们可以看到同一个对象实例被重新使用了:

$ python3 -m unittest -v test.py                                                                                                                           
test_myclass_1 (test.TestMyClass) ... 140057337562040
ok
test_myclass_2 (test.TestMyClass) ... 140057337562128
ok
test_myclass_3 (test.TestMyClass) ... 140057337562040
ok
test_myclass_4 (test.TestMyClass) ... 140057337562128
ok

这是怎么回事?

来自 id() 的 python 3 文档:

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

您的测试用例是一个接一个地执行的,这意味着 MyClass 的两个实例是非重叠对象,如文档中所指出的那样,不保证 id 对于这种情况是唯一的。

祝你好运! :)