我有以下测试方法
def test_fingerprintBadFormat(self):
"""
A C{BadFingerPrintFormat} error is raised when unsupported
formats are requested.
"""
with self.assertRaises(keys.BadFingerPrintFormat) as em:
keys.Key(self.rsaObj).fingerprint('sha256-base')
self.assertEqual('Unsupported fingerprint format: sha256-base',
em.exception.message)
这是异常类。
class BadFingerPrintFormat(Exception):
"""
Raises when unsupported fingerprint formats are presented to fingerprint.
"""
此测试方法在Python2中工作得很好,但在python3中失败,并显示以下消息
builtins.AttributeError: 'BadFingerPrintFormat' object has no attribute 'message'
如何在Python3中测试错误信息?我不喜欢使用asserRaisesRegex
的想法,因为它测试正则表达式而不是异常消息。
.message
属性已从Python 3的异常中删除。使用.args[0]
代替:
self.assertEqual('Unsupported fingerprint format: sha256-base',
em.exception.args[0])
或使用str(em.exception)
获得相同的值:
self.assertEqual('Unsupported fingerprint format: sha256-base',
str(em.exception))
在python2和python3上都可以使用:
>>> class BadFingerPrintFormat(Exception):
... """
... Raises when unsupported fingerprint formats are presented to fingerprint.
... """
...
>>> exception = BadFingerPrintFormat('Unsupported fingerprint format: sha256-base')
>>> exception.args
('Unsupported fingerprint format: sha256-base',)
>>> exception.args[0]
'Unsupported fingerprint format: sha256-base'
>>> str(exception)
'Unsupported fingerprint format: sha256-base'