如何在python doctest结果字符串中包含特殊字符(制表符、换行符)?

2024-06-12 05:01:18 发布

您现在位置:Python中文网/ 问答频道 /正文

给定以下python脚本:

# dedupe.py
import re

def dedupe_whitespace(s,spacechars='\t '):
    """Merge repeated whitespace characters.
    Example:
    >>> dedupe_whitespace(r"Green\t\tGround")  # doctest: +REPORT_NDIFF
    'Green\tGround'
    """
    for w in spacechars:
        s = re.sub(r"("+w+"+)", w, s)
    return s

该函数在python解释器中按预期工作:

$ python
>>> import dedupe
>>> dedupe.dedupe_whitespace('Purple\t\tHaze')
'Purple\tHaze'
>>> print dedupe.dedupe_whitespace('Blue\t\tSky')
Blue    Sky

但是,doctest示例失败,因为在与结果字符串进行比较之前,制表符被转换为空格:

>>> import doctest, dedupe
>>> doctest.testmod(dedupe)

给予

Failed example:
    dedupe_whitespace(r"Green           Ground")  #doctest: +REPORT_NDIFF
Differences (ndiff with -expected +actual):
    - 'Green  Ground'
    ?       -
    + 'Green Ground'

如何在doctest heredoc字符串中编码制表符,以便适当地执行测试结果比较?


Tags: 字符串importreportregreenbluedoctestdedupe
3条回答

是原始的herdoc字符串表示法(r""")实现了这个技巧:

# filename: dedupe.py
import re,doctest
def dedupe_whitespace(s,spacechars='\t '):
    r"""Merge repeated whitespace characters.
    Example:
    >>> dedupe_whitespace('Black\t\tGround')  #doctest: +REPORT_NDIFF
    'Black\tGround'
    """
    for w in spacechars:
        s = re.sub(r"("+w+"+)", w, s)
    return s

if __name__ == "__main__":
    doctest.testmod()

我已经使用docstring的文本字符串表示法来实现这一点:

def join_with_tab(iterable):
    r"""
    >>> join_with_tab(['1', '2'])
    '1\t2'
    """

    return '\t'.join(iterable)

if __name__ == "__main__":
    import doctest
    doctest.testmod()

TL;DR:转义反斜杠,即在未修改的字符串中使用\\n\\t,而不是\n\t

您可能不想让docstrings成为原始的,因为这样就无法使用任何Python字符串转义,包括您可能想要的那些转义。

对于支持使用普通转义的方法,只需转义反斜杠字符转义中的反斜杠,以便在Python对其进行解释之后,它会留下一个文本反斜杠,后跟doctest可以解析的字符。

相关问题 更多 >