assertraisesregxp可以在Python2中使用unicode

2024-04-24 17:25:57 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我注意到assertRaisesRegexp不能在Python2.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()

但有以下错误

^{pr2}$

看起来python标准库正在尝试将unicode字符串转换为str类型,这导致了错误。 如果我使用assertRaiseRegx,这个函数在Python3上运行得很好,没有unicode问题。 关于如何让它在Python2中工作有什么建议吗?在


Tags: importselfmaindef错误unicodeexceptionunittest
3条回答

还有另一种方法,即使str(exc_value)工作:

class UnicodeMsgException(Exception):
    def __str__(self):
        return unicode(self).encode('utf-8')
    def __unicode__(self):
        return self.message

我在这里遇到了同样的问题,不幸的是,我也不能解决它,但我有一个工作范围,在我的情况下,我把我的加薪例外改为:

raise Exception(u'\u4e2d\u6587'.encode('utf8'))

这对我很有用。。。在

如果显式地传入regexp对象,则效果似乎更好:

with self.assertRaisesRegexp(Exception, re.compile(u'\u4e2d\u6587')):

assertraisesregxp的文档建议,只要可以作为regexp使用,就可以传入一个字符串,但至少对于我使用的python版本(2.7.8)来说,这个字符串似乎已经损坏。在

相关问题 更多 >