2011-11-14 34 views
5

假設我有以下代碼:文檔測試嵌套文檔字符串

def foo(s): 
    """A dummy function foo. For example: 

>>> a = '''This is a test string line 1 
This is a test string line 2 
This is a test string line 3''' 
>>> foo(a) 
This is a test string line 1 
This is a test string line 2 
This is a test string line 3 
>>> 
    """ 
    print s 

if __name__ == '__main__': 
    import doctest 
    doctest.testmod() 

而且讓我們將它保存爲foo.py.當我運行:

C:\Python27>python.exe foo.py 
********************************************************************** 
File "foo.py", line 5, in __main__.foo 
Failed example: 
    a = '''This is a test string line 1 
Exception raised: 
    Traceback (most recent call last): 
     File "C:\Python27\lib\doctest.py", line 1254, in __run 
     compileflags, 1) in test.globs 
     File "<doctest __main__.foo[0]>", line 1 
     a = '''This is a test string line 1 
             ^
    SyntaxError: EOF while scanning triple-quoted string literal 
********************************************************************** 
File "foo.py", line 8, in __main__.foo 
Failed example: 
    foo(a) 
Exception raised: 
    Traceback (most recent call last): 
     File "C:\Python27\lib\doctest.py", line 1254, in __run 
     compileflags, 1) in test.globs 
     File "<doctest __main__.foo[1]>", line 1, in <module> 
     foo(a) 
    NameError: name 'a' is not defined 
********************************************************************** 
1 items had failures: 
    2 of 2 in __main__.foo 
***Test Failed*** 2 failures. 

試過縮進的文檔字符串(>>> A =「」「...‘’」都檢查過了縮進 - 4個空格每個縮進。),改變了單引號雙引號(>>> a =「」「....」「」),錯誤是不同的,doctest不會成功。目前唯一的工作是將所有行連接到極長的字符串,並用'\ r \ n'分隔。

我想念什麼?

回答

9

我認爲你需要把一些點有

>>> a = """This is a test string line 1 
... This is a test string line 2 
... This is a test string line 3""" 
+0

雖然我不能拇指向上(需要15聲望),感謝您的回答。你的答案完美無缺。 – user1045217

+1

我只想提及** doctest **需要用雙*引號引用。答案是** docstring **被引用*單*報價。我在單引號中引用了doctest的引用,但我無法弄清楚它爲什麼不起作用。 – Forethinker

+0

@Forethinker:謝謝!順便說一句,這個網站是合作編輯的,當你看到一個明顯的錯誤時,隨時編輯帖子並糾正它。 – georg