为什么模拟的类型与模拟不匹配?

Why the type of a mock does not match Mock?

我的代码:

from datetime import datetime
from unittest.mock import Mock

a = datetime.now()
print(id(type(a)))
print(id(datetime))

b = Mock()
print(id(Mock))
print(id(type(b)))

输出:

$ python3 foo.py
4477748792
4477748792
140351771879768
140351771828664

为什么type(a)datetime一样?但是 type(b)Mock 不是吗?

如果你看到 Mock class 它有

class Mock(CallableMixin, NonCallableMock):

现在如果你探索 NonCallableMock

class NonCallableMock(Base):
    """A non-callable version of `Mock`"""

    def __new__(cls, *args, **kw):
        # every instance has its own class
        # so we can create magic methods on the
        # class without stomping on other mocks
        new = type(cls.__name__, (cls,), {'__doc__': cls.__doc__})
        instance = object.__new__(new)
        return instance

它清楚地提到在 运行 时使用新的 class 创建了一个新实例,因此一个 Mock 不会干扰其他。这就是您看到 id 不同的原因,因为对象的实际 class 是在 运行 时间

生成的