Mar 25, 2019

Python Monkey Patching

Monkey Patching:
  • Monkey Patching refers to dynamic (run-time) modifications of a class or module
  • A MonkeyPatch is a piece of Python code which extends or modifies other code at runtime
  • The unittest.mock library makes use of monkey patching to replace part of your code under test by mock objects. 
  • It provides functionality for writing clever unittests


### test1.py 
class A: 
    def func(self): 
        print("func() is being called")


### test2.py
from test1 import A

def monkey_func(self): 
     print("monkey_func() is being called...")
   
# Replacing address of "func" with "monkey_func" 
A.func = monkey_func

if __name__ == '__main__':
    obj = A()
  
    # calling function "func" whose address got replaced with "monkey_func()" 
    obj.func() 


Output:

monkey_func() is being called...

No comments:

Post a Comment