pythonunittestassertCountEqual使用'is'而不是'=='?

Cas*_*all 3 python unit-testing python-3.x

我正在尝试使用 python 的unittest库来编写一些单元测试。我有一个返回对象的无序列表的函数。我想验证对象是否相同,并且我尝试使用assertCountEqual来执行此操作。

==然而,尽管各个对象彼此相等 ( ),但这似乎失败了。这是断言失败的“diff”输出:

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)
Run Code Online (Sandbox Code Playgroud)

验证它们是否相等:

>>> 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
Run Code Online (Sandbox Code Playgroud)

我的猜测是该assertCountEqual函数正在检查两者是否具有相同的身份(例如i is j),而不是相等。

  • 是否有一个单元测试函数可以提供相同的 diff 功能,但使用相等比较,而不是同一性?
  • 或者,有什么方法可以编写一个与 类似的函数assertCountEqual

编辑:我正在运行 python 3.2.2。

mat*_*ata 5

你可以自己看看如何进行比较

由于您的Intersections 是对象,因此它们默认可哈希的,但是如果您没有提供合适的哈希函数(如果您提供比较方法,则应该这样做),它们将被视为不同。

那么,你的Intersection班级是否履行了哈希合约?

  • 当两个对象比较相等时,它们应该返回相同的哈希值。当将对象添加到集合或字典作为键时,它们是通过它们的哈希值访问的,因此如果它们返回不同的值,它们将不会被视为相等。哈希函数应该快速并且可能为不同的对象产生不同的值。要了解总体思路,请查看[此处](http://effbot.org/zone/python-hash.htm) (2认同)