I'm trying to use a third-party lib (docutils) on Google App Engine and have a problem with this code (in docutils):
try:
import pwd
do stuff
except ImportError:
do other stuff
I want the import to fail, as it will on the actual GAE server, but the problem is that it doesn't fail on my development box (ubuntu). How to make it fail, given that the import is not in my own code?
In your testing framework, before you cause docutils to be imported, you can perform this setup task:
and of course in teardown put things back to normal:
Explanation: all import operations go through
__builtin__.__import__
, and you can reassign that name to have such operations use your own code (alternatives such as import hooks are better for such purposes as performing import from non-filesystem sources, but for purposes such as yours, overriding__builtin__.__import__
, as you see above, affords truly simple code).Even easier than messing with
__import__
is just insertingNone
in the sys.modules dict: