如何在开发机器上强制导入错误? (密码模块)

发布于 2024-08-20 23:11:51 字数 251 浏览 2 评论 0原文

我正在尝试在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

芸娘子的小脾气 2024-08-27 23:11:51

比搞乱 __import__ 更简单的是在 sys.modules 字典中插入 None

>>> import sys
>>> sys.modules['pwd'] = None
>>> import pwd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pwd

Even easier than messing with __import__ is just inserting None in the sys.modules dict:

>>> import sys
>>> sys.modules['pwd'] = None
>>> import pwd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pwd
尬尬 2024-08-27 23:11:51

在您的测试框架中,在导入 docutils 之前,您可以执行此设置任务:

import __builtin__
self.savimport = __builtin__.__import__
def myimport(name, *a):
  if name=='pwd': raise ImportError
  return self.savimport(name, *a)
__builtin__.__import__ = myimport

当然在拆卸中将一切恢复正常:

__builtin__.__import__ = self.savimport

说明:所有导入操作都经过 __builtin__.__import__,并且您可以重新分配该名称以使此类操作使用您自己的代码(诸如导入挂钩之类的替代方案更适合从非文件系统源执行导入之类的目的,但对于您这样的目的,可以覆盖 __builtin__.__import__,正如您在上面看到的,提供了真正简单的代码)。

In your testing framework, before you cause docutils to be imported, you can perform this setup task:

import __builtin__
self.savimport = __builtin__.__import__
def myimport(name, *a):
  if name=='pwd': raise ImportError
  return self.savimport(name, *a)
__builtin__.__import__ = myimport

and of course in teardown put things back to normal:

__builtin__.__import__ = self.savimport

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文