Mocking `from foo import *` functions

Rob Williscroft rtw at freenet.co.uk
Sat Jan 10 04:54:20 CET 2009


Silfheed wrote in news:c73b304b-f601-4bb5-89c1-3ee667eeb7d9
@l37g2000vba.googlegroups.com in comp.lang.python:

> 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?

Yes you alter the module *after* you have imported it.

In your test script do:

  def mock_sendEmails():
    pass # or some test code maybe

  # setup ...

  import alerter
  
  # now patch the module
  
  alerter.sendEmails = mock_sendEmails 

  # run the test ...

  DoStuffAndSendEmails()

Because python is dynamic alerter.DoStuffAndSendEmails will call 
the sendEmails in the alerter module that has been replaced with
mock_sendEmails from the test script.

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/



More information about the Python-list mailing list