Patch method only in one module
<p>For example, I have some module(<code>foo.py</code>) with next code:</p>

<pre><code>import requests

def get_ip():
    return requests.get('http://jsonip.com/').content
</code></pre>

<p>And module <code>bar.py</code> with similiar code:</p>

<pre><code>import requests

def get_fb():
    return requests.get('https://fb.com/').content
</code></pre>

<p>I just can't understand why next happens:</p>

<pre><code>from mock import patch

from foo import get_ip
from bar import get_fb

with patch('foo.requests.get'):
    print(get_ip())
    print(get_fb())
</code></pre>

<p>They are two mocked:
<code>
&lt;MagicMock name='get().content' id='4352254472'&gt;
&lt;MagicMock name='get().content' id='4352254472'&gt;
</code>
It is seemed to patch only <code>foo.get_ip</code> method due to <code>with patch('foo.requests.get')</code>, but it is not.
I know that I can just get <code>bar.get_fb</code> calling out of <code>with</code> scope, but there are cases where I just run in context manager one method that calls many other, and I want to patch <code>requests</code> only in one module.
Is there any way to solve this? Without changing imports in module</p>

<p>Not to steal <strong>@Neapolitan</strong>'s thunder, but another option would be to simply mock <code>foo.requests</code> instead of <code>foo.requests.get</code>:</p>

<pre><code>with patch('foo.requests'):
    print(get_ip())
    print(get_fb())
</code></pre>

<p>I think the reason why both methods get mocked in your case is that, since <code>requests.get</code> is not explicitly imported in <code>foo.py</code>, <code>mock</code> will have to look up the method in the <code>requests</code> module and mock it there, rather than mocking it in the <code>requests</code> object already imported into <code>foo</code>, so that when <code>bar</code> later imports <code>requests</code> and accesses <code>requests.get</code> it is geting the mocked version. However, if you <code>patch</code> <code>foo.requests</code> instead, you are just patching the module object already imported into <code>foo</code>, and the original <code>requests</code> module will not be affected.</p>

<p>Although not particularly helpful for this particular problem, <a href="https://docs.python.org/3/library/unittest.mock.html#where-to-patch" rel="nofollow">this article</a> is very useful for understanding the subtleties of <code>patch</code></p>

python python-3.x python-unittest python-mock python-unittest.mock