Skip to content

Commit 6975ac6

Browse files
author
Gauvain Pocentek
committed
Merge branch 'rhansen-get-specific-user'
2 parents 81be3cf + ac2e534 commit 6975ac6

File tree

3 files changed

+115
-3
lines changed

3 files changed

+115
-3
lines changed

gitlab/objects.py

Lines changed: 45 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@
3434
class jsonEncoder(json.JSONEncoder):
3535
def default(self, obj):
3636
if isinstance(obj, GitlabObject):
37-
return {k: v for k, v in six.iteritems(obj.__dict__)
38-
if (not isinstance(v, BaseManager)
39-
and not k[0] == '_')}
37+
return obj.as_dict()
4038
elif isinstance(obj, gitlab.Gitlab):
4139
return {'url': obj._url}
4240
return json.JSONEncoder.default(self, obj)
@@ -488,6 +486,19 @@ def json(self):
488486
"""
489487
return json.dumps(self, cls=jsonEncoder)
490488

489+
def as_dict(self):
490+
"""Dump the object as a dict."""
491+
return {k: v for k, v in six.iteritems(self.__dict__)
492+
if (not isinstance(v, BaseManager) and not k[0] == '_')}
493+
494+
def __eq__(self, other):
495+
if type(other) is type(self):
496+
return self.as_dict() == other.as_dict()
497+
return False
498+
499+
def __ne__(self, other):
500+
return not self.__eq__(other)
501+
491502

492503
class UserKey(GitlabObject):
493504
_url = '/users/%(user_id)s/keys'
@@ -541,10 +552,41 @@ def unblock(self, **kwargs):
541552
raise_error_from_response(r, GitlabUnblockError)
542553
self.state = 'active'
543554

555+
def __eq__(self, other):
556+
if type(other) is type(self):
557+
selfdict = self.as_dict()
558+
otherdict = other.as_dict()
559+
selfdict.pop(u'password', None)
560+
otherdict.pop(u'password', None)
561+
return selfdict == otherdict
562+
return False
563+
544564

545565
class UserManager(BaseManager):
546566
obj_cls = User
547567

568+
def search(self, query, **kwargs):
569+
"""Search users.
570+
571+
Returns a list of matching users.
572+
"""
573+
url = self.obj_cls._url + '?search=' + query
574+
return self._custom_list(url, self.obj_cls, **kwargs)
575+
576+
def get_by_username(self, username, **kwargs):
577+
"""Get a user by its username.
578+
579+
Returns a User object or None if the named user does not
580+
exist.
581+
"""
582+
url = self.obj_cls._url + '?username=' + username
583+
results = self._custom_list(url, self.obj_cls, **kwargs)
584+
assert len(results) in (0, 1)
585+
try:
586+
return results[0]
587+
except IndexError:
588+
raise GitlabGetError('no such user: ' + username)
589+
548590

549591
class CurrentUserKey(GitlabObject):
550592
_url = '/user/keys'

gitlab/tests/test_manager.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,55 @@ def resp_get_all(url, request):
235235
self.assertEqual(data[0].id, 1)
236236
self.assertEqual(data[1].id, 2)
237237

238+
def test_user_manager_search(self):
239+
mgr = UserManager(self.gitlab)
240+
241+
@urlmatch(scheme="http", netloc="localhost", path="/api/v3/users",
242+
query="search=foo", method="get")
243+
def resp_get_search(url, request):
244+
headers = {'content-type': 'application/json'}
245+
content = ('[{"name": "foo1", "id": 1}, '
246+
'{"name": "foo2", "id": 2}]')
247+
content = content.encode("utf-8")
248+
return response(200, content, headers, None, 5, request)
249+
250+
with HTTMock(resp_get_search):
251+
data = mgr.search('foo')
252+
self.assertEqual(type(data), list)
253+
self.assertEqual(2, len(data))
254+
self.assertEqual(type(data[0]), User)
255+
self.assertEqual(type(data[1]), User)
256+
self.assertEqual(data[0].name, "foo1")
257+
self.assertEqual(data[1].name, "foo2")
258+
self.assertEqual(data[0].id, 1)
259+
self.assertEqual(data[1].id, 2)
260+
261+
def test_user_manager_get_by_username(self):
262+
mgr = UserManager(self.gitlab)
263+
264+
@urlmatch(scheme="http", netloc="localhost", path="/api/v3/users",
265+
query="username=foo", method="get")
266+
def resp_get_username(url, request):
267+
headers = {'content-type': 'application/json'}
268+
content = '[{"name": "foo", "id": 1}]'.encode("utf-8")
269+
return response(200, content, headers, None, 5, request)
270+
271+
with HTTMock(resp_get_username):
272+
data = mgr.get_by_username('foo')
273+
self.assertEqual(type(data), User)
274+
self.assertEqual(data.name, "foo")
275+
self.assertEqual(data.id, 1)
276+
277+
@urlmatch(scheme="http", netloc="localhost", path="/api/v3/users",
278+
query="username=foo", method="get")
279+
def resp_get_username_nomatch(url, request):
280+
headers = {'content-type': 'application/json'}
281+
content = '[]'.encode("utf-8")
282+
return response(200, content, headers, None, 5, request)
283+
284+
with HTTMock(resp_get_username_nomatch):
285+
self.assertRaises(GitlabGetError, mgr.get_by_username, 'foo')
286+
238287
def test_group_manager_search(self):
239288
mgr = GroupManager(self.gitlab)
240289

tools/python_test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,12 +43,33 @@
4343
new_user.block()
4444
new_user.unblock()
4545

46+
foobar_user = gl.users.create(
47+
{'email': 'foobar@example.com', 'username': 'foobar',
48+
'name': 'Foo Bar', 'password': 'foobar_password'})
49+
50+
assert gl.users.search('foobar') == [foobar_user]
51+
usercmp = lambda x,y: cmp(x.id, y.id)
52+
expected = sorted([new_user, foobar_user], cmp=usercmp)
53+
actual = sorted(gl.users.search('foo'), cmp=usercmp)
54+
assert expected == actual
55+
assert gl.users.search('asdf') == []
56+
57+
assert gl.users.get_by_username('foobar') == foobar_user
58+
assert gl.users.get_by_username('foo') == new_user
59+
try:
60+
gl.users.get_by_username('asdf')
61+
except gitlab.GitlabGetError:
62+
pass
63+
else:
64+
assert False
65+
4666
# SSH keys
4767
key = new_user.keys.create({'title': 'testkey', 'key': SSH_KEY})
4868
assert(len(new_user.keys.list()) == 1)
4969
key.delete()
5070

5171
new_user.delete()
72+
foobar_user.delete()
5273
assert(len(gl.users.list()) == 1)
5374

5475
# current user key

0 commit comments

Comments
 (0)