abhi
abhi

Reputation: 366

test error message in python 3

I have the following test method

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)

Here is the exception class.

class BadFingerPrintFormat(Exception):
    """
    Raises when unsupported fingerprint formats are presented to fingerprint.
    """

this test method works perfectly fine in Python2 but fails in python 3 with the following message

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

How can I test the error message in Python3. I don't like the idea of using asserRaisesRegex as it tests the regex rather than the exception message.

Upvotes: 1

Views: 2395

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121644

The .message attribute was removed from exceptions in Python 3. Use .args[0] instead:

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

or use str(em.exception) to get the same value:

self.assertEqual('Unsupported fingerprint format: sha256-base',
    str(em.exception))

This will work both on Python 2 and 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'

Upvotes: 3

Related Questions