I am running python 3.6.4
, but some times the unit testing diff does not work as expected. For example, on the following there is a forced unit test error versus expected where the line wrapping behavior is not desired.
import unittest
class TestSemanticRules(unittest.TestCase):
maxDiff = None
def test_badWrapping(self):
self.assertEqual(
"1. Duplicated target language name defined in your grammar on: [@-1,63:87='Abstract Machine Language'<__ANON_3>,3:19]\n"
"2. Duplicated master scope name defined in your grammar on: [@-1,138:147='source.sma'<__ANON_3>,5:20]"
,
"1. Duplicated target language name defined in your grammar on: free_input_string\n"
" text_chunk_end Abstract Machine Language"
"\n"
"2. Duplicated master scope name defined in your grammar on: free_input_string\n"
" text_chunk_end source.sma"
)
unittest.main(failfast=True)
Running it with python3 test.py
you see the first error diff line does not got wrapped:
An expected result would be:
I tried searching for an alternative diff library, then I tried replacing the unittest
diff by a custom diff library as the built-in difflib
, but the diff results where the same. So, I assume the unittest
package is using the difflib
.
import unittest
import difflib
class TestSemanticRules(unittest.TestCase):
maxDiff = None
def myAssertEquals(self, expected, actual):
expected = expected.splitlines( 1 )
actual = actual.splitlines( 1 )
if expected != actual:
diff = difflib.context_diff( expected, actual, fromfile='expected input', tofile='actual output', lineterm='\n' )
self.fail( '\n' + ''.join( diff ) )
def test_badWrapping(self):
self.myAssertEquals(
"1. Duplicated target language name defined in your grammar on: [@-1,63:87='Abstract Machine Language'<__ANON_3>,3:19]\n"
"2. Duplicated master scope name defined in your grammar on: [@-1,138:147='source.sma'<__ANON_3>,5:20]"
,
"1. Duplicated target language name defined in your grammar on: free_input_string\n"
" text_chunk_end Abstract Machine Language"
"\n"
"2. Duplicated master scope name defined in your grammar on: free_input_string\n"
" text_chunk_end source.sma"
)
Can the difflib
built-in library used by the unittest
package to be configured, so, this behavior does not happen? Or there is an reliable alternative for the difflib
package?
This is a bug on python and can be fixed by applying this patch:
Searching for alternatives to
difflib
I got 3 results:Then, using
diff-match-patch
I manage to build the following code:Using
diffMode=0
as charactersUsing
diffMode=1
as wordsUsing
diffMode=2
as linesWhich seems already to be better than the built-in behavior from the
unittest
module. How could this newdiff_prettyText()
still be improved?References
PyCharm show full diff when unittest fails for multiline string?
How to print the comparison of two multiline strings in unified diff format?