在python 3中测试错误消息

时间:2016-08-16 12:58:18

标签: python unit-testing python-3.x exception

我有以下测试方法

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中运行得很好但在python 3中失败并带有以下消息

builtins.AttributeError: 'BadFingerPrintFormat' object has no attribute 'message'

如何在Python3中测试错误消息。我不喜欢使用asserRaisesRegex来测试正则表达式而不是异常消息。

1 个答案:

答案 0 :(得分:2)

从Python 3中的异常中删除了.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和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'