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

2024-02-02

我正在尝试使用 python 的unittest库来编写一些单元测试。我有一个返回对象的无序列表的函数。我想验证对象是否相同,并且我正在尝试使用断言计数等于 http://docs.python.org/py3k/library/unittest.html?highlight=unittest#unittest.TestCase.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)

验证它们是否相等:

>>> 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?

EDIT:我正在运行 python 3.2.2。


你可以自己找找比较是如何进行的 http://hg.python.org/cpython/file/5b2f40ed32fd/Lib/unittest/case.py#l969:

  • 从每个可迭代对象生成一个列表
  • use a 收藏.柜台 http://docs.python.org/py3k/library/collections#collections.Counter计算对象数量 - 仅适用于可散列元素
  • 如果元素不可散列,直接比较它们 http://hg.python.org/cpython/file/5b2f40ed32fd/Lib/unittest/util.py#l84

as your Intersections 是对象,它们是hashable http://docs.python.org/py3k/glossary.html#term-hashable per default http://docs.python.org/py3k/reference/datamodel.html#object.__hash__,但是如果你没有提供合适的哈希函数(如果你提供比较方法 http://docs.python.org/py3k/reference/datamodel.html#richcmpfuncs)它们将被视为不同。

那么,你的Intersection类履行哈希合约吗?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

pythonunittestassertCountEqual使用'is'而不是'=='? 的相关文章