mirror of
https://github.com/sphinx-doc/sphinx.git
synced 2025-02-25 18:55:22 -06:00
autodoc: Add a helper that checks the object is mocked; ismock()
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user