Wednesday, March 21, 2012

PYTHON: Reimplement imported methods for testing purposes

Spent some time figuring this out, though I'd share. Who knows someone might save some time.

I was trying to write a Django unit test for a method that performs some logic and then sends out several emails by calling the "send_email()" method. For the testing purposes, I wanted to replace the original "send_email()" method with "mock_send_email()". This would have been straightforward, if not for the fact that "send_email()" was not implemented in the tested module itself but in another module imported by it.

Here is what finally worked.

emailutils.send_email = mock_send_email # replace the method 

reload(testedmodule) # reload the module 

from testedmodule import testedmethod # import again 

testedmethod() # run the method 

Hope this helps.