我对一个只能接受 Python 2.x 中的 unicode 文本的函数进行了以下测试
def testNonUnicodeInput(self):
""" Test falure on non-unicode input. """
input = "foo".encode('utf-16')
self.assertRaises(UnicodeDecodeError, myfunction, input)
但是,该测试在 Python 3.x 中运行时会失败。我得到:
AssertionError: UnicodeDecodeError not raised by myfunction
我正在尝试弄清楚如何设置一个测试,该测试将继续在 Python 2.x 中运行,但在 Python 3.x 上通过 2to3 运行后也将运行。
我可能应该注意到我在我的函数中执行以下操作以强制使用 unicode:
def myfunction(input):
""" myfunction only accepts unicode input. """
...
try:
source = unicode(source)
except UnicodeDecodeError, e:
# Customise error message while maintaining original trackback
e.reason += '. -- Note: Myfunction only accepts unicode input!'
raise
...
当然,在 Python 3.x 上运行之前,它(连同测试)正在通过 2to3 运行。我想我在 Python 3 上真正想要的是不接受字节字符串,尽管我是通过首先对字符串进行编码来完成的。我没有使用“utf-8”作为编码,因为我知道这是默认设置。
有人对这里的一致性有什么想法吗?
最佳答案
您不必对 Python 3 字符串做任何事情;它们都是 Unicode。只需测试 isinstance(s, str)。或者,如果问题是相反的,您需要使用 bytes.decode()。
好的,一种在 Python 3 和 Python 2 中引起 UnicodeDecodeError
的方法:
python 3:
>>> "foo".encode('utf-16').decode('utf-8')
Traceback (most recent call last):
File "<pyshell#61>", line 1, in <module>
"foo".encode('utf-16').decode('utf-8')
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte
python 2:
>>> "foo".encode('utf-16').decode('utf-8')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\lib\encodings\utf_8.py", line 16, in decode
return codecs.utf_8_decode(input, errors, True)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: unexpected code byte
但不确定 2to3
是否会自动将字符串文字转换为 b"foo"
语法。如果是这样,您只需手动取出 b
,或将其设置为以某种方式忽略它。
关于python - 在 Python 3 中测试 UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6849399/