簡體   English   中英

使用 doctest 測試 Python 代碼時出現意外錯誤

[英]Unexpected errors while testing Python code with doctest

我正在使用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.

所有字符串都是逐字逐句的,根據模塊文檔,應該可以毫無問題地識別單個前導空格。

該函數不產生兩行輸出; 它返回一個包含兩行的字符串。

>>> 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)"""

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM