[TIP] Mocking import functions

Ned Batchelder ned at nedbatchelder.com
Sat Feb 8 09:45:22 PST 2014


On 2/7/14 4:09 PM, Mateusz Łoskot wrote:
> On 7 February 2014 16:07, David Stanek <dstanek at dstanek.com> wrote:
>> Instead of mock.patch('miners.tasks_utils.mechanize_url') you should try
>> mock.patch('twitter_profile.mechanize_url').
> AFAIU, the following can be used as an alternative, can't it?
>
> with mock.patch.dict('sys.modules', {'miners': mock.Mock()}):
>      miners.tasks_utils.mechanize_url.return_value =  content_file.read()
>      ...

This won't help if the module under test has already been imported. If 
it has, then it already has a reference to the module, and replacing it 
in sys.modules won't have any effect.

--Ned.
> Any major differences between the two approaches?
>
> Best regards,




More information about the testing-in-python mailing list