Python doctest字符串转义问题

时间:2012-03-26 08:47:59

标签: python doctest

对于这个doctest:

r'''
>>> uuid_hex_to_binary('8ed2d35f-2911-4c10-ad68-587c96b4686e')
'\x8e\xd2\xd3\x5f\x29\x11\x4c\x10\xad\x68\x58\x7c\x96\xb4\x68\x6e'
'''

我得到了这个结果:

Failed example:
    uuid_hex_to_binary('8ed2d35f-2911-4c10-ad68-587c96b4686e')
Expected:
    '\x8e\xd2\xd3\x5f\x29\x11\x4c\x10\xad\x68\x58\x7c\x96\xb4\x68\x6e'
Got:
    '\x8e\xd2\xd3_)\x11L\x10\xadhX|\x96\xb4hn'

测试应该通过,因为字符串是等效的。但是,在“Got:”字符串中,它已将一些\xHH转义符转换为相应的ascii字符,但它没有为“Expected:”字符串执行此操作。

如果我在文档字符串的乞讨时将r'''更改为''',我会改为:

Failed example:
    uuid_hex_to_binary('8ed2d35f-2911-4c10-ad68-587c96b4686e')
Expected:
    '???_)L?hX|??hn'
Got:
    '\x8e\xd2\xd3_)\x11L\x10\xadhX|\x96\xb4hn'

如何在doctest中匹配两个字符串?

2 个答案:

答案 0 :(得分:0)

哎呀,我问过之后10秒就知道了。我得到了这样的工作:

r'''
>>> a = uuid_hex_to_binary('8ed2d35f-2911-4c10-ad68-587c96b4686e')
>>> b = '\x8e\xd2\xd3\x5f\x29\x11\x4c\x10\xad\x68\x58\x7c\x96\xb4\x68\x6e'
>>> a == b
True
'''

答案 1 :(得分:0)

考虑一下:

>>> '\x8e\xd2\xd3\x5f\x29\x11\x4c\x10\xad\x68\x58\x7c\x96\xb4\x68\x6e'
'\x8e\xd2\xd3_)\x11L\x10\xadhX|\x96\xb4hn'

'\x5f''_')等字符具有可打印的ASCII值,因此在repr()调用中,它们会转换为缩写形式。这不是你想要的,所以如果你想把它与完整版比较,你需要像

这样的东西
>>> uuid_hex_to_binary('8ed2d35f-2911-4c10-ad68-587c96b4686e') == \
... '\x8e\xd2\xd3\x5f\x29\x11\x4c\x10\xad\x68\x58\x7c\x96\xb4\x68\x6e'
True