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

时间:2019-08-15 16:20:47

标签: python-3.x types mocking identity

我的代码:

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不是吗?

1 个答案:

答案 0 :(得分:2)

如果看到它具有的Mock类

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

它显然提到在运行时使用新类创建了一个新实例,因此一个Mock不会干扰其他实例。这就是为什么看到id不同的原因,因为对象的实际类是在运行时生成的