使用 doctest 测试 Python 代码时出现意外错误
Unexpected errors while testing Python code with doctest
我正在使用 doctest 测试我的代码,但在测试一个生成两行文本输出的简单函数时出现意外错误。为什么?
Python 3.6.9 在 Ubuntu 18.04。 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.
所有字符串都是逐字记录的,根据模块文档,应该可以毫无问题地识别单个前导space。
该函数不产生两行输出;它 returns 一个包含两行的字符串。
>>> 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)"""
我正在使用 doctest 测试我的代码,但在测试一个生成两行文本输出的简单函数时出现意外错误。为什么?
Python 3.6.9 在 Ubuntu 18.04。 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.
所有字符串都是逐字记录的,根据模块文档,应该可以毫无问题地识别单个前导space。
该函数不产生两行输出;它 returns 一个包含两行的字符串。
>>> 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)"""