[entity] give a default reasonnable __eq__ and __hash__ to Entity
authorAurelien Campeas <aurelien.campeas@logilab.fr>
Tue, 08 Oct 2013 10:46:06 +0200
changeset 9261 1dfe62a9da50
parent 9260 dd574929b414
child 9265 614762cdc357
[entity] give a default reasonnable __eq__ and __hash__ to Entity Using the eid. Closes #3179560.
entity.py
test/unittest_entity.py
--- a/entity.py	Fri Oct 04 18:16:45 2013 +0200
+++ b/entity.py	Tue Oct 08 10:46:06 2013 +0200
@@ -537,7 +537,14 @@
         raise NotImplementedError('comparison not implemented for %s' % self.__class__)
 
     def __eq__(self, other):
-        raise NotImplementedError('comparison not implemented for %s' % self.__class__)
+        if isinstance(self.eid, (int, long)):
+            return self.eid == other.eid
+        return self is other
+
+    def __hash__(self):
+        if isinstance(self.eid, (int, long)):
+            return self.eid
+        return super(Entity, self).__hash__()
 
     def _cw_update_attr_cache(self, attrcache):
         # if context is a repository session, don't consider dont-cache-attrs as
--- a/test/unittest_entity.py	Fri Oct 04 18:16:45 2013 +0200
+++ b/test/unittest_entity.py	Tue Oct 08 10:46:06 2013 +0200
@@ -742,7 +742,7 @@
         self.assertEqual(card.absolute_url(),
                           'http://testing.fr/cubicweb/%s' % card.eid)
 
-    def test_create_entity(self):
+    def test_create_and_compare_entity(self):
         req = self.request()
         p1 = req.create_entity('Personne', nom=u'fayolle', prenom=u'alexandre')
         p2 = req.create_entity('Personne', nom=u'campeas', prenom=u'aurelien')
@@ -756,6 +756,15 @@
         self.assertEqual(sorted([c.nom for c in p.evaluee]), ['campeas', 'fayolle'])
         self.assertEqual([c.type for c in p.reverse_ecrit_par], ['z'])
 
+        req = self.request()
+        auc = req.execute('Personne P WHERE P prenom "aurelien"').get_entity(0,0)
+        persons = set()
+        persons.add(p1)
+        persons.add(p2)
+        persons.add(auc)
+        self.assertEqual(2, len(persons))
+        self.assertNotEqual(p1, p2)
+        self.assertEqual(p2, auc)
 
 
 if __name__ == '__main__':