Mocking `from foo import *` functions
Rob Williscroft
rtw at freenet.co.uk
Sat Jan 10 10:19:21 EST 2009
wrote in news:a9ed10ff-d907-46f0-8c6a-
c3d95579a5ab at k1g2000prb.googlegroups.com in comp.lang.python:
> To answer to Rob: yeah, sure that would work, but I always thought
Just to note: you're answering a question about testing, but I
answered how to alter the alerter module *for* testing. given it
was the import * that was causing the OP the problem, I tried to
address that.
> mocking the imported function didn't feel right. The test then depends
> on the import method of the tested module. If you later change your
> mind and decide to use "import sender" and then "sender.sendEmails()",
> you have to change your test code.
You have to add:
import sender
sender.sendEmails = mock_sendEmails
to your test script.
Note that doing the above *before* any other module imports
from sender, will be sufficient in *any* case, though it won't
help if the tested code calls reload( sender ).
No need to scan every imported module for the mocked function.
It also handles the case where other code imports the sender
module and calls sendEmails().
For additional robustness the above can be changed to:
## assert sender module hasn't been imported elsewhere yet
import sys
assert 'sender' not in sys.modules
import sender
sender.sendEmails = mock_sendEmails
Rob.
--
http://www.victim-prime.dsl.pipex.com/
More information about the Python-list
mailing list