标签: zope.component

在Python中模拟ImportError

我现在正在尝试这个近两个小时,没有任何运气.

我有一个看起来像这样的模块:

try:
    from zope.component import queryUtility  # and things like this
except ImportError:
    # do some fallback operations <-- how to test this?
Run Code Online (Sandbox Code Playgroud)

稍后在代码中:

try:
    queryUtility(foo)
except NameError:
    # do some fallback actions <-- this one is easy with mocking 
    # zope.component.queryUtility to raise a NameError
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:

亚历克斯的建议似乎不起作用:

>>> import __builtin__
>>> realimport = __builtin__.__import__
>>> def fakeimport(name, *args, **kw):
...     if name == 'zope.component':
...         raise ImportError
...     realimport(name, *args, **kw)
...
>>> __builtin__.__import__ = fakeimport
Run Code Online (Sandbox Code Playgroud)

运行测试时: …

python doctest unit-testing mocking zope.component

7
推荐指数
1
解决办法
3591
查看次数

标签 统计

doctest ×1

mocking ×1

python ×1

unit-testing ×1

zope.component ×1