我有以下测试方法
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)下面是exception类。
class BadFingerPrintFormat(Exception):
"""
Raises when unsupported fingerprint formats are presented to fingerprint.
"""此测试方法在Python2中运行良好,但在Python3中失败,并显示以下消息
builtins.AttributeError: 'BadFingerPrintFormat' object has no attribute 'message'如何在Python3中测试错误消息。我不喜欢使用asserRaisesRegex的想法,因为它测试正则表达式而不是异常消息。
发布于 2016-08-16 22:42:10
已从Python3中的异常中删除了.message属性。请改用.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))这在Python 2和Python 3上都有效:
>>> 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'https://stackoverflow.com/questions/38975640
复制相似问题