Python 2.7 在python2.7和3.4中检查测试中的错误消息
我需要使用unittest编写一个测试来检查错误消息的内容。该测试需要同时适用于python2.7和python3.4。最初,我的测试是这样的:Python 2.7 在python2.7和3.4中检查测试中的错误消息,python-2.7,python-3.4,python-unittest,Python 2.7,Python 3.4,Python Unittest,我需要使用unittest编写一个测试来检查错误消息的内容。该测试需要同时适用于python2.7和python3.4。最初,我的测试是这样的: class MyFuncTestCaes(TestCase) def test_my_func(self): with self.assertRaises(TypeError) as context: my_func() self.assertIn("some message", cont
class MyFuncTestCaes(TestCase)
def test_my_func(self):
with self.assertRaises(TypeError) as context:
my_func()
self.assertIn("some message", context.exception.message
这适用于Python2.7,但不适用于Python3.4-在
异常
上似乎不再有消息
属性。如何修改此测试,使其适用于两个版本的Python?解决了这个问题assertRaisesRegexp
在Python2.7和Python3.4中都可以工作,因此我可以这样做,确保转义需要检查的字符串:
class MyFuncTestCaes(TestCase)
def test_my_func(self):
with self.assertRaisesRegexp(TypeError, re.escape("some message")) as context:
my_func()