Python assertItemsEqual/assertCountEqual 属性错误

Python assertItemsEqual/assertCountEqual AttributeError

我 运行 在使用 unittest.TestCase.assertItemsEqual (或 Python 3 中的 assertCountEqual 时遇到了一个问题,这让我有点困惑,我无法在这里找到解决方案,所以我在这里发布我的修复程序以供后代使用:

以下单元测试在 Python 2 和 3 下均失败:

import six
import unittest

class Foo(object):
    def __init__(self, a=1, b=2):
        self.a = a
        self.b = b
    def __repr__(self):
        return '({},{})'.format(self.a, self.b)
    def __eq__(self, other):
        return self.a == other.a and self.b == other.b
    def __lt__(self, other):
        return (self.a, self.b) < (other.a, other.b)
    __hash__ = None

class Test(unittest.TestCase):
    def test_foo_eq(self):
        self.assertEqual(sorted([Foo()]), sorted([Foo()]))
        six.assertCountEqual(self, [Foo()], [Foo()])
        six.assertCountEqual(self, [Foo(1,2), Foo(2,3)], [Foo(2,3), Foo(1,2)])

unittest.main()

错误消息如下所示:

======================================================================
ERROR: test_foo_eq (__main__.Test)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/tsanders/scripts/one_offs/test_unittest_assert_items_equal2.py", line 20, in test_foo_eq
    six.assertCountEqual(self, [Foo(1,2), Foo(2,3)], [Foo(2,3), Foo(1,2)])
  File "/home/tsanders/.local/lib/python2.7/site-packages/six.py", line 673, in assertCountEqual
    return getattr(self, _assertCountEqual)(*args, **kwargs)
  File "/usr/lib64/python2.7/unittest/case.py", line 929, in assertItemsEqual
    differences = _count_diff_all_purpose(first_seq, second_seq)
  File "/usr/lib64/python2.7/unittest/util.py", line 116, in _count_diff_all_purpose
    if other_elem == elem:
  File "/home/tsanders/scripts/one_offs/test_unittest_assert_items_equal2.py", line 11, in __eq__
    return self.a == other.a and self.b == other.b
AttributeError: 'object' object has no attribute 'a'

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

我不得不查看 sourceunittest 模块来解决这个问题。

当被比较的列表的元素不可散列时,assertItemsEqual/assertCountEqual 函数回退到 a different algorithm 来比较列表。该算法使用一个空的 object() 作为标记,它与 Foo.

类型的对象不相等。

修复方法是修改我的 __eq__ 函数如下:

def __eq__(self, other):
    try:
        return self.a == other.a and self.b == other.b
    except AttributeError:
        return False