嵌套文档字符串的Doctest
假设我有以下代码:
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 = """...."""),但是错误信息不一样,文档测试就是无法成功。目前唯一有效的方法是把所有行合并成一个超长的字符串,并用 '\r\n' 来分隔。
我是不是漏掉了什么?
1 个回答
14
我觉得你需要在那儿加一些点。
>>> a = """This is a test string line 1
... This is a test string line 2
... This is a test string line 3"""