[TIP] Patching __import__

Yoni Tsafir yonix85 at gmail.com
Tue May 24 00:31:37 PDT 2011

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).

My solution for this was the following:

real_import = __import__

def windows_safe_import(name, globals={}, locals={}, fromlist=(), *args,
    if name in ["wmi", "win32api"] or (name == "ctypes" and fromlist is not
None and "windll" in fromlist):
        return MagicMock()

        return real_import(name, globals, locals, fromlist, *args, **kargs)

@patch("__builtin__.__import__", new = windows_safe_import)
class MyTestCase(unittest.TestCase):
# (tested module was imported only inside the test so the problematic
imports it uses won't be imported before we mock the __import__)

Michael suggested 2 alternatives:
    import sys
    sys.modules['wmi'] = MagicMock()

    @patch.dict('sys.modules', {'wmi': MagicMock()})

Then "import wmi" will find your mock. I'm very wary of
overriding __import__ even in tests.

Well, just wanted to update that #1 works well, but #2 causes something
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.
Tried to debug it a bit but no luck...
Any ideas?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20110524/d0595887/attachment.htm>

More information about the testing-in-python mailing list