doctest 忽略省略号后的行首

doctest ignore the front of line after an ellipsis

文档似乎不太清楚如何解决以下问题...

def test():
    """
    >>> import doctest
    >>> doctest.ELLIPSIS_MARKER = '<ignore>'
    >>> import pandas as pd
    >>> raise pd.errors.InvalidIndexError # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
     <ignore>
    <ignore>InvalidIndexError
    """

import doctest
doctest.run_docstring_examples(test, globals())

这可以正常工作,但无法解决 <ignore>InvalidIndexError

前面的通配符
def test():
    """
    >>> import doctest
    >>> doctest.ELLIPSIS_MARKER = '<ignore>'
    >>> import pandas as pd
    >>> raise pd.errors.InvalidIndexError # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
     <ignore>
    pandas.errors.InvalidIndexError
    """

import doctest
doctest.run_docstring_examples(test, globals())

注意 pandas 版本是 1.1.3

参考资料

doctest 需要异常以某种方式查看。来自 the docs:

Each line of the traceback stack (if present) must be indented further than the first line of the example, or start with a non-alphanumeric character. The first line following the traceback header indented the same and starting with an alphanumeric is taken to be the start of the exception detail.

(加粗)

这意味着如果您使 ELLIPSIS_MARKER 以字母数字开头,它将正常工作。这是一个使用 re.error:

的例子
def test():
    """
    >>> import doctest
    >>> doctest.ELLIPSIS_MARKER = 'MODULE.'
    >>> import re
    >>> raise re.error(None) # doctest: +ELLIPSIS
    Traceback (most recent call last):
        ...
    MODULE.error: None
    """
  • 顺便说一句:

    Note that tracebacks are treated very specially. In particular, in the rewritten example, the use of ... is independent of doctest's ELLIPSIS option. The ellipsis in that example could be left out, or could just as well be three (or three hundred) commas or digits, or an indented transcript of a Monty Python skit.

对于上下文,这里有一个使用两个省略号的示例:

def test():
    r"""
    >>> print('foo\nbar\nbaz') # doctest: +ELLIPSIS
    foo
    ...
    ...
    """

也就是说,IGNORE_EXCEPTION_DETAIL 可能是更好的解决方案。 (我自己才知道的。)

When specified, an example that expects an exception passes if an exception of the expected type is raised, even if the exception detail does not match. For example, an example expecting ValueError: 42 will pass if the actual exception raised is ValueError: 3*14, but will fail, e.g., if TypeError is raised.

It will also ignore the module name used in Python 3 doctest reports.

(加粗)

例如:

def test():
    """
    >>> import re
    >>> raise re.error(None) # doctest: +IGNORE_EXCEPTION_DETAIL
    Traceback (most recent call last):
        ...
    error: foobar
    """

请注意,异常模块 异常详细信息在此示例中均被忽略。这是故意的,以显示此解决方案的副作用。