Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent truncating of string in unit test python

Tags:

I am doing a unit test in Python for my program and I would like to do an assertEquals test.

My code looks something like this:

class UnitTest(unittest.TestCase):
      def test_parser(self):
          self.assertEquals(parser,"some long string", "String is not equal")

However, as my string is too long, I got something like testing[471 chars]0 != testing[473 chars]. I wanna see what is the exact difference between both the strings instead of seeing the truncated ones.

Anyone has an idea how to counter this problem?

like image 458
decemberrobot Avatar asked May 08 '17 08:05

decemberrobot


2 Answers

So, I landed on this question because I had an issue where I was using assertEqual() and self.maxDiff = None wouldn't cause the full output to be displayed. Tracing through, it turned out that because the types of the two objects were different (one was a list, one was a generator), the code path that would make use of self.maxDiff wasn't used. So, if you run into the issue where you need the full diff and self.maxDiff isn't working, ensure the types of your two compared objects are the same.

like image 82
Robert Thille Avatar answered Sep 19 '22 13:09

Robert Thille


To replace [... chars] and [truncated]... with actual characters (no matter how long, and no matter what the type of the compared values are), add this to your *_test.py file:

if 'unittest.util' in __import__('sys').modules:
    # Show full diff in self.assertEqual.
    __import__('sys').modules['unittest.util']._MAX_LENGTH = 999999999

Indeed, as other answers have noted, setting self.maxDiff = None doesn't help, it doesn't make the [... chars] disappear. However, this setting helps showing other types of long diffs, so my recommendation is doing both.

like image 32
pts Avatar answered Sep 20 '22 13:09

pts