pytest下不报doctest异常输出

doctest exception output not reported under pytest

当 运行在 Pytest 下使用 doctest 时,我遇到了丢失的回溯。 reversible state library 以可逆的方式改变状态,例如这个示例代码:

import sys
from altered import state, forget
with state(sys.modules, shutil=forget):
    import shutil
#  Traceback output....

应该模拟导入问题和崩溃。如果我 运行 它作为我项目根目录中的脚本,我会得到一个回溯:

Traceback (most recent call last):
  ...traceback details...
KeyError: 'shutil'

另一方面,我有一个文档文件,其中包含以下示例的 doctest 格式示例:

>>> import sys
>>> from altered import state, forget
>>> with state(sys.modules, shutil=forget):
...     import shutil
Traceback (most recent call last):
    ...
KeyError: 'shutil'

如果我将示例文件作为 doctested glob 添加到 pytest,pytest 会在 运行ning 时抱怨:

$ py.test docs/examples.rst
============================ test session starts =============================
platform darwin -- Python 2.7.10, pytest-3.0.5, py-1.4.30, pluggy-0.4.0
rootdir: /Users/jacob/src/oss/altered.states, inifile: pytest.ini
collected 1 items

docs/examples.rst F

================================== FAILURES ==================================
[ ... parts of documentation /w doctest ... ]
053
054     >>> import sys
055     >>> from altered import state, forget
056     >>> with state(sys.modules, shutil=forget):
Expected:
    Traceback (most recent call last):
        ...
    KeyError: 'shutil'
Got nothing

会不会是 pytest 的标准输出捕获导致了问题?或者有人看到任何其他明显的故障排除切入点吗?

我曾尝试在我的 doc 文件的 doctest 示例中放置断点,但是步进使我进出 pdb 本身,并且我无法使用该方法对问题做出任何理解。

操作...

我的错误:我似乎对模块导入的工作原理知之甚少!显然,从 sys.modules 中删除模块并不是阻止访问(未导入的)模块的方法(参见 Preventing Python code from importing certain modules?)。

很抱歉打扰您,但感谢您有机会探索防止某些进口的正确方法!

将最上面的代码更改为

import sys
from altered import state
with state(sys.modules, shutil=None):
    import shutil

使一切都按预期运行。

另见 this commit 以供特别好奇。