22

在 Python (3.3.2) doctest 中,省略号 ( ...) 可以匹配任何字符串。所以,对于下面的代码

def foo():
    """
    >>> foo()
    hello ...
    """
    print("hello world")

运行 doctest 时不应引发任何错误。但

$ python -m doctest foo.py 
**********************************************************************
File "./foo.py", line 3, in foo.foo
Failed example:
    foo()
Expected:
    hello ...
Got:
    hello world
**********************************************************************
1 items had failures:
   1 of   1 in foo.foo
***Test Failed*** 1 failures.

我必须做什么才能启用省略号?据我所知,默认情况下它是禁用的。

我知道 add # doctest: +ELLIPSIS,如下面的代码所示,可以解决它,但我喜欢为所有测试启用省略号。

def foo():
    """
    >>> foo() # doctest: +ELLIPSIS
    hello ...
    """
    print("hello world")
4

3 回答 3

22

您可以传递optionflags给该testmod方法,但这需要您运行模块本身而不是doctest模块:

def foo():
    """
    >>> foo()
    hello ...
    """
    print("hello world")

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True, optionflags=doctest.ELLIPSIS)

输出:

$ python foo.py
Trying:
    foo()
Expecting:
    hello ...
ok
1 items had no tests:
    __main__
1 items passed all tests:
   1 tests in __main__.foo
1 tests in 2 items.
1 passed and 0 failed.
Test passed.
于 2013-06-13T17:03:26.403 回答
6

您可以为单个示例启用选项,如下所示:

'''
>>> 'foobarbaz' # doctest: +ELLIPSIS
'foo...baz'
'''

doctest指令文档很难理解,因为实际的指令似乎已被解析并且不可见。有一个开放的错误报告。同时,您可以查看原始文档源

于 2020-08-06T08:43:44.213 回答
3

从 Python 3.4 开始,您可以使用以下-o标志传递选项:

$ python -m doctest -o=ELLIPSIS foo.py

来源:https ://docs.python.org/3/library/doctest.html#option-flags

于 2020-06-01T21:34:33.403 回答