klenwell
klenwell

Reputation: 7148

When unit testing in Python, how can I display my custom message together with the default message when an assert fails?

Consider the following example:

import unittest

class MessageExampleTest(unittest.TestCase):
    def test_with_default_message(self):
        self.assertEqual('apples', 'oranges')

    def test_with_custom_message(self):
        self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')

Output:

======================================================================
FAIL: test_with_default_message (assert_message.MessageExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
    self.assertEqual('apples', 'oranges')
AssertionError: 'apples' != 'oranges'

======================================================================
FAIL: test_with_custom_message (assert_message.MessageExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
    self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')
AssertionError: You should not compare apples and oranges.


----------------------------------------------------------------------

What I'd like to see, in the second case, is something like:

AssertionError: 'apples' != 'oranges'; You should not compare apples and oranges.

Upvotes: 0

Views: 935

Answers (1)

klenwell
klenwell

Reputation: 7148

As of Python 2.7, unittest now provides a longMessage property that will do this.

In Python 2.7:

import unittest

class MessageExampleTest(unittest.TestCase):
    def setUp(self):
        self.longMessage = True

    def test_with_custom_message(self):
        self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')

Output:

======================================================================
FAIL: test_with_custom_message (assert_message.MessageExampleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  ...
    self.assertEqual('apples', 'oranges', 'You should not compare apples and oranges.')
AssertionError: 'apples' != 'oranges' : You should not compare apples and oranges.

======================================================================

Upvotes: 1

Related Questions