我正在尝试在一个使用null的函数上运行doctest.但是doctest似乎并不喜欢nulls ......
def do_something_with_hex(c):
"""
>>> do_something_with_hex('\x00')
'\x00'
"""
return repr(c)
import doctest
doctest.testmod()
Run Code Online (Sandbox Code Playgroud)
我看到了这些错误
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
**********************************************************************
Run Code Online (Sandbox Code Playgroud)
在这样的测试用例中,我该怎么做才能允许空值?
您可以转义所有反斜杠,或者将文档字符串更改为原始字符串文字:
def do_something_with_hex(c):
r"""
>>> do_something_with_hex('\x00')
'\x00'
"""
return repr(c)
Run Code Online (Sandbox Code Playgroud)
使用r字符串上的前缀,字符串中包含反斜杠后面的字符不会发生更改,并且所有反斜杠都保留在字符串中.