如何在调用Python doctest时启用省略号?

27

在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.

我该怎么做才能启用省略号呢?据我所知,默认情况下它是被禁用的。

我知道在下面的代码中添加# doctest: +ELLIPSIS可以解决这个问题,但我想为所有测试启用省略号。

def foo():
    """
    >>> foo() # doctest: +ELLIPSIS
    hello ...
    """
    print("hello world")
3个回答

29

你可以向testmod方法传递optionflags,但这要求你运行模块本身而不是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.

9
您可以使用以下方法为单个示例启用选项:
'''
>>> 'foobarbaz' # doctest: +ELLIPSIS
'foo...baz'
'''
Doctest指令文档难以理解,因为实际的指令似乎被解析掉了,不可见。这个问题已经有一个未决的错误报告。同时,您可以查看原始文档源

这个答案真是救了我一命,因为它不会改变全局行为,并且在你的doctest调用中也不需要额外的设置代码。 - AutomatedChaos

6

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

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

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

这里是Python文档中有关doctest中选项标记的解释。选项标记可以用于更改doctest如何运行和测试输出。以下是一些常用的选项标记及其作用:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接