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>For testing, you can use the <code>mock</code> module (standard in newer python 3, downloadable from pypi for older versions) to create "fake" classes.  There is a great article on the mock library that explains how to do this, which I will link <a href="https://www.toptal.com/python/an-introduction-to-mocking-in-python" rel="nofollow">here</a>, that helped me a lot.  You will want your test.py file to look something like the code below.</p>

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

class TestLm(unittest.Testcase):

    @mock.patch(pq.LM)
    def test_lm(self, mock_lm):
        my_ab = pq.AB()
        my_ab.echo()
</code></pre>

<p>Using the <code>mock</code> module, you can create a mock version of a module/class that you can use for testing methods, simply by "patching" it in with a decorator above your test method.  This replaces the original version of the specified module/class with a MagicMock object, that is then passed into the test method as a second argument.  This MagicMock does not actually execute any functionality of <code>Lm</code>, but allows you to make assertions about how it is supposed to work. You can override functionality later, should you need to.  However, there is a catch, which is explained in the guide I linked.  You need to make sure that you import <code>Lm</code> <strong>from the module in which it is used, not in the traditional manner.</strong>  For imports, Python creates module objects that are specific to the module they are imported into, so you need to mock the specific <code>Lm</code> object from the <code>pq</code> module in order to test its functionality.  The library is a little complicated to use at first, and contains far more information than is appropriate to cover in a single StackOverflow answer, so I would recommend doing some reading.</p>

<p>Documentation for the <code>mock</code> module can be found <a href="https://docs.python.org/dev/library/unittest.mock.html" rel="nofollow">here</a>. 
The download for the Python 2.7 version can be found <a href="https://pypi.python.org/pypi/mock" rel="nofollow">here</a>.</p>

<p>I am fairly new to the <code>mock</code> library myself, so feel free to correct me if I'm wrong!</p>

<p>EDIT: Upon seeing Martijn's answer, I realized I forgot parenthesis in the my_ab constructor!</p>

python python-2.7 namespaces mocking python-unittest