【问题标题】:Doctest for nested docstring嵌套文档字符串的 Doctest
【发布时间】:2011-11-14 09:08:26
【问题描述】:

假设我有以下代码:

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'分隔。

我错过了什么吗?

【问题讨论】:

    标签: python doctest docstring


    【解决方案1】:

    我认为您需要在此处添加一些点

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

    【讨论】:

    • 虽然我不能点赞(需要 15 声望),但感谢您的回答。你的答案很完美。
    • 我只想提一下 doctest 需要用 double 引号引起来。答案有 docstring 被引用 single 引号。我用单引号引用了我的 doctest,但我不知道为什么它不起作用。
    • @Forethinker:谢谢!顺便说一句,这个网站是协作编辑的,当您看到明显的错误时,请随时编辑帖子并更正它。
    • @Forethinker 我正好相反;我的 doctest 结果字符串用双引号括起来,而它必须是单引号。
    猜你喜欢
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-04
    相关资源
    最近更新 更多