我正在尝试对一个使用空值的函数运行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
**********************************************************************我该怎么做才能在这样的测试用例中允许空值?
发布于 2012-03-15 06:11:00
您可以对所有反斜杠进行转义,或者将文档字符串更改为raw string literal
def do_something_with_hex(c):
r"""
>>> do_something_with_hex('\x00')
'\x00'
"""
return repr(c)如果字符串中有r前缀,则反斜杠后面的字符将原封不动地包含在字符串中,而所有反斜杠都保留在字符串中。
发布于 2012-03-15 06:07:29
使用\\x而不是\x。当您编写\x时,Python解释器将其解释为空字节,并且空字节本身被插入到文档字符串中。例如,:
>>> def func(x):
... """\x00"""
...
>>> print func.__doc__ # this will print a null byte
>>> def func(x):
... """\\x00"""
...
>>> print func.__doc__
\x00https://stackoverflow.com/questions/9710987
复制相似问题