Search code examples
pythonasserterror-loggingnosetestspython-unittest

python unittests assertEqual print too much when it fails


In a bunch of tests that I'm running using nosetests, an assertEqual(a,b) fails, a and b (pretty long strings) are printed verbatim filling the screen, obfuscating everything else. You can create similar situation by adding this to one of your test cases:

def test_my_long_strings(self): 
    self.assertEqual('a'*5000, 'b'*5000)

I tried setting --verbosity=0 and --debug-log=File, but none of them had any effect, and the two strings are still printed on the screen.

Is there anyway to shutup the assertEqual verbosity or redirect it to a separate file other than stderr (where test failures/passes are also reported)?


Solution

  • assertEqual takes as a third parameter an assertion message for failure.

    class TestMyTest(unittest.TestCase):
        def test_example(self):
            a = 'a'
            b = 'b'
            self.assertEqual(a, b, 'a did not equal b')
    

    prints the stack trace of the failing location plus

    AssertionError: a did not equal b
    

    Reference: https://docs.python.org/2/library/unittest.html#unittest.TestCase.assertEqual