Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock class used in separate namespace?

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?

like image 695
Sanket Avatar asked Mar 12 '23 02:03

Sanket


1 Answers

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.

like image 189
Martijn Pieters Avatar answered Mar 20 '23 03:03

Martijn Pieters