I want to use a custom comparison function when I am unit testing a class. unittest has addTypeEqualityFunc
but that only works when the two objects are directly compared. It isn't used inside collections. Is there a way to do this? My specific use case is using MagicMock.assert_has_calls
and comparing arguments to the calls.
import unittest
class C:
def __eq__(self, other):
return False
def always_equal(this, that, msg=None):
return True
class TestCase(unittest.TestCase):
def test_without_equality_func(self):
# This passses
obj = C()
self.assertEqual(obj, obj)
def test_with_equality_func(self):
# This fails
self.addTypeEqualityFunc(C, always_equal)
obj = C()
self.assertEqual(obj, obj)
def test_in_list_with_equality_func(self):
# This fails
self.addTypeEqualityFunc(C, always_equal)
l1 = [C()]
l2 = [C()]
self.assertEqual(l1, l2)
addTypeEqualityFunc
isn't designed for changing comparison logic. It's designed for providing more detailed error messages when a mismatch is found. The way the API is designed, it wouldn't make sense to use it for subcomparisons.
If you want to patch the logic a class uses to do equality comparisons, then patch the __eq__
method with unittest.mock.patch
:
with patch.object(C, '__eq__', always_equal):
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.