Skip to content

Commit

Permalink
autodoc: Add a helper that checks the object is mocked; ismock()
Browse files Browse the repository at this point in the history
  • Loading branch information
tk0miya committed Dec 28, 2020
1 parent 7ae7eab commit 4761692
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
22 changes: 22 additions & 0 deletions sphinx/ext/autodoc/mock.py
Expand Up @@ -17,6 +17,7 @@
from typing import Any, Generator, Iterator, List, Sequence, Tuple, Union

from sphinx.util import logging
from sphinx.util.inspect import safe_getattr

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -147,3 +148,24 @@ def mock(modnames: List[str]) -> Generator[None, None, None]:
finally:
sys.meta_path.remove(finder)
finder.invalidate_caches()


def ismock(subject: Any) -> bool:
"""Check if the object is mocked."""
# check the object has '__sphinx_mock__' attribute
if not hasattr(subject, '__sphinx_mock__'):

This comment has been minimized.

Copy link
@jace

jace Jan 7, 2021

This hasattr call has reintroduced the breakage reported in #7516. Merely importing g or request from flask breaks autodoc.

return False

# check the object is mocked module
if isinstance(subject, _MockModule):
return True

try:
# check the object is mocked object
__mro__ = safe_getattr(type(subject), '__mro__', [])
if len(__mro__) > 2 and __mro__[1] is _MockObject:
return True
except AttributeError:
pass

return False
18 changes: 17 additions & 1 deletion tests/test_ext_autodoc_mock.py
Expand Up @@ -15,7 +15,7 @@

import pytest

from sphinx.ext.autodoc.mock import _MockModule, _MockObject, mock
from sphinx.ext.autodoc.mock import _MockModule, _MockObject, ismock, mock


def test_MockModule():
Expand Down Expand Up @@ -129,3 +129,19 @@ class Bar:
assert func.__doc__ == "docstring"
assert Foo.meth.__doc__ == "docstring"
assert Bar.__doc__ == "docstring"


def test_ismock():
with mock(['sphinx.unknown']):
mod1 = import_module('sphinx.unknown')
mod2 = import_module('sphinx.application')

class Inherited(mod1.Class):
pass

assert ismock(mod1) is True
assert ismock(mod1.Class) is True
assert ismock(Inherited) is False

assert ismock(mod2) is False
assert ismock(mod2.Sphinx) is False

0 comments on commit 4761692

Please sign in to comment.