autodoc: Add a helper that checks the object is mocked; ismock()

This commit is contained in:
Takeshi KOMIYA
2020-12-28 21:26:22 +09:00
parent 7ae7eab65d
commit 476169284d
2 changed files with 39 additions and 1 deletions

View File

@@ -17,6 +17,7 @@ from types import FunctionType, MethodType, ModuleType
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__)
@@ -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__'):
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

View File

@@ -15,7 +15,7 @@ from typing import TypeVar
import pytest
from sphinx.ext.autodoc.mock import _MockModule, _MockObject, mock
from sphinx.ext.autodoc.mock import _MockModule, _MockObject, ismock, mock
def test_MockModule():
@@ -129,3 +129,19 @@ def test_mock_decorator():
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