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'分隔。
我想念什么?
虽然我不能拇指向上(需要15声望),感谢您的回答。你的答案完美无缺。 – user1045217
我只想提及** doctest **需要用双*引号引用。答案是** docstring **被引用*单*报价。我在单引号中引用了doctest的引用,但我无法弄清楚它为什么不起作用。 – Forethinker
@Forethinker:谢谢!顺便说一句,这个网站是合作编辑的,当你看到一个明显的错误时,随时编辑帖子并纠正它。 – georg