Tyler Tyler - 2 months ago 15
Python Question

How can I only show the custom error message for Python's unittest module

Using Python's

module, the assertion

self.assertTrue(a > b - 0.5 && a < b + 0.5, "The two values did not agree")

outputs the following on failure:

AssertionError: False is not true : The two values did not agree

I don't want the
False is not true
to be printed. Ideally,
shouldn't be printed either. Only
The two values did not agree
should be printed.

Can I do this?


You can supress the False is true part, however, one thing to keep in mind here, you are raising an exception, and what you are seeing is the standard output of an assertion being raised in Python. You want to see this. Furthermore, this is being called directly in the assertion methods, as you can see from the assertTrue below:

def assertTrue(self, expr, msg=None):
    """Check that the expression is true."""
    if not expr:
        msg = self._formatMessage(msg, "%s is not true" % safe_repr(expr))
        raise self.failureException(msg)

To supress the 'False is true' part, change the longMessage class attribute to False:

class TestCompare(unittest.TestCase):

    longMessage = False

    def test_thing(self):
        self.assertTrue(5 == 6, "The two values did not agree")


Traceback (most recent call last):
  File "/Users/XXX/dev/rough/test_this.py", line 21, in test_things
    self.assertTrue(5 == 6, "The two values did not agree")
AssertionError: The two values did not agree