python unittest assertCountEqual 使用 'is' 而不是 '==' ?

标签 python unit-testing python-3.x

我正在尝试使用 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 :

因为您的 Intersection 是对象,所以它们是 hashabledefault , 但如果您没有提供合适的哈希函数(如果您是 provide comparison methods 则应该这样做),它们将被视为不同。

那么,您的Intersection 类是否满足哈希契约?

关于python unittest assertCountEqual 使用 'is' 而不是 '==' ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10455538/

相关文章:

python - 如何在不考虑空格并知道字符串的原始索引的情况下在字符串中查找子字符串

angularjs - Angular 和 Karma 测试使用 $resource 并返回 promise 的服务

java - JUnit 使用 HyperSQL 测试 DAO 类

wpf - 单元测试 - 在测试项目中使用图像作为资源

python - 合并共享单元值的 Python 3 DataFrame 行,将另一个值放入逗号分隔的数组中

python - 不能继承timedelta

python - Selenium 无法从workera.ai 中找到元素

python - 按值迭代多个列表

python - 如何在Python中将循环中的日期交换到数组中?

django - 使用 Django 3.0.0 最新版本时出现错误无法从 'six' 导入名称 'django.utils'