Mocking submodules in python
<p>I am trying to generate autodocumentation of my project through sphinx. However, I will run the generation of the autodocs in an environment that won't have all the modules I am importing. Hence I would like to mock the import statements.</p>

<p>On <a href="http://read-the-docs.readthedocs.io/en/latest/faq.html" rel="nofollow">http://read-the-docs.readthedocs.io/en/latest/faq.html</a> I found this trick for C modules:</p>

<pre><code>import sys
from unittest.mock import MagicMock

class Mock(MagicMock):
    @classmethod
    def __getattr__(cls, name):
        return Mock()

MOCK_MODULES = ['pygtk', 'gtk', 'gobject', 'argparse', 'numpy', 'pandas']
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
</code></pre>

<p>However mocking getattr does not solve cases like these:</p>

<pre><code>from foo.bar import blah
</code></pre>

<p>that is, when there is a dot [.] involved in the import statement. </p>

<p>Anyone any idea how to get all my imports mocked for a specific list of modules?</p>

<p>The import</p>

<pre><code>from foo.bar import blah
</code></pre>

<p>will look for <code>sys.modules['foo.bar']</code>. Just insert that:</p>

<pre><code>&gt;&gt;&gt; from foo.bar import blah
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ModuleNotFoundError: No module named 'foo'
&gt;&gt;&gt; import sys
&gt;&gt;&gt; from unittest import mock
&gt;&gt;&gt; sys.modules['foo.bar'] = mock.Mock()
&gt;&gt;&gt; from foo.bar import blah
&gt;&gt;&gt; blah
&lt;Mock name='mock.blah' id='4362289896'&gt;
</code></pre>

python python-3.x mocking python-sphinx autodoc