在 doc-tests

问题描述

我正在调试文档测试的失败。我使用 print() 语句而不是模拟器和断点进行调试。文档测试似乎抑制了被测函数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 框架。我通常将函数调用分配给一个变量并测试该变量,因此打印结果不是在测试失败中而是在函数调用中(我通常用省略号捕捉,即使我在这里不这样做)。一种解决方案是隐藏文档测试的打印输出,并在我需要调试时将其重新打开。

解决方法

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

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