[英]assertRaisesRegexp does work with unicode in Python2
嗨,我注意到assertRaisesRegexp在Python 2.7上不適用於unicode。 我正在嘗試運行以下代碼
import unittest
def raise_exception():
raise Exception(u'\u4e2d\u6587')
class TestUnicode(unittest.TestCase):
def test_test1(self):
with self.assertRaisesRegexp(Exception, u'\u4e2d\u6587'):
raise_exception()
if __name__ == '__main__':
unittest.main()
但是出現了以下錯誤
Traceback (most recent call last):
File "C:\ZChenCode\unicode.py", line 27, in test_test1
raise_exception()
File "C:\Python27\ArcGIS10.3\Lib\unittest\case.py", line 127, in __exit__
if not expected_regexp.search(str(exc_value)):
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
看起來Python標准庫正在嘗試將Unicode字符串轉換為導致錯誤的str類型。 如果我使用assertRaiseRegx,則此函數在Python3上效果很好,沒有unicode問題。 關於如何使其在Python2中起作用的任何建議?
我在這里遇到了同樣的問題,不幸的是我也無法解決,但是我為此做了一個工作,就我而言,我將我的throw Exception更改為:
raise Exception(u'\中\文'.encode('utf8'))
這在這里對我有用...
還有另一種方法,使str(exc_value)
起作用:
class UnicodeMsgException(Exception):
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return self.message
如果您顯式傳遞一個regexp對象,它似乎會更好地工作:
with self.assertRaisesRegexp(Exception, re.compile(u'\u4e2d\u6587')):
assertRaisesRegexp的文檔建議您只要傳入一個字符串即可,只要它可以用作正則表達式即可,但至少對於我使用的python版本– 2.7.8 –似乎已損壞。
您可以編寫一個支持Unicode的新斷言方法:
def assertRaisesRegexpUnicode(self, expected_exception, expected_regexp, callable_obj=None, *args, **kwargs):
"""Asserts that the message in a raised exception matches a regexp.
Args:
expected_exception: Exception class expected to be raised.
expected_regexp: Regexp (re pattern object or string) expected
to be found in error message.
callable_obj: Function to be called.
args: Extra args.
kwargs: Extra kwargs.
"""
if callable_obj is None:
return _AssertRaisesContext(expected_exception, self, expected_regexp)
try:
callable_obj(*args, **kwargs)
except expected_exception, exc_value:
if isinstance(expected_regexp, basestring):
expected_regexp = re.compile(expected_regexp)
actual = exc_value.message
if not expected_regexp.search(actual):
raise self.failureException(u'"{expected}" does not match "{actual}"'.
format(expected=expected_regexp.pattern, actual=actual))
else:
if hasattr(expected_exception, '__name__'):
excName = expected_exception.__name__
else:
excName = str(expected_exception)
raise self.failureException, "%s not raised" % excName
除了像assertRaisesRegex
建議的那樣重寫assertRaisesRegex
之外,您還可以像這樣修改monkeypatch unittest2.case.str
:
# unittest2's assertRaisesRegex doesn't do unicode comparison.
# Let's monkeypatch the str() function to point to unicode()
# so that it does :)
# For reference, this is where this patch is required:
# https://hg.python.org/unittest2/file/tip/unittest2/case.py#l227
try:
unittest2.case.str = unicode
except Exception:
pass # python 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.