Skip to content
Advertisement

How to mock a function that is not part of any class using monkeypatch in Python?

Consider a function:

def some_function():
    print("some function")

and it’s mock function:

def some_function_dummy():
    print("some function")

How do I mock some_function() function using monkeypath.setattr()?

Something similar to:

monkeypatch.setattr(<class name>, "some_function", dummy_function)

Not sure what <class name> here should be.

Advertisement

Answer

obj should be the current module:

import sys

# Get the current module
this = sys.modules[__name__]

monkeypatch.setattr(this, "some_function", dummy_function)

If some_function is inside another file, you need to import this file to your current module:

import another_file

monkeypatch.setattr(another_file, "some_function", dummy_function)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement