As part of some Python tests using the unittest
framework, I need to compare two relatively short text files, where the one is a test output file and the other is a reference file.
The immediate approach is:
import filecmp
...
self.assertTrue(filecmp.cmp(tst_path, ref_path, shallow=False))
It works fine if the test passes, but in the even of failure, there is not much help in the output:
AssertionError: False is not true
Is there a better way of comparing two files as part of the unittest
framework, so some useful output is generated in case of mismatch?
To get a report of which line has a difference, and a printout of that line, use assertListEqual
on the contents, e.g
import io
self.assertListEqual(
list(io.open(tst_path)),
list(io.open(ref_path)))
Comparing the files in the form of arrays bear meaningful assert errors:
assert [row for row in open(actual_path)] == [row for row in open(expected_path)]
You could use that each time you need to compare files, or put it in a function. You could also put the files in the forms of text string instead of arrays.