Skip to content Skip to sidebar Skip to footer

Assertequal Custom Comparison Of List Item

In Python I would like to execute a custom comparison for a specific class. The function I have to test return a list containing objects created by a library that I don't have no c

Solution 1:

but the problem is that the function could return recursive result such as list into list

So let's use recursion. I could suggest the following code (untested):

defassertListNotControlledClassEqual(self, list1, list2, msg=None):
    self.assertEqual(len(list1), len(list2), msg)
    for obj1, obj2 inzip(list1, list2):
        self.assertEqual(type(obj1), type(obj2), msg)
        ifisinstance(obj1, list):
            self.assertListNotControlledClassEqual(obj1, obj2, msg)
        else:
            self.assertEqual(obj1, obj2, msg)

...

deftest(self):
    self.addTypeEqualityFunc(NotControlledClass, myCustomEqual)

    obj1 = NotControlledClass()
    obj2 = NotControlledClass()

    self.assertListNotControlledClassEqual([obj1], [obj2])

This seems like a bug in unittest to me. I would expect addTypeEqualityFunc to recurse down into containers, but it doesn't

Manual for assertEqual states:

In addition, if first and second are the exact same type and one of list, tuple, dict, set, frozenset or str or any type that a subclass registers with addTypeEqualityFunc() the type-specific equality function will be called in order to generate a more useful default error message

However, the type-specific list method assertListEqual doesn't mention addTypeEqualityFunc() at all

Post a Comment for "Assertequal Custom Comparison Of List Item"