Doctest用于嵌套docstring

use*_*217 6 python doctest docstring

假设我有以下代码:

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()
Run Code Online (Sandbox Code Playgroud)

让我们把它保存为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.
Run Code Online (Sandbox Code Playgroud)

尝试缩进文档字符串(>>> a ='''...''''.检查所有缩进 - 每个缩进4个空格)并将单引号更改为双引号(>>> a =""".. .."""),错误是不同的,doctest不会成功.目前唯一可行的方法是将所有行连接到一个极长字符串并用'\ r \n'分隔.

我错过了什么吗?

geo*_*org 11

我想你需要在那里放一些点

>>> a = """This is a test string line 1
... This is a test string line 2
... This is a test string line 3"""
Run Code Online (Sandbox Code Playgroud)

  • 虽然我不能点赞(需要15声望),但谢谢你的回答。你的答案非常有效。 (2认同)