Mocking `from foo import *` functions

MRAB google at mrabarnett.plus.com
Sat Jan 10 04:41:21 CET 2009


Silfheed wrote:
> So I'm in the current testing situation:
> 
> sender.py:
> -------------
> def sendEmails():
>    return "I send emails"
> 
> alerter.py:
> -------------
> from sender import *
> def DoStuffAndSendEmails():
>   doStuff()
>   sendEmails()
> 
> I'm trying to write a test fn that will test DoStuffAndSendEmails()
> (as well as it's kin) without actually sending any emails out.  I
> could go through alter alerter so that it does `import sender` and
> then find and replace fn() with sender.fn() so I can just create a
> mock fn fakeSendEmails() and and do something like sender.sendEmails =
> fakeSendEmails, but I'd rather not.
> 
> Anyone know how to test alerter.py with out altering the file?
> 
> 
You could alter sender.py. :-)

Actually, you could have:

alerter.py:
-------------
TEST = False
if TEST:
     from mock_sender import *
else:
     from sender import *


so you're changing alerter.py in only one place, or read the value of 
TEST from a config file.



More information about the Python-list mailing list