我们说我有以下代码
class MyClass(object):
def __init__(self, val1, val2):
self.attr1 = val1
self.attr2 = val2
class MySecondClass(object):
def __init__(self):
self.my_list = []
def add_to_list(self, val1, val2):
self.my_list.append(MyClass(val1, val2))
以及以下单元测试代码
import unittest
def myclass_equality(inst1, inst2, msg=None):
val1_matches = inst1.val1 == inst2.val1
val2_matches = inst1.val2 == inst2.val2
if not val1_matches or not val2_matches:
raise unittest.TestCase.failureException(msg)
class ListTests(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(ListTests, self).__init__(*args, **kwargs)
self.addTypeEqualityFunc(MyClass, myclass_equality)
def setUp(self):
self.second = MySecondClass()
def test_adding_to_list(self):
val1, val2 = 1, 2
self.second.add_to_list(val1, val2)
my_other_list = [(MyClass(val1, val2))]
self.assertListEqual(self.second.my_list, my_other_list)
然而,断言失败,因为assertListEqual方法将对象与' =='可以看出here而不是我定义的方法,如果我在两个MyClass实例上调用assertEqual就会调用它。
有任何变通方法吗?因为我不需要并且想要为MyClass定义__eq__方法。
为什么assertListEqual与' =='而不是assertEqual?
答案 0 :(得分:0)
您可以在循环中执行此操作,还是为myclass_equality
函数创建另一个循环包装器?我觉得我错过了什么。
E.g:
def test_adding_to_list(self):
val1, val2 = 1, 2
self.second.add_to_list(val1, val2)
my_other_list = [(MyClass(val1, val2))]
for i, (a, b) in enumerate(zip(self.second.my_list, my_other_list)):
myclass_equality(a, b, msg='Adding to list failed on element {}:{}!={}'.format(i, a, b)