如何重新定义MagicMock __str__方法?

时间:2019-01-03 11:04:28

标签: python python-sphinx python-mock read-the-docs

我正在尝试为Readthedocs自动生成文档。我将一些依赖项模拟为they suggest in FAQ,但是从函数的类型注释中,我可以得到一些文档外观

  

返回类型:

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

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

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

1 个答案:

答案 0 :(得分:2)

这是因为 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