我正在尝试使用 python 的 unittest
库来编写一些单元测试。我有一个返回无序列表的对象的函数。我想验证对象是否相同,我正在尝试使用 assertCountEqual做这个。
然而,这似乎失败了,尽管各个对象彼此相等 (==
)。这是断言失败的“差异”输出:
First has 1, Second has 0: Intersection(time=8.033252939677466e-08, del_time=8.033252939677466e-08, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
First has 1, Second has 0: Intersection(time=-9.918729244820295e-16, del_time=-9.918729244820295e-16, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
First has 0, Second has 1: Intersection(time=8.033252939677466e-08, del_time=8.033252939677466e-08, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
First has 0, Second has 1: Intersection(time=-9.918729244820295e-16, del_time=-9.918729244820295e-16, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
验证它们是否相等:
>>> i = Intersection(time=8.033252939677466e-08, del_time=8.033252939677466e-08, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
>>> j = Intersection(time=8.033252939677466e-08, del_time=8.033252939677466e-08, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
>>> i == j
True
>>> i = Intersection(time=-9.918729244820295e-16, del_time=-9.918729244820295e-16, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
>>> j = Intersection(time=-9.918729244820295e-16, del_time=-9.918729244820295e-16, pos=Vector(10.00, 0.00), line=Line(Vector(500.00, 0.00), Vector(0.00, 0.00)), ent=None, oth=None, invalid=False)
>>> i == j
True
我的猜测是 assertCountEqual
函数正在检查两者是否具有相同的标识(例如 i is j
),而不是相等。
- 是否有单元测试函数可以提供相同的差异 能力,但使用平等比较,而不是身份?
- 或者,有没有什么方法可以编写一个函数来执行
类似于
assertCountEqual
?
编辑:我正在运行 python 3.2.2。
最佳答案
可以自己找how the comparison is done :
- 从每个可迭代对象生成一个列表
- 使用collections.Counter计算对象 - 仅适用于可哈希元素
- 如果元素不可散列,compare them directly
因为您的 Intersection
是对象,所以它们是 hashable每default , 但如果您没有提供合适的哈希函数(如果您是 provide comparison methods 则应该这样做),它们将被视为不同。
那么,您的Intersection
类是否满足哈希契约?
关于python unittest assertCountEqual 使用 'is' 而不是 '==' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10455538/