我正在使用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.
所有字符串都是逐字记录的,并且根据模块文档,应该识别单个前导空格而没有任何问题。
答案 0 :(得分:1)
该函数不会产生两行输出;它返回一个包含两行的字符串。
>>> 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)"""