测试错误信息在Python 3中

2024-10-02 22:26:01 发布

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

我有以下测试方法

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)

这是异常类。在

^{pr2}$

这个测试方法在Python2中可以很好地工作,但是在python3中失败,并显示以下消息

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

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


Tags: testself消息messagebaseisdeferror
1条回答
网友
1楼 · 发布于 2024-10-02 22:26:01

在python3中,.message属性已从异常中删除。使用.args[0]代替:

self.assertEqual('Unsupported fingerprint format: sha256-base',
    em.exception.args[0])

或者使用str(em.exception)获得相同的值:

^{pr2}$

这对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'

相关问题 更多 >