How to mock class used in separate namespace?
<p>Package Structure:</p>

<pre><code>pqr/pq.py
test.py
</code></pre>

<p><code>pqr/pq.py</code> has following structure</p>

<p>Where lmn is globally installed pip module</p>

<p>Structure of <code>pq.py</code></p>

<pre><code>from lmn import Lm

class Ab():

    def __init__(self):
        self.lm = Lm()

    def echo(self, msg):
        print msg
</code></pre>

<p><code>test.py</code> has following structure</p>

<pre><code>from pqr.pq import Ab
</code></pre>

<p>How to mock <code>Lm()</code> class over here so to test all method from Ab class?</p>

<p>It doesn't really matter where <code>Lm</code> came from. You imported <code>Lm</code> into the <code>pqr.pq</code> namespace as a global <em>there</em>, so you'd only have replace that name there and nowhere else. That's because the <code>Ab.__init__</code> method will look for it 'locally' in it's own module.</p>

<p>So using the <a href="https://pypi.python.org/pypi/mock" rel="nofollow"><code>mock</code> library</a> all you need to do is patch the name <code>pqr.pq.Lm</code>:</p>

<pre><code>import mock
from pqr.pq import Ab

with mock.patch('pqr.pq.Lm') as mock_lm:
    # within this block, `Lm` in the `pqr.pq` namespace has been replaced
    # by a mock object
    test_instance = Ab()
    # assert that the patch succeeded; .return_value is used because
    # Ab.__init__ *calls* Lm()
    assert test_instance.lm is mock_lm.return_value
</code></pre>

<p>Also see the <a href="https://docs.python.org/dev/library/unittest.mock.html#where-to-patch" rel="nofollow"><em>Where to patch</em> section</a> of the <code>mock</code> documentation.</p>

python python-2.7 namespaces mocking python-unittest