如何重新定义 MagicMock __str__ 方法?

How to redefine MagicMock __str__ method?

我正在尝试为 Readthedocs 自动生成文档。我将一些依赖项模拟为 they suggest in FAQ,但是从函数的类型注释中我得到的文档的某些部分看起来像

Return type: <MagicMock id=‘140517266915680’>

这当然是不可接受的。所以我像这样重写了模拟:

from unittest.mock import Mock

class ModuleMock(Mock):
    def __init__(self, path='', *args, **kwargs):
        super().__init__(*args, *kwargs)
        self.path = path

    def __getattr__(self, name):
        return ModuleMock(path=self.path + '.' + name)

    def __repr__(self):
        return self.path

所以我可以

>>> x = ModuleMock('x')
>>> x
x
>>> x.y.z
x.y.z

但是有了这个我得到了例外

  ...
  File "<frozen importlib._bootstrap>", line 906, in _find_spec
  File "<frozen importlib._bootstrap_external>", line 1280, in find_spec
  File "<frozen importlib._bootstrap_external>", line 1246, in _get_spec
TypeError: 'ModuleMock' object is not iterable

当我改为尝试从 MagicMock 继承时,我得到 RecursionError

我应该怎么做才能正确隔离文档生成的依赖关系,并使该文档可读?

因为MagicMock使用了_mock_methods_mock_unsafe属性,但是Mock没有(似乎) . 我用 Python 2.7

正确实施:

from mock import MagicMock

class ModuleMock(MagicMock):
    def __init__(self, path='', *args, **kwargs):
        super(ModuleMock, self).__init__(*args, **kwargs)
        self.path = path

    def __repr__(self):
        return self.path

    def __getattr__(self, name):
        #print(name)
        if name in ('_mock_methods', '_mock_unsafe'):
            return super(ModuleMock, self).__getattr__(name)

        return ModuleMock(self.path + "." + name)


if __name__ == '__main__':
    x = ModuleMock('x')
    print(x)
    print(x.y.z)

因此,如果您在 __getattr__ 中打印属性名称,您可以看到 MagicMock 有多个调用。

结果:

_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z