Python doctest string escaping issue
سؤال
For this 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'
'''
I'm getting this result:
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'
The test should pass because the strings are equivalent. However, in the "Got:" string it has converted some of the \xHH
escapes into their corresponding ascii characters, but it hasn't done this for the "Expected:" string.
If I change r'''
to '''
at the begging of the docstring, I get this instead:
Failed example:
uuid_hex_to_binary('8ed2d35f-2911-4c10-ad68-587c96b4686e')
Expected:
'???_)L?hX|??hn'
Got:
'\x8e\xd2\xd3_)\x11L\x10\xadhX|\x96\xb4hn'
How can I get the two strings to match up in doctest?
المحلول
Consider this:
>>> '\x8e\xd2\xd3\x5f\x29\x11\x4c\x10\xad\x68\x58\x7c\x96\xb4\x68\x6e'
'\x8e\xd2\xd3_)\x11L\x10\xadhX|\x96\xb4hn'
Characters like '\x5f'
('_'
) have printable ASCII values, so in the repr()
call they get converted to the short form. This isn't what you want, so if you want to compare it with the full version, you will need something like
>>> 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
نصائح أخرى
Whoops, I figured it out 10 seconds after I asked. I got it working like this:
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
'''
لا تنتمي إلى StackOverflow