How to redefine MagicMock __str__ method?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
I'm trying to autogenerate documentation for 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
Return type: <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
.
What should I do to properly isolate dependencies for documentation generation, and make that documentation readable?
python python-sphinx python-mock read-the-docs
add a comment |
I'm trying to autogenerate documentation for 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
Return type: <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
.
What should I do to properly isolate dependencies for documentation generation, and make that documentation readable?
python python-sphinx python-mock read-the-docs
In this context, a mock is an object that pretends to be a module, so that it can be imported, but it doesn’t actually do anything, and cannot be documented like 'real' modules. Note also that you are best off adding the mocks to conf.py, see also blog.rtwilson.com/…
– ElToro1966
Jan 3 at 16:00
@ElToro1966 I don't want it to be documented, I want references to it to not look like<MagicMock id=‘140517266915680’>
I found unfinished PR to Sphinx that fixes this github.com/sphinx-doc/sphinx/pull/5394, but not yet able to figure out how it works.
– Bunyk
Jan 3 at 16:44
add a comment |
I'm trying to autogenerate documentation for 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
Return type: <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
.
What should I do to properly isolate dependencies for documentation generation, and make that documentation readable?
python python-sphinx python-mock read-the-docs
I'm trying to autogenerate documentation for 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
Return type: <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
.
What should I do to properly isolate dependencies for documentation generation, and make that documentation readable?
python python-sphinx python-mock read-the-docs
python python-sphinx python-mock read-the-docs
edited Jan 3 at 15:16
Bunyk
asked Jan 3 at 11:04
BunykBunyk
4,12732450
4,12732450
In this context, a mock is an object that pretends to be a module, so that it can be imported, but it doesn’t actually do anything, and cannot be documented like 'real' modules. Note also that you are best off adding the mocks to conf.py, see also blog.rtwilson.com/…
– ElToro1966
Jan 3 at 16:00
@ElToro1966 I don't want it to be documented, I want references to it to not look like<MagicMock id=‘140517266915680’>
I found unfinished PR to Sphinx that fixes this github.com/sphinx-doc/sphinx/pull/5394, but not yet able to figure out how it works.
– Bunyk
Jan 3 at 16:44
add a comment |
In this context, a mock is an object that pretends to be a module, so that it can be imported, but it doesn’t actually do anything, and cannot be documented like 'real' modules. Note also that you are best off adding the mocks to conf.py, see also blog.rtwilson.com/…
– ElToro1966
Jan 3 at 16:00
@ElToro1966 I don't want it to be documented, I want references to it to not look like<MagicMock id=‘140517266915680’>
I found unfinished PR to Sphinx that fixes this github.com/sphinx-doc/sphinx/pull/5394, but not yet able to figure out how it works.
– Bunyk
Jan 3 at 16:44
In this context, a mock is an object that pretends to be a module, so that it can be imported, but it doesn’t actually do anything, and cannot be documented like 'real' modules. Note also that you are best off adding the mocks to conf.py, see also blog.rtwilson.com/…
– ElToro1966
Jan 3 at 16:00
In this context, a mock is an object that pretends to be a module, so that it can be imported, but it doesn’t actually do anything, and cannot be documented like 'real' modules. Note also that you are best off adding the mocks to conf.py, see also blog.rtwilson.com/…
– ElToro1966
Jan 3 at 16:00
@ElToro1966 I don't want it to be documented, I want references to it to not look like
<MagicMock id=‘140517266915680’>
I found unfinished PR to Sphinx that fixes this github.com/sphinx-doc/sphinx/pull/5394, but not yet able to figure out how it works.– Bunyk
Jan 3 at 16:44
@ElToro1966 I don't want it to be documented, I want references to it to not look like
<MagicMock id=‘140517266915680’>
I found unfinished PR to Sphinx that fixes this github.com/sphinx-doc/sphinx/pull/5394, but not yet able to figure out how it works.– Bunyk
Jan 3 at 16:44
add a comment |
1 Answer
1
active
oldest
votes
It because MagicMock uses _mock_methods
and _mock_unsafe
attributes, but Mock doesn't (seems).
I use 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.
Result:
_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z
Yes! After I also added__mro_entries__
to list of exceptions for__getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)
– Bunyk
Jan 3 at 17:24
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54021062%2fhow-to-redefine-magicmock-str-method%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
It because MagicMock uses _mock_methods
and _mock_unsafe
attributes, but Mock doesn't (seems).
I use 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.
Result:
_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z
Yes! After I also added__mro_entries__
to list of exceptions for__getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)
– Bunyk
Jan 3 at 17:24
add a comment |
It because MagicMock uses _mock_methods
and _mock_unsafe
attributes, but Mock doesn't (seems).
I use 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.
Result:
_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z
Yes! After I also added__mro_entries__
to list of exceptions for__getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)
– Bunyk
Jan 3 at 17:24
add a comment |
It because MagicMock uses _mock_methods
and _mock_unsafe
attributes, but Mock doesn't (seems).
I use 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.
Result:
_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z
It because MagicMock uses _mock_methods
and _mock_unsafe
attributes, but Mock doesn't (seems).
I use 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.
Result:
_mock_methods
_mock_methods
x
y
_mock_methods
z
_mock_methods
_mock_methods
x.y.z
answered Jan 3 at 17:03


ValijonValijon
2,09121743
2,09121743
Yes! After I also added__mro_entries__
to list of exceptions for__getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)
– Bunyk
Jan 3 at 17:24
add a comment |
Yes! After I also added__mro_entries__
to list of exceptions for__getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)
– Bunyk
Jan 3 at 17:24
Yes! After I also added
__mro_entries__
to list of exceptions for __getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)– Bunyk
Jan 3 at 17:24
Yes! After I also added
__mro_entries__
to list of exceptions for __getattr__
redefinition it started to work! (Sphinx wanted to get some data from there, and wanted it to be a tuple)– Bunyk
Jan 3 at 17:24
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54021062%2fhow-to-redefine-magicmock-str-method%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
In this context, a mock is an object that pretends to be a module, so that it can be imported, but it doesn’t actually do anything, and cannot be documented like 'real' modules. Note also that you are best off adding the mocks to conf.py, see also blog.rtwilson.com/…
– ElToro1966
Jan 3 at 16:00
@ElToro1966 I don't want it to be documented, I want references to it to not look like
<MagicMock id=‘140517266915680’>
I found unfinished PR to Sphinx that fixes this github.com/sphinx-doc/sphinx/pull/5394, but not yet able to figure out how it works.– Bunyk
Jan 3 at 16:44