[TIP] Mocking import functions

Mateusz Łoskot mateusz at loskot.net
Sat Feb 8 11:22:49 PST 2014


On 8 February 2014 17:45, Ned Batchelder <ned at nedbatchelder.com> wrote:
> 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,

Thanks for reminding that, I missed this requirement indeed.
In my case, where I used that technique, I import module during TestCase.setUp,
before running individual test cases.

Best regards,
-- 
Mateusz  Łoskot, http://mateusz.loskot.net



More information about the testing-in-python mailing list