断言等于其中包含数组的对象

时间:2018-08-01 17:10:33

标签: python unit-testing python-unittest

我的目标是使用python中的unittesting检查对象的相似性。我有这种东西

from PySide2 import QtCore, QtGui, QtWidgets


class QTreeWidget(QtWidgets.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(TreeWidget, self).__init__(*args, **kwargs)
        self.special_item = None
        self.special_col = 0

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Return:
            self.editItem(self.special_item, self.special_col)
        QtWidgets.QTreeWidget.keyPressEvent(self, event)

    def editEnable(self, pos):
        press_item = self.itemAt(pos)
        if press_item is None:
            return
        if press_item is self.selectedItems()[0]:
            col = self.header().logicalIndexAt(pos.x())
            self.special_item = press_item
            self.special_col = col

    def mousePressEvent(self, event):
        QtWidgets.QTreeWidget.mousePressEvent(self, event)
        self.editEnable(event.pos())

我已经读到,如果您要测试数组class ImageModel(object): def __init__(self): self.data = data #this an array self.name = name self.path = path 的相似性,则必须在每个数组之后放置self.assertEqual(arr1,arr2)。但是我必须检查其中具有数组的对象的相似性。就我而言,应该是:

.all()

但是它总是表明那些对象不相似,我认为问题出在self.assertEqual(ImageObj1, ImageObj2)

那么,有什么方法可以使一个对象中的数组相等?

1 个答案:

答案 0 :(得分:0)

一种可能性是重写类的__eq__方法。基本上,这是在==实例上使用ImageModel运算符时调用的方法。

这里是一个例子:

def __eq__(self, other):
    return (
        # the two instances must be of the same class
        isinstance(other, self.__class__) and
        # compare name and path, that's straightforward
        self.name == other.name and
        self.path == other.path and
        # and compare data
        len(self.data) == len(other.data) and
        all(a == b for a, b in zip(self.data, other.data))
    )