Judy T Raj
Judy T Raj

Reputation: 1844

Monkey patch an object from another module in Python

I've a class, say foo, in module 1.

    class foo():
       def __init__(var1, var2):
         self.var1 = var1
         self.var2 = var2
      
      def method1(self):
          pass
      def method2(self):
         pass

foo_ = foo("blah", "blah")

The foo_ object is widely used in various modules across the code base. I've to write a test for a method in module 2 which uses the foo_ object.

Module 2:

from module1 import foo_
import module3
def blah():
   foo_.method1()
   module3.random_method()
   return blah

The random_method in module 3 also imports and calls another method of foo_. I've a dummy foo_ object in my test module.The test is for the blah method. Here's what I've so far.

Test Module:

from module1 import foo
from module2 import blah

@pytest.fixture()
def dummy_foo_():
 var1 = 'blah'
 var2 = 'blah'
 return foo(var1,var2)

def test_blah(dummy_foo_):
 assert blah() == 'blah'

Is there a way I can get the test_blah to work where the blah method would use the dummy foo_ object instead of the one imported in the module 1?

Upvotes: 1

Views: 1631

Answers (1)

Prem Anand
Prem Anand

Reputation: 2537

You can use mock.patch to temporarily patch module1.foo_ with dummy_foo_ by using it as a context manager

from mock import patch
def test_blah(dummy_foo_):
    with patch('module1.foo_', dummy_foo_) as mock:
        assert blah() == 'blah'

Upvotes: 2

Related Questions