autodoc a class that extends a mocked class

2019-04-09 00:03发布

问题:

I'm trying to run autodoc over a class that extends an external class.

I've used mock so that the import is accepted.

For that I used what was described in this blog http://blog.rtwilson.com/how-to-make-your-sphinx-documentation-compile-with-readthedocs-when-youre-using-numpy-and-scipy/

import mock

MOCK_MODULES = ['de', 'de.xyz', 'de.xyz.class_that_is_extended']
for mod_name in MOCK_MODULES:
  sys.modules[mod_name] = mock.Mock()

The python file I try to document looks like this: from de.xyz import class_that_is_extended

class extending_class (class_that_is_extended):
'''
  docstring
'''

After running sphinx the result is, that just the class name plus the link to the source is shown.

When I change the line "class extending_class (class_that_is_extended):" to "class extending_class (object):" sphinx/autodoc generates the documentation with docstring.

How can I leave the class as is and still get the docstring in the documentation?

回答1:

Using the apporach posted here: Sphinx-doc :automodule: with Mock imports

I just changed this line:

sys.modules[mod_name] = mock.Mock()

to:

sys.modules[mod_name] = mock.Mock(class_that_is_extended=object)

and removed 'de.xyz.class_that_is_extended' from MOCK_MODULES



回答2:

I met the same problem, and my solution was to return object directly from Mock on attribute access.

from unittest.mock import MagicMock

MOCK_MODULES = [
    # modules to mock
    'kivy.uix.floatlayout',
]

MOCK_CLASSES = [
    # classes you are inheriting from
    "FloatLayout",
]


class Mock(MagicMock):
    @classmethod
    def __getattr__(cls, name):
        if name in MOCK_CLASSES:
            return object
        return MagicMock()


sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)