[TIP] Patching __import__

Michael Foord michael at voidspace.org.uk
Tue May 24 11:16:16 PDT 2011


On 24/05/2011 16:45, Kumar McMillan wrote:
> On Tue, May 24, 2011 at 2:31 AM, Yoni Tsafir<yonix85 at gmail.com>  wrote:
>> Moving a discussion with Michael Foord to TIP so everyone can contribute:
>> I suggested a feature to the mock framework in which you can mock non
>> existing imports (useful when you are unit-testing platform dependent code).
> ...
>>      @patch.dict('sys.modules', {'wmi': MagicMock()})
> ...
>> On PyDev I can run the tests fine, but when I try running them with
>> nosetests, nose doesn't recognize any tests. If I comment out the
>> @patch.dict line, everything works fine.
> Well, you are playing with fire here.  Nose already uses import hooks
> to make test discovery possible within subdirectories that are not
> __init__ modules.  Because of this, it has to alter / restore
> sys.modules before some tests.
Right, but the point is that using patch.dict *isn't* an import hook. It 
only adds (and then removes or restores) that entry from the sys.modules 
dict when the decorated test is executed.

*However*, it does get a reference to the sys.modules dictionary at 
import time (to know which dictionary to patch) - and as the problem is 
happening you're probably right about why. It's just that getting a 
reference to sys.modules is not unusual in Python code, so I don't think 
it is "playing with fire". It is a very odd interaction.

All the best,

Michael Foord

> You could try:
>
> nosetests --debug=nose.importer,nose.inspector,nose.selector
>
> to see if that gives you some clues before / after commenting out the
> @patch.dict line.  You could also try:
>
> nosetests --no-path-adjustment
>
> to turn off the import hooks.
>
>
>> Tried to debug it a bit but no luck...
>> Any ideas?
>> _______________________________________________
>> testing-in-python mailing list
>> testing-in-python at lists.idyll.org
>> http://lists.idyll.org/listinfo/testing-in-python
>>
>>
> _______________________________________________
> testing-in-python mailing list
> testing-in-python at lists.idyll.org
> http://lists.idyll.org/listinfo/testing-in-python


-- 
http://www.voidspace.org.uk/

May you do good and not evil
May you find forgiveness for yourself and forgive others
May you share freely, never taking more than you give.
-- the sqlite blessing http://www.sqlite.org/different.html




More information about the testing-in-python mailing list