Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey patch a function in a module for unit testing

I have the following method in a module that calls another method imported from another module:

def imported_function():
    do_unnecessary_things_for_unittest()

The actual method that needs to be tested, imports and uses the above function:

from somewhere import imported_function

def function_to_be_tested():
    imported_function()
    do_something_more()
    return 42

The inner calls and related calculations inside imported_function are not important and they are not what I want to test so I just want to skip them while testing the actual function function_to_be_tested.

Thus, I tried to monkey patch the module named somewhere inside the test method but no luck.

def test_function_to_be_tested(self):
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True

The question is, how can I monkey patch a method of a module while testing so that it will not be called during the test phase?

like image 910
Ozgur Vatansever Avatar asked Aug 31 '12 07:08

Ozgur Vatansever


People also ask

What is the use of monkey patching in Python?

In Python, the term monkey patch refers to dynamic (or run-time) modifications of a class or module. In Python, we can actually change the behavior of code at run-time. We use above module (monk) in below code and change behavior of func() at run-time by assigning different value.

Why do we need monkey patching?

Monkey patching is a technique used to dynamically update the behavior of a piece of code at run-time. A monkey patch (also spelled monkey-patch, MonkeyPatch) is a way to extend or modify the runtime code of dynamic languages (e.g. Smalltalk, JavaScript, Objective-C, Ruby, Perl, Python, Groovy, etc.)

What is monkey patching in Pytest?

Monkeypatching functionsmonkeypatch can be used to patch functions dependent on the user to always return a specific value. In this example, monkeypatch. setattr is used to patch Path. home so that the known testing path Path("/abc") is always used when the test is run.

What does monkey Patch_all () do?

A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.


1 Answers

I think better to use Mock Library

So you can do something like:

from somewhere import imported_function

@patch(imported_function)
def test_function_to_be_tested(self, imported_function):
    imported_function.return_value = True
    #Your test

I think for unit tests it's better than monkey patch.

like image 171
lyapun Avatar answered Nov 09 '22 09:11

lyapun