Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two files as part of unittest, while getting useful output in case of mismatch?

Tags:

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?

like image 540
EquipDev Avatar asked Feb 28 '17 14:02

EquipDev


People also ask

What is difference between comm and cmp command?

#1) cmp: This command is used to compare two files character by character. Example: Add write permission for user, group and others for file1. #2) comm: This command is used to compare two sorted files. One set of options allows selection of 'columns' to suppress.


1 Answers

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))) 
like image 156
Ethan Bradford Avatar answered Oct 17 '22 08:10

Ethan Bradford