Unittest's assertEqual and iterables - only check the contents

PythonUnit TestingAssertIterable

Python Problem Overview


Is there a 'decent' way in unittest to check the equality of the contents of two iterable objects? I am using a lot of tuples, lists and numpy arrays and I usually only want to test for the contents and not for the type. Currently I am simply casting the type:

self.assertEqual (tuple (self.numpy_data), tuple (self.reference_list))

I used this list comprehension a while ago:

[self.assertEqual (*x) for x in zip(self.numpy_data, self.reference_list)]

But this solution seems a bit inferior to the typecast because it only prints single values if it fails and also it does not fail for different lengths of reference and data (due to the zip-function).

Python Solutions


Solution 1 - Python

Python 3

Python >= 2.7

Solution 2 - Python

You can always add your own assertion methods to your TestCase class:

def assertSequenceEqual(self, it1, it2):
    self.assertEqual(tuple(it1), tuple(it2))

or take a look at how 2.7 defined it: http://hg.python.org/cpython/file/14cafb8d1480/Lib/unittest/case.py#l621

Solution 3 - Python

It looks to me you care about the order of items in the sequences. Therefore, assertItemsEqual/assertCountEqual is not for you.

In Python 2.7 and in Python 3, what you want is self.assertSequenceEqual. This is sensitive to the order of the items.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLucas HoepnerView Question on Stackoverflow
Solution 1 - PythonCédric JulienView Answer on Stackoverflow
Solution 2 - PythonNed BatchelderView Answer on Stackoverflow
Solution 3 - Pythonuser7610View Answer on Stackoverflow