Skip to content

Commit 3d60850

Browse files
author
Jonathan Piron
committed
Implement __eq__ and __hash__ methods
To ease lists and sets manipulations.
1 parent 31bca2f commit 3d60850

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

gitlab/base.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,16 @@ def __repr__(self):
9696
else:
9797
return '<%s>' % self.__class__.__name__
9898

99+
def __eq__(self, other):
100+
if self.get_id() and other.get_id():
101+
return self.get_id() == other.get_id()
102+
return super().__eq__(other)
103+
104+
def __hash__(self):
105+
if not self.get_id():
106+
return super().__hash__()
107+
return hash(self.get_id())
108+
99109
def _create_managers(self):
100110
managers = getattr(self, '_managers', None)
101111
if managers is None:
@@ -112,7 +122,7 @@ def _update_attrs(self, new_attrs):
112122

113123
def get_id(self):
114124
"""Returns the id of the resource."""
115-
if self._id_attr is None:
125+
if self._id_attr is None or not hasattr(self, self._id_attr):
116126
return None
117127
return getattr(self, self._id_attr)
118128

gitlab/tests/test_base.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,3 +134,26 @@ class ObjectWithManager(FakeObject):
134134
self.assertIsInstance(obj.fakes, FakeManager)
135135
self.assertEqual(obj.fakes.gitlab, self.gitlab)
136136
self.assertEqual(obj.fakes._parent, obj)
137+
138+
def test_equality(self):
139+
obj1 = FakeObject(self.manager, {'id': 'foo'})
140+
obj2 = FakeObject(self.manager, {'id': 'foo', 'other_attr': 'bar'})
141+
self.assertEqual(obj1, obj2)
142+
143+
def test_equality_custom_id(self):
144+
class OtherFakeObject(FakeObject):
145+
_id_attr = 'foo'
146+
147+
obj1 = OtherFakeObject(self.manager, {'foo': 'bar'})
148+
obj2 = OtherFakeObject(self.manager, {'foo': 'bar', 'other_attr': 'baz'})
149+
self.assertEqual(obj1, obj2)
150+
151+
def test_inequality(self):
152+
obj1 = FakeObject(self.manager, {'id': 'foo'})
153+
obj2 = FakeObject(self.manager, {'id': 'bar'})
154+
self.assertNotEqual(obj1, obj2)
155+
156+
def test_inequality_no_id(self):
157+
obj1 = FakeObject(self.manager, {'attr1': 'foo'})
158+
obj2 = FakeObject(self.manager, {'attr1': 'bar'})
159+
self.assertNotEqual(obj1, obj2)

0 commit comments

Comments
 (0)