预期行为: 1次测试通过
实际行为:从doctest.py引发ValueError异常。
我尝试使用b'\x00'文字也有相同的结果。 如何在doctest中使用空字节? 究竟是什么问题,是否有任何修复或不太丑陋的解决方法?
import hashlib def my_function(bytes_): """ >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest() if __name__ == "__main__": import doctest doctest.testmod()Expected behaviour: 1 test passes
Actual behaviour: ValueError exception is raised from within doctest.py.
I've tried to use b'\x00' literal as well with the same result. How to use null bytes in doctest? What exactly is the problem here, and is there any fix or not-too-ugly workaround?
最满意答案
你的doctest正在进行双重解析。 首先,Python应用反斜杠处理将\0转换为docstring本身的空字节,然后doctest尝试在>>>之后运行事物作为Python代码并遇到错误,因为已经应用了反斜杠处理。
对于只是尝试打印文档字符串或尝试调用函数help人来说,这也是一个问题。
与正则表达式一样,要避免第一层反斜杠处理,请使用原始字符串表示法:
def my_function(bytes_): r""" >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest()Your doctest is getting double-parsed. First, Python applies backslash processing to convert \0 to a null byte in the docstring itself, and then doctest tries to run the thing after the >>> as Python code and encounters an error because backslash processing has already been applied.
This would also be a problem for anyone just trying to print your docstring, or trying to call help on your function.
As with regexes, to avoid the first layer of backslash processing, use raw string notation:
def my_function(bytes_): r""" >>> my_function(b'\0') '6e340b9cffb37a989ca544e6bb780a2c78901d3fb33738768511a30617afa01d' """ return hashlib.sha256(bytes_).hexdigest()更多推荐
发布评论