Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unittest's assertEqual and iterables - only check the contents

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).

like image 792
Lucas Hoepner Avatar asked Sep 19 '11 15:09

Lucas Hoepner


People also ask

How do I run a unit test in Python?

The command to run the tests is python -m unittest filename.py . In our case, the command to run the tests is python -m unittest test_utils.py .

How do I test a function in Python?

First you need to create a test file. Then import the unittest module, define the testing class that inherits from unittest. TestCase, and lastly, write a series of methods to test all the cases of your function's behavior. First, you need to import a unittest and the function you want to test, formatted_name() .

Which item in Python will stop a unit test abruptly?

An exception object is created when a Python script raises an exception. If the script explicitly doesn't handle the exception, the program will be forced to terminate abruptly.


2 Answers

Python 3

  • If you don't care about the order of the content, you have the assertCountEqual(a,b) method
  • If you care about the order of the content, you have the assertSequenceEqual(a,b) method

Python >= 2.7

  • If you don't care about the order of the content, you have the assertItemsEqual(a,b) method
  • If you care about the order of the content, you have the assertSequenceEqual(a,b) method
like image 85
Cédric Julien Avatar answered Sep 22 '22 02:09

Cédric Julien


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

like image 35
Ned Batchelder Avatar answered Sep 22 '22 02:09

Ned Batchelder