【问题标题】:Show result of print function calls in doc-tests在文档测试中显示打印函数调用的结果
【发布时间】:2021-06-15 09:54:53
【问题描述】:

我正在调试文档测试的失败。我使用print() 语句而不是模拟器和断点进行调试。 Doc-tests 似乎抑制了被测函数的stdout

Is there way to only perform the doctests, ignoring print function calls? 提到相反的情况,如何抑制打印函数调用。 Python3 中的行为似乎发生了变化。

一个笨拙的解决方案是将 doc-test 的正文复制到 main(),删除前导尖括号,调试,复制回来,然后迭代。将函数保留在 doc-test 中会更容易。

此命令打印来自 doctest 的扩展输出,而不是来自被测函数的扩展输出:

python3 -m doctest -v module.py 

如何包含被测函数的打印函数调用的输出?

更新

这是一个文档测试的最小示例。

import doctest

def sum(a, b):
    """
    >>> 2 == sum(1, 1)
    True
    >>> n = sum(1, 1)
    >>> 2 == n
    True
    """

    print("Hello world")
    return False  # anything to break the test


doctest.testmod(optionflags=doctest.ELLIPSIS)

结果是:

**********************************************************************
Failed example:
    2 == sum(1, 1)
Expected:
    True
Got:
    Hello world
    False
**********************************************************************
Failed example:
    n = sum(1, 1)
Expected nothing
Got:
    Hello world
**********************************************************************
Failed example:
    2 == n
Expected:
    True
Got:
    False
**********************************************************************

所以代码按预期工作,问题在于编写测试以适应匹配预期和实际打印输出的 doctest 框架。我通常将函数调用分配给一个变量并测试该变量,因此打印不是出现在测试失败中,而是出现在函数调用中(我通常用省略号捕获,即使我在这里不这样做)。一种解决方案是隐藏文档测试的打印输出,并在需要调试时重新打开。

【问题讨论】:

  • 您有正在运行的 doctest 的样本吗?我得到了所有失败测试的输出。
  • 我添加了细节并意识到问题不是我所说的。你能发布一个答案吗,可能取自我的更新?

标签: python doctest


【解决方案1】:

您可以将调试输出写入stderr 而不是stdout

import sys
# for debug statements
print('debugging stuff', file=sys.stderr)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多