Package Structure:
pqr/pq.py
test.py
pqr/pq.py
has following structure
Where lmn is globally installed pip module
Structure of pq.py
from lmn import Lm
class Ab():
def __init__(self):
self.lm = Lm()
def echo(self, msg):
print msg
test.py
has following structure
from pqr.pq import Ab
How to mock Lm()
class over here so to test all method from Ab class?
It doesn't really matter where Lm
came from. You imported Lm
into the pqr.pq
namespace as a global there, so you'd only have replace that name there and nowhere else. That's because the Ab.__init__
method will look for it 'locally' in it's own module.
So using the mock
library all you need to do is patch the name pqr.pq.Lm
:
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
Also see the Where to patch section of the mock
documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With