[英]How to redefine MagicMock __str__ method?
I'm trying to autogenerate documentation for Readthedocs. 我正在尝试自动生成Readthedocs的文档。 I mock some dependencies as they suggest in FAQ , but from type annotations of functions I get some parts of documentation to look like
我在FAQ中建议了一些依赖项,但是从函数的类型注释中我得到了一些文档的部分
Return type: <MagicMock id='140517266915680'>
返回类型:<MagicMock id ='140517266915680'>
Which is of course unacceptable. 这当然是不可接受的。 So I rewritten mock like this:
所以我改写了这样的模拟:
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
So I could do 所以我能做到
>>> x = ModuleMock('x')
>>> x
x
>>> x.y.z
x.y.z
But with this I get exception 但有了这个,我得到了例外
...
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
When I instead try to inherit from MagicMock
, I get RecursionError
. 当我尝试从
MagicMock
继承时,我得到了RecursionError
。
What should I do to properly isolate dependencies for documentation generation, and make that documentation readable? 我该怎么做才能正确隔离文档生成的依赖关系,并使文档可读?
It because MagicMock uses _mock_methods
and _mock_unsafe
attributes, but Mock doesn't (seems). 这是因为MagicMock使用
_mock_methods
和_mock_unsafe
属性,但Mock没有(似乎)。 I use Python 2.7 我使用Python 2.7
Correct implementation: 正确实施:
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)
So if you print attribute name inside __getattr__
, you can see MagicMock has several calls. 因此,如果您在
__getattr__
打印属性名称,则可以看到MagicMock有多个调用。
Result: 结果:
_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.