【问题标题】:doctest exception output not reported under pytestpytest下未报告doctest异常输出
【发布时间】:2017-01-11 17:56:27
【问题描述】:

在 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 在运行它时会报错:

$ 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 本身,使用该方法我无法理解问题。

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    运维...

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

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

    把最上面的代码改成

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

    让一切都按预期运行。

    更多好奇请参见thiscommit。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多