6

我正在尝试在一个适用于空值的函数上运行 doctest。但是 doctest 似乎不喜欢空值......

def do_something_with_hex(c):
    """
    >>> do_something_with_hex('\x00')
    '\x00'
    """
return repr(c)

import doctest
doctest.testmod()

我看到了这些错误

Failed example:
    do_something_with_hex(' ')
Exception raised:
    Traceback (most recent call last):
      File "C:\Python27\lib\doctest.py", line 1254, in __run
        compileflags, 1) in test.globs
    TypeError: compile() expected string without null bytes
**********************************************************************

我该怎么做才能在这样的测试用例中允许空值?

4

2 回答 2

7

您可以转义所有反斜杠,或者将您的文档字符串更改为原始字符串文字

def do_something_with_hex(c):
    r"""
    >>> do_something_with_hex('\x00')
    '\x00'
    """
    return repr(c)

使用r字符串上的前缀,反斜杠后面的字符将不加更改地包含在字符串中,并且所有反斜杠都保留在字符串中

于 2012-03-14T22:11:00.133 回答
3

使用\\x而不是\x. 当您编写\x时,Python 解释器将其解释为空字节,并且空字节本身被插入到文档字符串中。例如,:

>>> def func(x):
...     """\x00"""
...
>>> print func.__doc__     # this will print a null byte

>>> def func(x):
...     """\\x00"""
...
>>> print func.__doc__
\x00
于 2012-03-14T22:07:29.123 回答