assertEqual custom comparison of list item

主宰稳场 提交于 2020-05-31 03:21:06

问题


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 control on it. The error (which make my test failing) is because of this specific object comparison.

First differing element 0:

The return is actually correct but the __eq__ function of the library object return False.

class NotControlledClass:
    def __eq__(self, other):
        # Always return false as objects are created into the tested function and 
        # the other one into the testing function
        return False

def myCustomEqual(a, b, msg):
    # This is never call
    return a.name == b.name

def test(self):
    self.addTypeEqualityFunc(NotControlledClass, myCustomEqual)

    obj1 = NotControlledClass()
    obj2 = NotControlledClass()

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

I tried to loop through my result and comparing element one by one but the problem is that the function could return recursive result such as list into list.
Is anyone know how to make this test pass?


回答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):

def assertListNotControlledClassEqual(self, list1, list2, msg=None):
    self.assertEqual(len(list1), len(list2), msg)
    for obj1, obj2 in zip(list1, list2):
        self.assertEqual(type(obj1), type(obj2), msg)
        if isinstance(obj1, list):
            self.assertListNotControlledClassEqual(obj1, obj2, msg)
        else:
            self.assertEqual(obj1, obj2, msg)

...

def test(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



来源:https://stackoverflow.com/questions/59505258/assertequal-custom-comparison-of-list-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!