【问题标题】:How enable ellipsis when calling Python doctest?调用 Python doctest 时如何启用省略号?
【发布时间】:2013-06-10 03:25:04
【问题描述】:

在 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")

【问题讨论】:

    标签: python python-3.x ellipsis doctest


    【解决方案1】:

    您可以将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.
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

        【解决方案3】:

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

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

        doctest directives 文档很难理解,因为实际的指令似乎已被解析并且不可见。为此有一个open bug report。同时您可以查看raw documentation source

        【讨论】:

        • 这个答案是救命稻草,因为它不会改变全局行为,也不需要在您的 doctest 调用中添加额外的设置代码。
        猜你喜欢
        • 2021-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-12
        • 1970-01-01
        相关资源
        最近更新 更多