我正在尝试自动生成文档以供阅读文档。我将一些依赖项模拟为they suggest in FAQ,但从函数的类型注释可以看出文档的某些部分看起来像
返回类型:
这当然是不能接受的。所以我重写了mock如下:

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不使用(似乎)。
我使用Python2.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

关于python - 如何重新定义MagicMock __str__方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54021062/

10-11 03:08