10

我现在尝试了将近两个小时,没有任何运气。

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

try:
    from zope.component import queryUtility  # and things like this
except ImportError:
    # do some fallback operations <-- how to test this?

稍后在代码中:

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

有任何想法吗?

编辑:

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

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

运行测试时:

aatiis@aiur ~/work/ao.shorturl $ ./bin/test --coverage .
Running zope.testing.testrunner.layer.UnitTests tests:
  Set up zope.testing.testrunner.layer.UnitTests in 0.000 seconds.


Error in test /home/aatiis/work/ao.shorturl/src/ao/shorturl/shorturl.txt
Traceback (most recent call last):
  File "/usr/lib64/python2.5/unittest.py", line 260, in run
    testMethod()
  File "/usr/lib64/python2.5/doctest.py", line 2123, in runTest
    test, out=new.write, clear_globs=False)
  File "/usr/lib64/python2.5/doctest.py", line 1361, in run
    return self.__run(test, compileflags, out)
  File "/usr/lib64/python2.5/doctest.py", line 1282, in __run
    exc_info)
  File "/usr/lib64/python2.5/doctest.py", line 1148, in report_unexpected_exception
    'Exception raised:\n' + _indent(_exception_traceback(exc_info)))
  File "/usr/lib64/python2.5/doctest.py", line 1163, in _failure_header
    out.append(_indent(source))
  File "/usr/lib64/python2.5/doctest.py", line 224, in _indent
    return re.sub('(?m)^(?!$)', indent*' ', s)
  File "/usr/lib64/python2.5/re.py", line 150, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "/usr/lib64/python2.5/re.py", line 239, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/usr/lib64/python2.5/sre_compile.py", line 507, in compile
    p = sre_parse.parse(p, flags)
AttributeError: 'NoneType' object has no attribute 'parse'



Error in test BaseShortUrlHandler (ao.shorturl)
Traceback (most recent call last):
  File "/usr/lib64/python2.5/unittest.py", line 260, in run
    testMethod()
  File "/usr/lib64/python2.5/doctest.py", line 2123, in runTest
    test, out=new.write, clear_globs=False)
  File "/usr/lib64/python2.5/doctest.py", line 1351, in run
    self.debugger = _OutputRedirectingPdb(save_stdout)
  File "/usr/lib64/python2.5/doctest.py", line 324, in __init__
    pdb.Pdb.__init__(self, stdout=out)
  File "/usr/lib64/python2.5/pdb.py", line 57, in __init__
    cmd.Cmd.__init__(self, completekey, stdin, stdout)
  File "/usr/lib64/python2.5/cmd.py", line 90, in __init__
    import sys
  File "<doctest shorturl.txt[10]>", line 4, in fakeimport
NameError: global name 'realimport' is not defined

但是,当我从 python 交互式控制台运行相同的代码时,它确实有效。

更多编辑:

我正在使用zope.testing一个测试文件,shorturl.txt其中包含特定于我模块的这一部分的所有测试。首先,我正在导入zope.component可用的模块,以演示和测试通常的用法。没有zope.*包被认为是一种极端情况,所以我稍后会对其进行测试。因此,我必须以某种方式reload()使我的模块zope.*不可用。

到目前为止,我什至尝试在 tempdir 中使用tempfile.mktempdir()和清空zope/__init__.pyand文件,然后将zope/component/__init__.pytempdir 插入到.sys.path[0]zope.*sys.modules

也没有用。

更多编辑:

与此同时,我试过这个:

>>> class NoZope(object):
...     def find_module(self, fullname, path):
...         if fullname.startswith('zope'):
...             raise ImportError
... 

>>> import sys
>>> sys.path.insert(0, NoZope())

它适用于测试套件的命名空间(= 中的所有导入shorturl.txt),但它不在我的主模块中执行,ao.shorturl. 甚至当我reload()它。知道为什么吗?

>>> import zope  # ok, this raises an ImportError
>>> reload(ao.shorturl)    <module ...>

导入zope.interfaces会引发ImportError,因此它不会到达我 import 的部分zope.component,并且它保留在 ao.shorturl 命名空间中。为什么?!

>>> ao.shorturl.zope.component  # why?! 
<module ...>
4

3 回答 3

10

只需将猴子补丁添加到builtins您自己的版本中__import__- 当它识别出在您想要模拟错误的特定模块上调用它时,它可以引发您想要的任何内容。有关详细信息,请参阅文档。大致:

try:
    import builtins
except ImportError:
    import __builtin__ as builtins
realimport = builtins.__import__

def myimport(name, globals, locals, fromlist, level):
    if ...:
        raise ImportError
    return realimport(name, globals, locals, fromlist, level)

builtins.__import__ = myimport

代替...,您可以硬编码name == 'zope.component',或者使用您自己的回调更灵活地安排事情,这可以根据您的特定测试需求在不同情况下按需增加导入,而无需您编写多个__import__类似的函数;-) .

另请注意,如果您使用的是 ,而不是import zope.componentor from zope.component import something,则from zope import componentthename将是'zope''component'然后将是fromlist.

编辑:函数的文档__import__说要导入的名称是builtin(就像在 Python 3 中一样),但实际上你需要__builtins__- 我已经编辑了上面的代码,以便它可以工作。

于 2010-03-20T01:50:03.230 回答
3

这就是我在单元测试中刚刚提到的。

它使用PEP-302 "New Import Hooks"。(警告:PEP-302 文档和我链接的更简洁的发行说明并不完全准确。)

我使用meta_path它是因为它在导入序列中尽可能早。

如果模块已经被导入(在我的例子中,因为早期的单元测试模拟了它),那么有必要在执行reload依赖模块之前从 sys.modules 中删除它。

 # Ensure we fallback to using ~/.pif if XDG doesn't exist.

 >>> import sys

 >>> class _():
 ... def __init__(self, modules):
 ...  self.modules = modules
 ...
 ...  def find_module(self, fullname, path=None):
 ...  if fullname in self.modules:
 ...   raise ImportError('Debug import failure for %s' % fullname)

 >>> fail_loader = _(['xdg.BaseDirectory'])
 >>> sys.meta_path.append(fail_loader)

 >>> del sys.modules['xdg.BaseDirectory']

 >>> reload(pif.index) #doctest: +ELLIPSIS
 <module 'pif.index' from '...'>

 >>> pif.index.CONFIG_DIR == os.path.expanduser('~/.pif')
 True

 >>> sys.meta_path.remove(fail_loader)

pif.index 中的代码如下所示:

try:
    import xdg.BaseDirectory

    CONFIG_DIR = os.path.join(xdg.BaseDirectory.xdg_data_home, 'pif')
except ImportError:
    CONFIG_DIR = os.path.expanduser('~/.pif')

要回答为什么新重新加载的模块具有旧加载和新加载的属性的问题,这里有两个示例文件。

第一个是y带有导入失败案例的模块。

# y.py

try:
    import sys

    _loaded_with = 'sys'
except ImportError:
    import os

    _loaded_with = 'os'

第二个是x演示如何在重新加载时为模块留下句柄会影响其属性。

# x.py

import sys

import y

assert y._loaded_with == 'sys'
assert y.sys

class _():
    def __init__(self, modules):
        self.modules = modules
        
    def find_module(self, fullname, path=None):
        if fullname in self.modules:
            raise ImportError('Debug import failure for %s' % fullname)

# Importing sys will not raise an ImportError.
fail_loader = _(['sys'])
sys.meta_path.append(fail_loader)

# Demonstrate that reloading doesn't work if the module is already in the
# cache.

reload(y)

assert y._loaded_with == 'sys'
assert y.sys

# Now we remove sys from the modules cache, and try again.
del sys.modules['sys']

reload(y)

assert y._loaded_with == 'os'
assert y.sys
assert y.os

# Now we remove the handles to the old y so it can get garbage-collected.
del sys.modules['y']
del y

import y

assert y._loaded_with == 'os'
try:
    assert y.sys
except AttributeError:
    pass
assert y.os
于 2010-03-20T19:27:48.503 回答
0

如果您不介意更改程序本身,您还可以将导入调用放在一个函数中并在您的测试中对其进行修补。

于 2015-07-02T18:01:33.953 回答