如何在开发机器上强制导入错误? (密码模块)
我正在尝试在 Google App Engine 上使用第三方库(docutils),但此代码(在 docutils 中)有问题:
try:
import pwd
do stuff
except ImportError:
do other stuff
我希望导入失败,就像在实际的 GAE 服务器上一样,但问题是它在我的开发盒(ubuntu)上不会失败。鉴于导入不在我自己的代码中,如何使其失败?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
比搞乱
__import__
更简单的是在 sys.modules 字典中插入None
:Even easier than messing with
__import__
is just insertingNone
in the sys.modules dict:在您的测试框架中,在导入 docutils 之前,您可以执行此设置任务:
当然在拆卸中将一切恢复正常:
说明:所有导入操作都经过
__builtin__.__import__
,并且您可以重新分配该名称以使此类操作使用您自己的代码(诸如导入挂钩之类的替代方案更适合从非文件系统源执行导入之类的目的,但对于您这样的目的,可以覆盖__builtin__.__import__
,正如您在上面看到的,提供了真正简单的代码)。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).