使用doctest测试Python代码时出现意外错误

问题描述 投票:0回答:1

我正在使用doctest测试我的代码,并且在测试一个简单的函数时会遇到意外错误,该函数会生成两行文本输出。为什么?

Ubuntu 18.04上的Python 3.6.9。使用Python 2.7和Python 3.9可以观察到相同的错误。

测试程序(保存为doctest-bugs.py):

#!/usr/bin/env python3

def testme():
    """
    Emit test message.

    >>> testme()
    First line (no leading spaces)
     Second line (one leading space)
    """
    return """First line (no leading spaces)
 Second line (one leading space)"""

常规运行:

$ python3 doctest-bugs.py

使用doctest进行测试:

$ python3 -m doctest doctest-bugs.py 
**********************************************************************
File "/home/filip/doctest-bugs.py", line 7, in doctest-bugs.testme
Failed example:
    testme()
Expected:
    First line (no leading spaces)
     Second line (one leading space)
Got:
    'First line (no leading spaces)\n Second line (one leading space)'
**********************************************************************
1 items had failures:
   1 of   1 in doctest-bugs.testme
***Test Failed*** 1 failures.

所有字符串都是逐字记录的,根据模块文档,应识别单个前导空格而不会出现任何问题。

python python-3.x doctest
1个回答
0
投票

该函数不会产生两行输出;它返回一个包含两行的字符串。

>>> testme()
'First line (no leading spaces)\n Second line (one leading space)'

也许您对返回打印感到困惑。

>>> print(testme())
First line (no leading spaces)
 Second line (one leading space)

这是一个有效的示例:

def testme():
    """
    >>> testme()
    'First line (no leading spaces)\\n Second line (one leading space)'
    >>> print(testme())
    First line (no leading spaces)
     Second line (one leading space)
    """
    return """First line (no leading spaces)
 Second line (one leading space)"""
© www.soinside.com 2019 - 2024. All rights reserved.