How to override functions in python?

I got a function in a specific module that I want to override (mock) at runtime for testing. As I understand it, a function definition is nothing more than an assignment in python (the module definition itself is a kind of executable function). As I said, I want to do this when setting up a test case, so the function that needs to be redefined lives in another module. What is the syntax for this? For example, "module1" is my module, and "func1" is my function, in my test script I tried this (without success):

import module1 module1.func1 = lambda x: return True 
+7
python django
source share
5 answers
 import module1 import unittest class MyTest(unittest.TestCase): def setUp(self): # Replace othermod.function with our own mock self.old_func1 = module1.func1 module1.func1 = self.my_new_func1 def tearDown(self): module1.func1 = self.old_func1 def my_new_func1(self, x): """A mock othermod.function just for our tests.""" return True def test_func1(self): module1.func1("arg1") 

Many of the mocking libraries provide tools for this kind of ridicule, you should research them, as you will probably get a lot of help.

+9
source share
 import foo def bar(x): pass foo.bar = bar 
+3
source share

Just assign a new function or lambda to the old name:

 >>> def f(x): ... return x+1 ... >>> f(3) 4 >>> def new_f(x): ... return x-1 ... >>> f = new_f >>> f(3) 2 

It also works when a function belongs to another module:

 ### In other.py: # def f(x): # return x+1 ### import other other.f = lambda x: x-1 print other.f(1) # prints 0, not 2 
+2
source share

Use redef: http://github.com/joeheyming/redef

 import module1 from redef import redef rd_f1 = redef(module1, 'func1', lambda x: True) 

When rd_f1 goes out of scope or is deleted, the func1 function will return to normal operation

+2
source share

If you want to reload the foo.py interpreter file that you are editing, you can make a simple function and use execfile (), but I just found out that it does not work without a global list of all functions (unfortunately) if someone doesn't best idea:

Somewhere in the foo.py file:

 def refoo (): global fooFun1, fooFun2 execfile("foo.py") 

In the python interpreter:

refoo () # Now you have the latest changes from foo.py

+1
source share

All Articles