From 9cc45128713f85a0508b21d3784adec7c6af96fd Mon Sep 17 00:00:00 2001 From: Sanjana Chandrashekar Date: Tue, 11 May 2021 18:35:37 -0700 Subject: [PATCH 01/24] Updated to support permissions integration --- argusclient/client.py | 64 +++++++++++++++++++++++++++++++++++++++-- argusclient/model.py | 9 +++--- tests/test_data.py | 32 +++++++++++++++++++++ tests/test_modelobjs.py | 16 +++++++++++ tests/test_service.py | 20 +++++++++++++ 5 files changed, 134 insertions(+), 7 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index a981b8d..d23d0fc 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -438,13 +438,66 @@ def _init_all(self, coll=None): self._coll[id] = perms self._retrieved_all = True - def get_permissions_for_entities(self, entityIds): + def get_permissions_for_entities(self, entity_ids): """ Gets permissions that are associated with the given entity id's. :return: a dict of entity id's mapped to a list of :class:`argusclient.model.Permission` objects """ - return convert(self.argus._request("post", "permission/entityIds", dataObj=entityIds)) + entityIds = [] + for entity_id in entity_ids: + if entity_id not in self._coll: + entityIds.append(entity_id) + + if entityIds: + response = convert(self.argus._request("post", "permission/entityIds", dataObj=entityIds)) + for id, perms in response.items(): + self._coll[id] = perms + return self._coll + + + def add(self, entity_id, permission): + """ + Associates a permission with an alert + :return: the :class:`argusclient.model.Permission` object with the entityId field set. + """ + if not isinstance(permission, Permission): + raise TypeError("Need a Permission object, got: %s" % type(permission)) + if permission.argus_id: raise ValueError("A new permission can't have an entity id associated with it") + updated_permission = self.argus._request("post", "permission/%s" % entity_id, dataObj=permission) + + self._coll[updated_permission.entityId] = updated_permission + + if updated_permission.entityId != entity_id: + raise ArgusException("This is unexpected... permission: %s not associated with entity after successfully" + " adding it" % permission) + return updated_permission + + def delete(self, entity_id, permission): + if not isinstance(permission, Permission): + raise TypeError("Need a Permission object, got: %s" % type(permission)) + if permission.type == "user" and permission.permissionIds == []: + raise ValueError("A user permission needs to have the permission that needs to be revoked") + updated_permission = self.argus._request("delete", "permission/%s" % entity_id, dataObj=permission) + if updated_permission.entityId in self._coll: + del self._coll[updated_permission.entity_id] + +class GroupPermissionServiceClient(BaseUpdatableModelServiceClient): + """ + Service class that interfaces with the Argus alert Group Permissions endpoint. + """ + def __init__(self, argus): + super(GroupPermissionServiceClient, self).__init__([], argus, "grouppermission", "grouppermission/getvalidgroupkeys") + + def get_groups_with_valid_permissions(self, group_ids): + """ + Checks if the group ids specified have valid permissions + :return: the a list of strings representing group id's that have valid permissions. + """ + + groups_with_valid_permissions = self.argus._request("get", "grouppermission/getvalidgroupkeys", + params=dict(groupIds=group_ids)) + return groups_with_valid_permissions def convert(input): if isinstance(input, Mapping): @@ -880,6 +933,7 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non self.users = UsersServiceClient(self) self.namespaces = NamespacesServiceClient(self) self.alerts = AlertsServiceClient(self) + self.group_permissions = GroupPermissionServiceClient(self) self.conn = requests.Session() def login(self): @@ -930,9 +984,13 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE headers = {"Content-Type": "application/json"} if self.accessToken: headers["Authorization"] = "Bearer "+self.accessToken + + # print "url "+ str(url) + " data "+ str(data) + "params "+ str(params) + "headers "+ str(headers) resp = req_method(url, data=data, params=params, headers=headers, - timeout=self.timeout) + timeout=self.timeout, + verify=False) + # print resp res = check_success(resp, decCls) return res diff --git a/argusclient/model.py b/argusclient/model.py index 82184fd..8123e0e 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -262,11 +262,12 @@ class Permission(BaseEncodable): :type entityId: int """ - id_fields = ("permissionNames",) - - def __init__(self, type, permissionNames, **kwargs): - super(Permission, self).__init__(type=type, permissionNames=permissionNames, **kwargs) + id_fields = ("type",) + VALID_TYPES = frozenset(("user", "group")) + def __init__(self, type, **kwargs): + assert type in Permission.VALID_TYPES, "permission type is not valid: %s" % type + super(Permission, self).__init__(type=type, **kwargs) class Namespace(BaseEncodable): """ diff --git a/tests/test_data.py b/tests/test_data.py index eb67748..a44a8c2 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -38,6 +38,12 @@ userPermissionIdentifier = "user" permissionNames = ["VIEW", "EDIT", "DELETE"] permissionGroupId = '24231-52321-43523-64353-23111' +username = "testuser" +permission_ids = [1,2,3] +user_type = "user" +group_type = "group" +group_id = "c8be7819-bf5e-40aa-8535-88694d34280f" +entity_id = 23590046 compAlertID = 6000 childAlertID_1 = 6003 @@ -128,6 +134,32 @@ "username": userName } +permission_user_D = { + "id": testId, + "createdById": 6906380, + "createdDate": 1616098911000, + "modifiedById": 6906380, + "modifiedDate": 1616098911000, + "type": user_type, + "username": userName, + "permissionIds": permission_ids, + "entityId": testId, + "groupId": "" +} + +permission_group_D = { + "id": testId, + "createdById": 6906380, + "createdDate": 1616098911000, + "modifiedById": 6906380, + "modifiedDate": 1616098911000, + "type": group_type, + "groupId": group_id, + "username": '', + "permissionIds": [], + "entityId": testId +} + namespace_D = { "id": testId, "createdById": 101851, diff --git a/tests/test_modelobjs.py b/tests/test_modelobjs.py index 7abd160..00126a9 100644 --- a/tests/test_modelobjs.py +++ b/tests/test_modelobjs.py @@ -159,6 +159,22 @@ def testCreateNotification(self): def testCreateNotificationInvalidNotifier(self): self.failUnlessRaises(AssertionError, lambda: Notification(notificationName, "abc")) + def testCreateUserPermission(self): + permission = Permission(user_type, id=testId, permissionIds=permission_ids, username=username, entityId=testId) + self.assertEquals(permission.type, user_type) + self.assertEquals(permission.entityId, testId) + self.assertEquals(permission.permissionIds, permission_ids) + self.assertEquals(permission.username, username) + + def testCreateGroupPermission(self): + permission = Permission(group_type, id=testId, groupId=group_id, entityId=testId) + self.assertEquals(permission.type, group_type) + self.assertEquals(permission.entityId, testId) + self.assertEquals(permission.groupId, group_id) + + def testCreateInvalidPermission(self): + self.failUnlessRaises(AssertionError, lambda: Permission("abc", id=testId)) + def testCreateAlertDeep(self): trigger = Trigger(triggerName, Trigger.EQUAL, 100, 200) notification = Notification(notificationName, notifierName=Notification.EMAIL, subscriptions=[email]) diff --git a/tests/test_service.py b/tests/test_service.py index 8e15769..efdc8c3 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -447,6 +447,26 @@ def testGetPermissions(self, mockPost): self.assertTrue(isinstance(p, Permission)) self.assertIn((os.path.join(endpoint, "permission/entityIds"),), tuple(mockPost.call_args)) + def testAddInvalidPermission(self): + self.failUnlessRaises(TypeError, lambda: self.argus.permissions.add(entity_id, dict())) + self.failUnlessRaises(ValueError, lambda: self.argus.permissions.add(entity_id, Permission.from_dict(permission_user_D))) + + @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(permission_user_D), 200)) + def testAddPermission(self, mockPost): + user_permission = Permission.from_dict(permission_user_D) + delattr(user_permission, "id") + res = self.argus.permissions.add(testId, user_permission) + self.assertTrue(isinstance(res, Permission)) + self.assertTrue(hasattr(res, "id")) + self.assertIn((os.path.join(endpoint, "permission", str(testId)),), tuple(mockPost.call_args)) + self.assertEquals(self.argus.permissions[testId].argus_id, testId) + + @mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(permission_user_D), 200)) + def testDeletePermission(self, mockDelete): + self.argus.permissions.delete(testId, Permission.from_dict(permission_user_D)) + self.assertIn((os.path.join(endpoint, "permission", str(testId)),), tuple(mockDelete.call_args)) + + class TestNamespace(TestServiceBase): def testAddInvalidNamespace(self): self.failUnlessRaises(TypeError, lambda: self.argus.namespaces.add(dict())) From 59c15f77db21396737ba73b26fb29c673c3e4eeb Mon Sep 17 00:00:00 2001 From: Sanjana Chandrashekar Date: Mon, 9 Aug 2021 23:56:36 -0700 Subject: [PATCH 02/24] Removed unnecessary logs --- argusclient/client.py | 19 ------------------- 1 file changed, 19 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index d23d0fc..46f3f36 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -482,23 +482,6 @@ def delete(self, entity_id, permission): if updated_permission.entityId in self._coll: del self._coll[updated_permission.entity_id] -class GroupPermissionServiceClient(BaseUpdatableModelServiceClient): - """ - Service class that interfaces with the Argus alert Group Permissions endpoint. - """ - def __init__(self, argus): - super(GroupPermissionServiceClient, self).__init__([], argus, "grouppermission", "grouppermission/getvalidgroupkeys") - - def get_groups_with_valid_permissions(self, group_ids): - """ - Checks if the group ids specified have valid permissions - :return: the a list of strings representing group id's that have valid permissions. - """ - - groups_with_valid_permissions = self.argus._request("get", "grouppermission/getvalidgroupkeys", - params=dict(groupIds=group_ids)) - return groups_with_valid_permissions - def convert(input): if isinstance(input, Mapping): return {convert(key): convert(value) for key, value in input.iteritems()} @@ -985,12 +968,10 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE if self.accessToken: headers["Authorization"] = "Bearer "+self.accessToken - # print "url "+ str(url) + " data "+ str(data) + "params "+ str(params) + "headers "+ str(headers) resp = req_method(url, data=data, params=params, headers=headers, timeout=self.timeout, verify=False) - # print resp res = check_success(resp, decCls) return res From be0c36bdf9a1c36ef8d9faeb2e02efadd6b2afa7 Mon Sep 17 00:00:00 2001 From: Sanjana Chandrashekar Date: Tue, 10 Aug 2021 00:19:03 -0700 Subject: [PATCH 03/24] Updated formatting --- argusclient/client.py | 11 ++++++----- tests/test_service.py | 4 ++-- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 46f3f36..f1106e2 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -409,6 +409,7 @@ def get_user_dashboards(self, ownerName=None, shared=True, limit=None, version=N """ return self.argus._request("get", "dashboards", params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) + class PermissionsServiceClient(BaseUpdatableModelServiceClient): """ Service class that interfaces with the Argus permissions endpoint. @@ -451,11 +452,11 @@ def get_permissions_for_entities(self, entity_ids): if entityIds: response = convert(self.argus._request("post", "permission/entityIds", dataObj=entityIds)) - for id, perms in response.items(): - self._coll[id] = perms + if response: + for id, perms in response.items(): + self._coll[id] = perms return self._coll - def add(self, entity_id, permission): """ Associates a permission with an alert @@ -480,7 +481,8 @@ def delete(self, entity_id, permission): raise ValueError("A user permission needs to have the permission that needs to be revoked") updated_permission = self.argus._request("delete", "permission/%s" % entity_id, dataObj=permission) if updated_permission.entityId in self._coll: - del self._coll[updated_permission.entity_id] + del self._coll[updated_permission.entityId] + def convert(input): if isinstance(input, Mapping): @@ -916,7 +918,6 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non self.users = UsersServiceClient(self) self.namespaces = NamespacesServiceClient(self) self.alerts = AlertsServiceClient(self) - self.group_permissions = GroupPermissionServiceClient(self) self.conn = requests.Session() def login(self): diff --git a/tests/test_service.py b/tests/test_service.py index efdc8c3..fd6c0da 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -394,8 +394,8 @@ def testGetItems(self, mockGet): class TestPermission(TestServiceBase): @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) def testGetPermissionsBadId(self, mockPost): - res = self.argus.permissions.get_permissions_for_entities(testId) - self.assertIsNone(res) + res = self.argus.permissions.get_permissions_for_entities([testId]) + self.assertEquals(len(res), 0) self.assertIn((os.path.join(endpoint, "permission/entityIds"),), tuple(mockPost.call_args)) @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D, groupPermission_D], From 14945b07727556773dd485f0b739a1a024562225 Mon Sep 17 00:00:00 2001 From: Sanjana Chandrashekar Date: Tue, 10 Aug 2021 11:16:33 -0700 Subject: [PATCH 04/24] Removed attributes used for testing --- argusclient/client.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index f1106e2..8dc044f 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -971,8 +971,7 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE resp = req_method(url, data=data, params=params, headers=headers, - timeout=self.timeout, - verify=False) + timeout=self.timeout) res = check_success(resp, decCls) return res From b9405fef1d67dec46d267c37c8b1909c104b0215 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 8 Jul 2021 14:40:26 -0700 Subject: [PATCH 05/24] updated api for groups --- argusclient/client.py | 157 +++++++++++++++++++++++++++++++----------- argusclient/model.py | 7 ++ 2 files changed, 122 insertions(+), 42 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 8dc044f..0051ab6 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -4,52 +4,55 @@ and `web service reference `__. """ +import json +import logging +import os # # Copyright (c) 2016, salesforce.com, inc. # All rights reserved. -# Licensed under the BSD 3-Clause license. +# Licensed under the BSD 3-Clause license. # For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause # -import unicodedata from collections import Mapping import requests -import json -import os -import logging -import collections + try: import http.client as httplib # Python 3 except ImportError: - import httplib # Python 2 + import httplib # Python 2 from functools import wraps from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, JsonEncoder, JsonDecoder, \ - Permission + Permission, GroupPermission REQ_METHOD = "req_method" REQ_PATH = "req_path" REQ_PARAMS = "req_params" REQ_BODY = "req_body" + class ArgusException(Exception): """ An exception type that is thrown for Argus service errors. """ pass + class ArgusAuthException(ArgusException): """ An exception type that is thrown for Argus authentication errors. """ pass + class ArgusObjectNotFoundException(ArgusException): """ An exception type that is thrown for Argus object not found errors. """ pass + class BaseQuery(object): def __init__(self, baseExpr, *tailParams, **kwargs): self.baseExpr = baseExpr @@ -80,9 +83,12 @@ class MetricQuery(BaseQuery): >>> print str(mquery) -1d:-0d:test.scope:test.metric{test.tag=test.value}:sum:test.namespace """ - def __init__(self, scope, metric, aggregator, tags=None, namespace=None, downsampler=None, stTimeSpec=None, enTimeSpec=None): + + def __init__(self, scope, metric, aggregator, tags=None, namespace=None, downsampler=None, stTimeSpec=None, + enTimeSpec=None): # NOTE: Namespace no longer goes into the metric expression, so we pass it down as a tail parameter. - super(MetricQuery, self).__init__(str(Metric(scope, metric, tags=tags)), aggregator, downsampler, namespace, stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) + super(MetricQuery, self).__init__(str(Metric(scope, metric, tags=tags)), aggregator, downsampler, namespace, + stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) class AnnotationQuery(BaseQuery): @@ -94,8 +100,10 @@ class AnnotationQuery(BaseQuery): >>> print str(mquery) -1d:-0d:test.scope:test.metric{test.tag=test.value}:test.source """ + def __init__(self, scope, metric, source, tags=None, stTimeSpec=None, enTimeSpec=None): - super(AnnotationQuery, self).__init__(str(Annotation(source, scope, metric, None, None, None, tags=tags)), stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) + super(AnnotationQuery, self).__init__(str(Annotation(source, scope, metric, None, None, None, tags=tags)), + stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) class BaseCollectionServiceClient(object): @@ -121,7 +129,8 @@ def add(self, data): :return: :class:`argusclient.model.AddListResult` object with a summary of the operation. """ if not data: raise ValueError("need a value for data parameter") - if not isinstance(data, list) or not isinstance(data[0], self.obj_type): raise TypeError("data should be a list of %s objects" % self.obj_type) + if not isinstance(data, list) or not isinstance(data[0], self.obj_type): raise TypeError( + "data should be a list of %s objects" % self.obj_type) return self.argus._request("post", self.coll_path, dataObj=data) @@ -131,6 +140,7 @@ class MetricCollectionServiceClient(BaseCollectionServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.metrics` attribute. """ + def __init__(self, argus): super(MetricCollectionServiceClient, self).__init__(MetricQuery, Metric, argus, "metrics", "collection/metrics") @@ -141,8 +151,10 @@ class AnnotationCollectionServiceClient(BaseCollectionServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.annotations` attribute. """ + def __init__(self, argus): - super(AnnotationCollectionServiceClient, self).__init__(AnnotationQuery, Annotation, argus, "annotations", "collection/annotations") + super(AnnotationCollectionServiceClient, self).__init__(AnnotationQuery, Annotation, argus, "annotations", + "collection/annotations") class BaseModelServiceClient(object): @@ -163,9 +175,11 @@ def _init_all(self, coll=None): if not self._retrieved_all: self._coll = dict((obj.argus_id, self._fill(obj)) for obj in (coll or self.argus._request(self.get_all_req_opts.get(REQ_METHOD, "get"), - self.get_all_req_opts.get(REQ_PATH, None), - params=self.get_all_req_opts.get(REQ_PARAMS, None), - dataObj=self.get_all_req_opts.get(REQ_BODY, None)))) + self.get_all_req_opts.get(REQ_PATH, None), + params=self.get_all_req_opts.get(REQ_PARAMS, + None), + dataObj=self.get_all_req_opts.get(REQ_BODY, + None)))) self._retrieved_all = True def _fill(self, obj): @@ -246,6 +260,7 @@ class UsersServiceClient(BaseModelServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.users` attribute. """ + def __init__(self, argus): super(UsersServiceClient, self).__init__(argus) self._coll_by_name = {} @@ -276,6 +291,7 @@ class NamespacesServiceClient(BaseModelServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.namespaces` attribute. """ + def __init__(self, argus): super(NamespacesServiceClient, self).__init__(argus, get_all_req_opts={REQ_PATH: "namespace"}) @@ -288,7 +304,8 @@ def update(self, id, namespace): if not id: raise ValueError("Need to specify an id to update namespace") id = int(id) if not namespace.argus_id: raise ValueError("Namespace needs an id to update") - if id != namespace.argus_id: raise ValueError("Namespace id: %s doesn't match the id: %s that you are updating" % (namespace.id, id)) + if id != namespace.argus_id: raise ValueError( + "Namespace id: %s doesn't match the id: %s that you are updating" % (namespace.id, id)) self._coll[id] = self.argus._request("put", "namespace/%s" % id, dataObj=namespace) return self._coll[id] @@ -342,7 +359,8 @@ def update(self, id, obj): if not isinstance(obj, self.objType): raise TypeError("Need an object of type: %s" % self.objType) if not obj.argus_id: raise ValueError("Object needs an id to update") # Ensure that user doesn't accidentally copy another item. - if id != obj.argus_id: raise ValueError("Object id: %s doesn't match the id: %s that you are updating" % (obj.id, id)) + if id != obj.argus_id: raise ValueError( + "Object id: %s doesn't match the id: %s that you are updating" % (obj.id, id)) self._coll[id] = self.argus._request("put", self.id_path % id, dataObj=obj) return self._coll[id] @@ -363,6 +381,7 @@ class DashboardsServiceClient(BaseUpdatableModelServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.dashboards` attribute. """ + def __init__(self, argus, get_all_req_opts=None): """ :param get_all_req_opts: See BaseModelServiceClient.__init__() for description. @@ -393,7 +412,8 @@ def get_user_dashboard(self, ownerName, dashboardName, shared=True): """ assert dashboardName, "Expected a dashboard name" assert ownerName, "Expected a owner name" - dashboards = self.argus._request("get", "dashboards", params=dict(dashboardName=dashboardName, owner=ownerName, shared=shared)) + dashboards = self.argus._request("get", "dashboards", + params=dict(dashboardName=dashboardName, owner=ownerName, shared=shared)) if not dashboards: return None else: @@ -407,7 +427,36 @@ def get_user_dashboards(self, ownerName=None, shared=True, limit=None, version=N :return: a list of :class:`argusclient.model.Dashboard` objects with all fields populated. """ - return self.argus._request("get", "dashboards", params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) + return self.argus._request("get", "dashboards", + params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) + + +class GroupPermissionsServiceCleint(BaseUpdatableModelServiceClient): + """ + Service class that interfaces with the Argus grouppermissions endpoint. + + There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.permissions` attribute. + """ + + def __init__(self, argus, get_all_req_opts=None): + """ + :param get_all_req_opts: See BaseModelServiceClient.__init__() for description. + """ + if not get_all_req_opts: + get_all_req_opts = {} + get_all_req_opts.setdefault(REQ_PATH, "dashboards") + super(DashboardsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/%s", + get_all_req_opts=get_all_req_opts) + + def get_permissions_for_group(self, groupId): + return convert(self.argus._request("get", "grouppermission", dataObj=groupId)) + + def add_permissions_for_group(self, groupId): + return convert(self.argus._request("post", "grouppermission", dataObj=groupId)) + + def delete_permissions_for_group(self, groupId): + return self.argus._request("delete", "grouppermission/%" % groupId) + class PermissionsServiceClient(BaseUpdatableModelServiceClient): @@ -416,6 +465,7 @@ class PermissionsServiceClient(BaseUpdatableModelServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.permissions` attribute. """ + def __init__(self, argus, get_all_req_opts=None): """ :param get_all_req_opts: See BaseModelServiceClient.__init__() for description. @@ -432,9 +482,9 @@ def _init_all(self, coll=None): raise TypeError("Unsupported operation on: %s" % type(self)) if not self._retrieved_all: resp = convert(self.argus._request(self.get_all_req_opts.get(REQ_METHOD, "get"), - self.get_all_req_opts.get(REQ_PATH, None), - params=self.get_all_req_opts.get(REQ_PARAMS, None), - dataObj=self.get_all_req_opts.get(REQ_BODY, None))) + self.get_all_req_opts.get(REQ_PATH, None), + params=self.get_all_req_opts.get(REQ_PARAMS, None), + dataObj=self.get_all_req_opts.get(REQ_BODY, None))) for id, perms in resp.items(): self._coll[id] = perms self._retrieved_all = True @@ -484,6 +534,7 @@ def delete(self, entity_id, permission): del self._coll[updated_permission.entityId] + def convert(input): if isinstance(input, Mapping): return {convert(key): convert(value) for key, value in input.iteritems()} @@ -517,6 +568,7 @@ class AlertsServiceClient(BaseUpdatableModelServiceClient): Interfaces with the Argus alert notifications endpoint. """ + def __init__(self, argus, get_all_req_opts=None): """ :param get_all_req_opts: See BaseModelServiceClient.__init__() for description. @@ -580,7 +632,8 @@ def get_notification_trigger(self, alertid, notificationid, triggerid): if not notificationid: raise ValueError("Need to specify a notificationid") if not triggerid: raise ValueError("Need to specify a triggerid") # TODO: Update self._coll - return self.argus._request("get", "alerts/%s/notifications/%s/triggers/%s" % (alertid, notificationid, triggerid)) + return self.argus._request("get", + "alerts/%s/notifications/%s/triggers/%s" % (alertid, notificationid, triggerid)) def add_notification_trigger(self, alertid, notificationid, triggerid): """ @@ -592,7 +645,8 @@ def add_notification_trigger(self, alertid, notificationid, triggerid): if not notificationid: raise ValueError("Need to specify a notificationid") if not triggerid: raise ValueError("Need to specify a triggerid") # TODO: Update self._coll - return self.argus._request("post", "alerts/%s/notifications/%s/triggers/%s" % (alertid, notificationid, triggerid)) + return self.argus._request("post", + "alerts/%s/notifications/%s/triggers/%s" % (alertid, notificationid, triggerid)) def delete_notification_trigger(self, alertid, notificationid, triggerid): """ @@ -612,7 +666,8 @@ def get_user_alert(self, ownerName, alertName, shared=True): """ assert alertName, "Expected an alert name" assert ownerName, "Expected a owner name" - alerts = self.argus._request("get", "alerts/meta", params=dict(alertname=alertName, ownername=ownerName, shared=shared)) + alerts = self.argus._request("get", "alerts/meta", + params=dict(alertname=alertName, ownername=ownerName, shared=shared)) if not alerts: return None else: @@ -627,7 +682,9 @@ def get_alerts_allinfo(self, ownerName=None, alertNameContains=None, shared=Fals :return: the list of :class:`argusclient.model.Alert` objects, with all fields populated, including triggers and notifications """ - return self.argus._request("get", "alerts/allinfo", params=dict(ownername=ownerName, alertNameContains=alertNameContains, shared=shared, limit=limit)) + return self.argus._request("get", "alerts/allinfo", + params=dict(ownername=ownerName, alertNameContains=alertNameContains, shared=shared, + limit=limit)) ''' Functions to enable support for composite alerts @@ -647,7 +704,7 @@ def get_composite_alert_children(self, comp_alert_id): uri_path = "alerts/{}/children".format(comp_alert_id) child_alerts = self.argus._request("get", uri_path) child_alerts = [self._fill(child_alert) for child_alert in child_alerts] - return child_alerts + return child_alerts def get_composite_alert_children_info(self, comp_alert_id): """ @@ -664,7 +721,6 @@ def get_composite_alert_children_info(self, comp_alert_id): uri_path = "alerts/{}/children/info".format(comp_alert_id) return self.argus._request("get", uri_path) - def add_child_alert_to_composite_alert(self, comp_alert_id, alert): """ Add child alert to a composite alert @@ -687,7 +743,6 @@ def add_child_alert_to_composite_alert(self, comp_alert_id, alert): self._coll[alert_obj.id] = alert_obj return alert_obj - def delete_child_alert_from_composite_alert(self, comp_alert_id, child_alert_id): """ Delete a child alert from a composite alert @@ -700,7 +755,8 @@ def delete_child_alert_from_composite_alert(self, comp_alert_id, child_alert_id) """ if not comp_alert_id: raise ValueError("Need to specify a composite alert id") if not child_alert_id: raise ValueError("Need to specify a child alert id") - if not isinstance(comp_alert_id, int): raise TypeError("Need a composite Alert ID, got: %s" % type(comp_alert_id)) + if not isinstance(comp_alert_id, int): raise TypeError( + "Need a composite Alert ID, got: %s" % type(comp_alert_id)) if not isinstance(child_alert_id, int): raise TypeError("Need an Alert ID, got: %s" % type(child_alert_id)) uri_path = "alerts/{}/children/{}".format(comp_alert_id, child_alert_id) @@ -739,7 +795,8 @@ def add(self, trigger): try: return next(t for t in triggers if t.name == trigger.name) except StopIteration: - raise ArgusException("This is unexpected... trigger: %s not found after successfully adding it" % trigger.name) + raise ArgusException( + "This is unexpected... trigger: %s not found after successfully adding it" % trigger.name) def delete(self, id): super(AlertTriggersServiceClient, self).delete(id) @@ -752,11 +809,14 @@ class AlertNotificationsServiceClient(BaseUpdatableModelServiceClient): There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.AlertsServiceClient.notifications` attribute. """ + def __init__(self, argus, alert): assert alert, "Expected an alert at this point" assert alert.id, "Alert expected to have an id at this point" - super(AlertNotificationsServiceClient, self).__init__(Notification, argus, id_path="alerts/%s/notifications/%%s" % alert.id, - get_all_req_opts={REQ_PATH: "alerts/%s/notifications" % alert.id}) + super(AlertNotificationsServiceClient, self).__init__(Notification, argus, + id_path="alerts/%s/notifications/%%s" % alert.id, + get_all_req_opts={ + REQ_PATH: "alerts/%s/notifications" % alert.id}) self.alert = alert if alert.notifications: self._init_all(alert.notifications) @@ -767,7 +827,8 @@ def add(self, notification): :return: the added :class:`argusclient.model.Notification` with all fields populated. """ - if not isinstance(notification, Notification): raise TypeError("Need a Notification object, got: %s" % type(notification)) + if not isinstance(notification, Notification): raise TypeError( + "Need a Notification object, got: %s" % type(notification)) if notification.argus_id: raise ValueError("A new Notification can't have an id") notifications = self.argus._request("post", "alerts/%s/notifications" % self.alert.id, dataObj=notification) self._init_all(notifications) @@ -775,7 +836,8 @@ def add(self, notification): try: return next(n for n in notifications if n.name == notification.name) except StopIteration: - raise ArgusException("This is unexpected... notification: %s not found after successfully adding it" % notification.name) + raise ArgusException( + "This is unexpected... notification: %s not found after successfully adding it" % notification.name) def delete(self, id): super(AlertNotificationsServiceClient, self).delete(id) @@ -806,8 +868,8 @@ def with_auth_token(*args, **kwargs): if not argus.accessToken and argus.refreshToken: try: res = argus._request_no_auth("post", - "v2/auth/token/refresh", - dataObj=dict(refreshToken=argus.refreshToken)) + "v2/auth/token/refresh", + dataObj=dict(refreshToken=argus.refreshToken)) argus.accessToken = res["accessToken"] except ArgusAuthException: if argus.password: @@ -817,8 +879,8 @@ def with_auth_token(*args, **kwargs): if not argus.accessToken and argus.password: argus.refreshToken = None res = argus._request_no_auth("post", - "v2/auth/login", - dataObj=dict(username=argus.user, password=argus.password)) + "v2/auth/login", + dataObj=dict(username=argus.user, password=argus.password)) argus.refreshToken, argus.accessToken = res["refreshToken"], res["accessToken"] try: @@ -860,6 +922,12 @@ class ArgusServiceClient(object): Interfaces with the Argus permissions endpoint. + ..attribute:: grouppermissions + + :class: `argusclient.client.GroupPermissionsServiceClient` + + Interfaces with the argus group permissions endpoint + .. attribute:: users :class:`argusclient.client.UsersServiceClient` @@ -897,6 +965,7 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non :param accessToken: A token that can be used to authenticate with Argus. If a ``refreshToken`` or ``password`` is specified, the ``accessToken`` will be refreshed as and when it is needed. :type refreshToken: str """ + if not user: raise ValueError("A valid user must be specified") if not any((password, refreshToken, accessToken)): @@ -917,6 +986,7 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non self.permissions = PermissionsServiceClient(self) self.users = UsersServiceClient(self) self.namespaces = NamespacesServiceClient(self) + self.grouppermissions = GroupPermission(self) self.alerts = AlertsServiceClient(self) self.conn = requests.Session() @@ -935,7 +1005,7 @@ def logout(self): Logs out of the Argus service and destroys the session. """ # The new V2 auth doesn't support a logout, so just clear the tokens. - #self._request("get", "auth/logout") + # self._request("get", "auth/logout") self.refreshToken = self.accessToken = None @retry_auth @@ -963,12 +1033,15 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE url = os.path.join(self.endpoint, path) req_method = getattr(self.conn, method) data = dataObj and json.dumps(dataObj, cls=encCls) or None - logging.debug("%s request with params: %s data length %s on: %s", method.upper(), params, data and len(data) or 0, url) # Mainly for the sake of data length + logging.debug("%s request with params: %s data length %s on: %s", method.upper(), params, + data and len(data) or 0, url) # Mainly for the sake of data length # Argus seems to recognized "Accept" header for "application/json" and "application/ms-excel", but the former is the default. headers = {"Content-Type": "application/json"} if self.accessToken: + headers["Authorization"] = "Bearer "+self.accessToken + resp = req_method(url, data=data, params=params, headers=headers, timeout=self.timeout) diff --git a/argusclient/model.py b/argusclient/model.py index 8123e0e..f9f5e7d 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -269,6 +269,13 @@ def __init__(self, type, **kwargs): assert type in Permission.VALID_TYPES, "permission type is not valid: %s" % type super(Permission, self).__init__(type=type, **kwargs) +class GroupPermission(BaseEncodable): + + id_fields = ("groupId",) + + def __init__(self, type, groupId, **kwargs): + super(GroupPermission, self).__init__(type=type, groupId=groupId, **kwargs) + class Namespace(BaseEncodable): """ Represents a Namespace object in Argus. From 3bad2fe773b2b5b805ce53b950bbb5bf51537834 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Mon, 12 Jul 2021 12:37:20 -0700 Subject: [PATCH 06/24] updates to client for groups API --- argusclient/client.py | 12 +++--- argusclient/model.py | 6 +++ tests/test_data.py | 5 ++- tests/test_group.py | 91 +++++++++++++++++++++++++++++++++++++++++++ tests/test_service.py | 13 ++++++- 5 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 tests/test_group.py diff --git a/argusclient/client.py b/argusclient/client.py index 0051ab6..b5de5c5 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -24,7 +24,7 @@ from functools import wraps from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, JsonEncoder, JsonDecoder, \ - Permission, GroupPermission + Permission, GroupPermission, basestring REQ_METHOD = "req_method" REQ_PATH = "req_path" @@ -431,7 +431,7 @@ def get_user_dashboards(self, ownerName=None, shared=True, limit=None, version=N params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) -class GroupPermissionsServiceCleint(BaseUpdatableModelServiceClient): +class GroupPermissionsServiceClient(BaseUpdatableModelServiceClient): """ Service class that interfaces with the Argus grouppermissions endpoint. @@ -445,7 +445,7 @@ def __init__(self, argus, get_all_req_opts=None): if not get_all_req_opts: get_all_req_opts = {} get_all_req_opts.setdefault(REQ_PATH, "dashboards") - super(DashboardsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/%s", + super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission", get_all_req_opts=get_all_req_opts) def get_permissions_for_group(self, groupId): @@ -455,7 +455,7 @@ def add_permissions_for_group(self, groupId): return convert(self.argus._request("post", "grouppermission", dataObj=groupId)) def delete_permissions_for_group(self, groupId): - return self.argus._request("delete", "grouppermission/%" % groupId) + return self.argus._request("delete", "grouppermission" % groupId) @@ -986,7 +986,7 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non self.permissions = PermissionsServiceClient(self) self.users = UsersServiceClient(self) self.namespaces = NamespacesServiceClient(self) - self.grouppermissions = GroupPermission(self) + self.grouppermissions = GroupPermissionsServiceClient(self) self.alerts = AlertsServiceClient(self) self.conn = requests.Session() @@ -1044,7 +1044,7 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE resp = req_method(url, data=data, params=params, headers=headers, - timeout=self.timeout) + timeout=self.timeout, verify=False) res = check_success(resp, decCls) return res diff --git a/argusclient/model.py b/argusclient/model.py index f9f5e7d..c22e4aa 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -270,6 +270,12 @@ def __init__(self, type, **kwargs): super(Permission, self).__init__(type=type, **kwargs) class GroupPermission(BaseEncodable): + """ + Represents a Group permission object in Argus + + :param groupId : the id of the group to be given permissions to + :type groupId: str + """ id_fields = ("groupId",) diff --git a/tests/test_data.py b/tests/test_data.py index a44a8c2..7bf4148 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -36,6 +36,7 @@ notificationName = "test.notification" groupPermissionIdentifier = "group" userPermissionIdentifier = "user" +groupID = "5eb1fc18-c985-47eb-94f9-aebce66e119a" permissionNames = ["VIEW", "EDIT", "DELETE"] permissionGroupId = '24231-52321-43523-64353-23111' username = "testuser" @@ -374,7 +375,7 @@ 'id': triggerID_1, 'threshold': 1.0, 'type': 'GREATER_THAN', - 'inertia': 0L, + 'inertia': 0, 'name': 'CompAlertTest/trigger1' } @@ -385,7 +386,7 @@ 'subscriptions': ['jdoe@example.com'], 'notifierName': 'com.salesforce.dva.argus.service.alert.notifier.EmailNotifier', 'metricsToAnnotate': [], - 'cooldownPeriod': 0L, + 'cooldownPeriod': 0, 'sractionable': False, 'customText': 'None' } \ No newline at end of file diff --git a/tests/test_group.py b/tests/test_group.py new file mode 100644 index 0000000..6309b2d --- /dev/null +++ b/tests/test_group.py @@ -0,0 +1,91 @@ +# +# Copyright (c) 2016, salesforce.com, inc. +# All rights reserved. +# Licensed under the BSD 3-Clause license. +# For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause +# +# Use the package in this repo (argusclient directory) +import json +import pprint +from argusclient import ArgusServiceClient, Notification, Trigger, Dashboard +import os +import unittest +from argusclient import * +from argusclient.client import AlertNotificationsServiceClient, GroupPermissionsServiceClient, AlertsServiceClient, PermissionsServiceClient, \ + DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY +from argusclient.model import Permission +""" +LOGGING IN!~ +""" +username = "s.basu" +password = "SanFrancisco2021!" +argus = ArgusServiceClient(username, + password, + endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") + # endpoint = "https://argus-ws.data.sfdc.net/argusws/") +print ('logging in...') +argus.login() +print ('logged in!') +""" +Set endpoint and params +""" +# argus.alerts = AlertsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False, +# alertNameContains='TestAlert', +# limit=1), +# REQ_PATH: "allinfo"}) +permission_group_D = { + "id": 10, + "createdById": 6906380, + "createdDate": 1616098911000, + "modifiedById": 6906380, + "modifiedDate": 1616098911000, + "type": "group", + "groupId": "c8be7819-bf5e-40aa-8535-88694d34280f", + "username": '', + "permissionIds": [], + "entityId": 23590046 +} +argus.permissions = PermissionsServiceClient(argus) +group_perm = Permission.from_dict(permission_group_D) +# delattr(group_perm, "id") +# deleted_perm = argus.permissions.delete(23590046, group_perm) +# +# print "updating perm" +# updated_perm = argus.permissions.add(23590046, group_perm) +# print "updated permission is "+ str(updated_perm) +print ("making call to get perms for entities") +all_perms = argus.permissions.get_permissions_for_entities([26947204]) +print (all_perms) +print (type(all_perms)) +for id, val in all_perms.items(): + print (id) + print (type(val)) + for perm in val: + perm_type = perm.type + if perm_type == 'group': + print (perm.groupId) + else: + print (perm.username) +# argus.permissions = PermissionsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False), +# REQ_PATH: "entityIds", +# REQ_METHOD: "post", +# REQ_BODY: [14796957, 14796958]}) +# argus.dashboards = DashboardsServiceClient(argus, get_all_req_opts=dict(REQ_PARAMS=dict(username="j.ma", shared=False, limit=3))) # note - limit does not work +""" +Making the call +""" +if __name__ == '__main__': + + # print 'calling items()' + # res = argus.alerts.items() + # res = argus.permissions.items() + # res = argus.dashboards.items() + res = argus.grouppermissions.get() + # res = argus.permissions.get(16348603) + # Get notif + # alert = res[0][1] + # print 'notifs:', alert.notifications.items() + # notifs = alert.notifications.items() + # notif = notifs[0][1] + # print '\nresult: ', res + print ('size of result: ', len(res)) \ No newline at end of file diff --git a/tests/test_service.py b/tests/test_service.py index fd6c0da..9093f79 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -9,11 +9,11 @@ import unittest from argusclient import * -from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, PermissionsServiceClient, \ +from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, GroupPermissionsServiceClient, PermissionsServiceClient, \ DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY from argusclient.model import Permission -from test_data import * +from tests.test_data import * try: import mock # Python 2 @@ -198,6 +198,9 @@ def testInvalidRefreshTokenWithDirectAccessToken(self): self.assertEquals((os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"),), called_endpoints(mockConn.get)) self.assertEquals(3, mockConn.get.call_count) + + + def testInvalidPasswordWithDirectRefreshToken(self): """Test inability to refresh refresh token as there is no password""" self.argus.refreshToken = "refresh" @@ -390,6 +393,12 @@ def testGetItems(self, mockGet): self.assertIn((os.path.join(endpoint, "dashboards"),), tuple(mockGet.call_args)) self.assertEquals(len(mockGet.call_args_list), 1) +class TestGroupPermissions(TestServiceBase): + @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) + def testGroupPermissionsWrongID(self, mockPost): + res = self.argus.grouppermissions.get(permissionGroupId) + self.assertIsNone(res) + self.assertIn((os.path.join(endpoint, "grouppermission/groupIds"),), tuple(mockPost.call_args)) class TestPermission(TestServiceBase): @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) From ac2757dfc5af6b0831e4d229a5bcbc1c6e42a7cb Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Tue, 13 Jul 2021 11:46:21 -0700 Subject: [PATCH 07/24] Revert "updates to client for groups API" This reverts commit 9283776e880ec70b0a1badd0db2c70c509cbeae9. --- argusclient/client.py | 12 +++--- argusclient/model.py | 6 --- tests/test_data.py | 5 +-- tests/test_group.py | 91 ------------------------------------------- tests/test_service.py | 13 +------ 5 files changed, 10 insertions(+), 117 deletions(-) delete mode 100644 tests/test_group.py diff --git a/argusclient/client.py b/argusclient/client.py index b5de5c5..0051ab6 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -24,7 +24,7 @@ from functools import wraps from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, JsonEncoder, JsonDecoder, \ - Permission, GroupPermission, basestring + Permission, GroupPermission REQ_METHOD = "req_method" REQ_PATH = "req_path" @@ -431,7 +431,7 @@ def get_user_dashboards(self, ownerName=None, shared=True, limit=None, version=N params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) -class GroupPermissionsServiceClient(BaseUpdatableModelServiceClient): +class GroupPermissionsServiceCleint(BaseUpdatableModelServiceClient): """ Service class that interfaces with the Argus grouppermissions endpoint. @@ -445,7 +445,7 @@ def __init__(self, argus, get_all_req_opts=None): if not get_all_req_opts: get_all_req_opts = {} get_all_req_opts.setdefault(REQ_PATH, "dashboards") - super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission", + super(DashboardsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/%s", get_all_req_opts=get_all_req_opts) def get_permissions_for_group(self, groupId): @@ -455,7 +455,7 @@ def add_permissions_for_group(self, groupId): return convert(self.argus._request("post", "grouppermission", dataObj=groupId)) def delete_permissions_for_group(self, groupId): - return self.argus._request("delete", "grouppermission" % groupId) + return self.argus._request("delete", "grouppermission/%" % groupId) @@ -986,7 +986,7 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non self.permissions = PermissionsServiceClient(self) self.users = UsersServiceClient(self) self.namespaces = NamespacesServiceClient(self) - self.grouppermissions = GroupPermissionsServiceClient(self) + self.grouppermissions = GroupPermission(self) self.alerts = AlertsServiceClient(self) self.conn = requests.Session() @@ -1044,7 +1044,7 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE resp = req_method(url, data=data, params=params, headers=headers, - timeout=self.timeout, verify=False) + timeout=self.timeout) res = check_success(resp, decCls) return res diff --git a/argusclient/model.py b/argusclient/model.py index c22e4aa..f9f5e7d 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -270,12 +270,6 @@ def __init__(self, type, **kwargs): super(Permission, self).__init__(type=type, **kwargs) class GroupPermission(BaseEncodable): - """ - Represents a Group permission object in Argus - - :param groupId : the id of the group to be given permissions to - :type groupId: str - """ id_fields = ("groupId",) diff --git a/tests/test_data.py b/tests/test_data.py index 7bf4148..a44a8c2 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -36,7 +36,6 @@ notificationName = "test.notification" groupPermissionIdentifier = "group" userPermissionIdentifier = "user" -groupID = "5eb1fc18-c985-47eb-94f9-aebce66e119a" permissionNames = ["VIEW", "EDIT", "DELETE"] permissionGroupId = '24231-52321-43523-64353-23111' username = "testuser" @@ -375,7 +374,7 @@ 'id': triggerID_1, 'threshold': 1.0, 'type': 'GREATER_THAN', - 'inertia': 0, + 'inertia': 0L, 'name': 'CompAlertTest/trigger1' } @@ -386,7 +385,7 @@ 'subscriptions': ['jdoe@example.com'], 'notifierName': 'com.salesforce.dva.argus.service.alert.notifier.EmailNotifier', 'metricsToAnnotate': [], - 'cooldownPeriod': 0, + 'cooldownPeriod': 0L, 'sractionable': False, 'customText': 'None' } \ No newline at end of file diff --git a/tests/test_group.py b/tests/test_group.py deleted file mode 100644 index 6309b2d..0000000 --- a/tests/test_group.py +++ /dev/null @@ -1,91 +0,0 @@ -# -# Copyright (c) 2016, salesforce.com, inc. -# All rights reserved. -# Licensed under the BSD 3-Clause license. -# For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause -# -# Use the package in this repo (argusclient directory) -import json -import pprint -from argusclient import ArgusServiceClient, Notification, Trigger, Dashboard -import os -import unittest -from argusclient import * -from argusclient.client import AlertNotificationsServiceClient, GroupPermissionsServiceClient, AlertsServiceClient, PermissionsServiceClient, \ - DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY -from argusclient.model import Permission -""" -LOGGING IN!~ -""" -username = "s.basu" -password = "SanFrancisco2021!" -argus = ArgusServiceClient(username, - password, - endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") - # endpoint = "https://argus-ws.data.sfdc.net/argusws/") -print ('logging in...') -argus.login() -print ('logged in!') -""" -Set endpoint and params -""" -# argus.alerts = AlertsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False, -# alertNameContains='TestAlert', -# limit=1), -# REQ_PATH: "allinfo"}) -permission_group_D = { - "id": 10, - "createdById": 6906380, - "createdDate": 1616098911000, - "modifiedById": 6906380, - "modifiedDate": 1616098911000, - "type": "group", - "groupId": "c8be7819-bf5e-40aa-8535-88694d34280f", - "username": '', - "permissionIds": [], - "entityId": 23590046 -} -argus.permissions = PermissionsServiceClient(argus) -group_perm = Permission.from_dict(permission_group_D) -# delattr(group_perm, "id") -# deleted_perm = argus.permissions.delete(23590046, group_perm) -# -# print "updating perm" -# updated_perm = argus.permissions.add(23590046, group_perm) -# print "updated permission is "+ str(updated_perm) -print ("making call to get perms for entities") -all_perms = argus.permissions.get_permissions_for_entities([26947204]) -print (all_perms) -print (type(all_perms)) -for id, val in all_perms.items(): - print (id) - print (type(val)) - for perm in val: - perm_type = perm.type - if perm_type == 'group': - print (perm.groupId) - else: - print (perm.username) -# argus.permissions = PermissionsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False), -# REQ_PATH: "entityIds", -# REQ_METHOD: "post", -# REQ_BODY: [14796957, 14796958]}) -# argus.dashboards = DashboardsServiceClient(argus, get_all_req_opts=dict(REQ_PARAMS=dict(username="j.ma", shared=False, limit=3))) # note - limit does not work -""" -Making the call -""" -if __name__ == '__main__': - - # print 'calling items()' - # res = argus.alerts.items() - # res = argus.permissions.items() - # res = argus.dashboards.items() - res = argus.grouppermissions.get() - # res = argus.permissions.get(16348603) - # Get notif - # alert = res[0][1] - # print 'notifs:', alert.notifications.items() - # notifs = alert.notifications.items() - # notif = notifs[0][1] - # print '\nresult: ', res - print ('size of result: ', len(res)) \ No newline at end of file diff --git a/tests/test_service.py b/tests/test_service.py index 9093f79..fd6c0da 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -9,11 +9,11 @@ import unittest from argusclient import * -from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, GroupPermissionsServiceClient, PermissionsServiceClient, \ +from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, PermissionsServiceClient, \ DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY from argusclient.model import Permission -from tests.test_data import * +from test_data import * try: import mock # Python 2 @@ -198,9 +198,6 @@ def testInvalidRefreshTokenWithDirectAccessToken(self): self.assertEquals((os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"),), called_endpoints(mockConn.get)) self.assertEquals(3, mockConn.get.call_count) - - - def testInvalidPasswordWithDirectRefreshToken(self): """Test inability to refresh refresh token as there is no password""" self.argus.refreshToken = "refresh" @@ -393,12 +390,6 @@ def testGetItems(self, mockGet): self.assertIn((os.path.join(endpoint, "dashboards"),), tuple(mockGet.call_args)) self.assertEquals(len(mockGet.call_args_list), 1) -class TestGroupPermissions(TestServiceBase): - @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) - def testGroupPermissionsWrongID(self, mockPost): - res = self.argus.grouppermissions.get(permissionGroupId) - self.assertIsNone(res) - self.assertIn((os.path.join(endpoint, "grouppermission/groupIds"),), tuple(mockPost.call_args)) class TestPermission(TestServiceBase): @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) From f40eaf0100d8c1f22f4d90c3946ffde860693d7b Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Tue, 13 Jul 2021 11:46:39 -0700 Subject: [PATCH 08/24] Revert "Revert "updates to client for groups API"" This reverts commit 6019781d8fef5ad37489b96a9393335274dcb4ee. --- argusclient/client.py | 12 +++--- argusclient/model.py | 6 +++ tests/test_data.py | 5 ++- tests/test_group.py | 91 +++++++++++++++++++++++++++++++++++++++++++ tests/test_service.py | 13 ++++++- 5 files changed, 117 insertions(+), 10 deletions(-) create mode 100644 tests/test_group.py diff --git a/argusclient/client.py b/argusclient/client.py index 0051ab6..b5de5c5 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -24,7 +24,7 @@ from functools import wraps from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, JsonEncoder, JsonDecoder, \ - Permission, GroupPermission + Permission, GroupPermission, basestring REQ_METHOD = "req_method" REQ_PATH = "req_path" @@ -431,7 +431,7 @@ def get_user_dashboards(self, ownerName=None, shared=True, limit=None, version=N params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) -class GroupPermissionsServiceCleint(BaseUpdatableModelServiceClient): +class GroupPermissionsServiceClient(BaseUpdatableModelServiceClient): """ Service class that interfaces with the Argus grouppermissions endpoint. @@ -445,7 +445,7 @@ def __init__(self, argus, get_all_req_opts=None): if not get_all_req_opts: get_all_req_opts = {} get_all_req_opts.setdefault(REQ_PATH, "dashboards") - super(DashboardsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/%s", + super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission", get_all_req_opts=get_all_req_opts) def get_permissions_for_group(self, groupId): @@ -455,7 +455,7 @@ def add_permissions_for_group(self, groupId): return convert(self.argus._request("post", "grouppermission", dataObj=groupId)) def delete_permissions_for_group(self, groupId): - return self.argus._request("delete", "grouppermission/%" % groupId) + return self.argus._request("delete", "grouppermission" % groupId) @@ -986,7 +986,7 @@ def __init__(self, user, password, endpoint, timeout=(10, 120), refreshToken=Non self.permissions = PermissionsServiceClient(self) self.users = UsersServiceClient(self) self.namespaces = NamespacesServiceClient(self) - self.grouppermissions = GroupPermission(self) + self.grouppermissions = GroupPermissionsServiceClient(self) self.alerts = AlertsServiceClient(self) self.conn = requests.Session() @@ -1044,7 +1044,7 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE resp = req_method(url, data=data, params=params, headers=headers, - timeout=self.timeout) + timeout=self.timeout, verify=False) res = check_success(resp, decCls) return res diff --git a/argusclient/model.py b/argusclient/model.py index f9f5e7d..c22e4aa 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -270,6 +270,12 @@ def __init__(self, type, **kwargs): super(Permission, self).__init__(type=type, **kwargs) class GroupPermission(BaseEncodable): + """ + Represents a Group permission object in Argus + + :param groupId : the id of the group to be given permissions to + :type groupId: str + """ id_fields = ("groupId",) diff --git a/tests/test_data.py b/tests/test_data.py index a44a8c2..7bf4148 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -36,6 +36,7 @@ notificationName = "test.notification" groupPermissionIdentifier = "group" userPermissionIdentifier = "user" +groupID = "5eb1fc18-c985-47eb-94f9-aebce66e119a" permissionNames = ["VIEW", "EDIT", "DELETE"] permissionGroupId = '24231-52321-43523-64353-23111' username = "testuser" @@ -374,7 +375,7 @@ 'id': triggerID_1, 'threshold': 1.0, 'type': 'GREATER_THAN', - 'inertia': 0L, + 'inertia': 0, 'name': 'CompAlertTest/trigger1' } @@ -385,7 +386,7 @@ 'subscriptions': ['jdoe@example.com'], 'notifierName': 'com.salesforce.dva.argus.service.alert.notifier.EmailNotifier', 'metricsToAnnotate': [], - 'cooldownPeriod': 0L, + 'cooldownPeriod': 0, 'sractionable': False, 'customText': 'None' } \ No newline at end of file diff --git a/tests/test_group.py b/tests/test_group.py new file mode 100644 index 0000000..6309b2d --- /dev/null +++ b/tests/test_group.py @@ -0,0 +1,91 @@ +# +# Copyright (c) 2016, salesforce.com, inc. +# All rights reserved. +# Licensed under the BSD 3-Clause license. +# For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause +# +# Use the package in this repo (argusclient directory) +import json +import pprint +from argusclient import ArgusServiceClient, Notification, Trigger, Dashboard +import os +import unittest +from argusclient import * +from argusclient.client import AlertNotificationsServiceClient, GroupPermissionsServiceClient, AlertsServiceClient, PermissionsServiceClient, \ + DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY +from argusclient.model import Permission +""" +LOGGING IN!~ +""" +username = "s.basu" +password = "SanFrancisco2021!" +argus = ArgusServiceClient(username, + password, + endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") + # endpoint = "https://argus-ws.data.sfdc.net/argusws/") +print ('logging in...') +argus.login() +print ('logged in!') +""" +Set endpoint and params +""" +# argus.alerts = AlertsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False, +# alertNameContains='TestAlert', +# limit=1), +# REQ_PATH: "allinfo"}) +permission_group_D = { + "id": 10, + "createdById": 6906380, + "createdDate": 1616098911000, + "modifiedById": 6906380, + "modifiedDate": 1616098911000, + "type": "group", + "groupId": "c8be7819-bf5e-40aa-8535-88694d34280f", + "username": '', + "permissionIds": [], + "entityId": 23590046 +} +argus.permissions = PermissionsServiceClient(argus) +group_perm = Permission.from_dict(permission_group_D) +# delattr(group_perm, "id") +# deleted_perm = argus.permissions.delete(23590046, group_perm) +# +# print "updating perm" +# updated_perm = argus.permissions.add(23590046, group_perm) +# print "updated permission is "+ str(updated_perm) +print ("making call to get perms for entities") +all_perms = argus.permissions.get_permissions_for_entities([26947204]) +print (all_perms) +print (type(all_perms)) +for id, val in all_perms.items(): + print (id) + print (type(val)) + for perm in val: + perm_type = perm.type + if perm_type == 'group': + print (perm.groupId) + else: + print (perm.username) +# argus.permissions = PermissionsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False), +# REQ_PATH: "entityIds", +# REQ_METHOD: "post", +# REQ_BODY: [14796957, 14796958]}) +# argus.dashboards = DashboardsServiceClient(argus, get_all_req_opts=dict(REQ_PARAMS=dict(username="j.ma", shared=False, limit=3))) # note - limit does not work +""" +Making the call +""" +if __name__ == '__main__': + + # print 'calling items()' + # res = argus.alerts.items() + # res = argus.permissions.items() + # res = argus.dashboards.items() + res = argus.grouppermissions.get() + # res = argus.permissions.get(16348603) + # Get notif + # alert = res[0][1] + # print 'notifs:', alert.notifications.items() + # notifs = alert.notifications.items() + # notif = notifs[0][1] + # print '\nresult: ', res + print ('size of result: ', len(res)) \ No newline at end of file diff --git a/tests/test_service.py b/tests/test_service.py index fd6c0da..9093f79 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -9,11 +9,11 @@ import unittest from argusclient import * -from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, PermissionsServiceClient, \ +from argusclient.client import JsonEncoder, JsonDecoder, check_success, AlertsServiceClient, GroupPermissionsServiceClient, PermissionsServiceClient, \ DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY from argusclient.model import Permission -from test_data import * +from tests.test_data import * try: import mock # Python 2 @@ -198,6 +198,9 @@ def testInvalidRefreshTokenWithDirectAccessToken(self): self.assertEquals((os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"), os.path.join(endpoint, "namespace"),), called_endpoints(mockConn.get)) self.assertEquals(3, mockConn.get.call_count) + + + def testInvalidPasswordWithDirectRefreshToken(self): """Test inability to refresh refresh token as there is no password""" self.argus.refreshToken = "refresh" @@ -390,6 +393,12 @@ def testGetItems(self, mockGet): self.assertIn((os.path.join(endpoint, "dashboards"),), tuple(mockGet.call_args)) self.assertEquals(len(mockGet.call_args_list), 1) +class TestGroupPermissions(TestServiceBase): + @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) + def testGroupPermissionsWrongID(self, mockPost): + res = self.argus.grouppermissions.get(permissionGroupId) + self.assertIsNone(res) + self.assertIn((os.path.join(endpoint, "grouppermission/groupIds"),), tuple(mockPost.call_args)) class TestPermission(TestServiceBase): @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) From 9041b5c57b80a7418125a7906d26e3bffb146424 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Tue, 13 Jul 2021 11:49:14 -0700 Subject: [PATCH 09/24] update --- tests/test_group.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_group.py b/tests/test_group.py index 6309b2d..0bc76db 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -18,7 +18,7 @@ LOGGING IN!~ """ username = "s.basu" -password = "SanFrancisco2021!" +password = " " argus = ArgusServiceClient(username, password, endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") From ab94bcc3cfdd484d9058eb1d0e2c138ccbbe0621 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Wed, 14 Jul 2021 13:59:59 -0700 Subject: [PATCH 10/24] updated --- argusclient/client.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index b5de5c5..a41bda5 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -449,13 +449,13 @@ def __init__(self, argus, get_all_req_opts=None): get_all_req_opts=get_all_req_opts) def get_permissions_for_group(self, groupId): - return convert(self.argus._request("get", "grouppermission", dataObj=groupId)) + return convert(self.argus._request("get", "grouppermission", params=dict(groupId= groupId))) def add_permissions_for_group(self, groupId): - return convert(self.argus._request("post", "grouppermission", dataObj=groupId)) + return convert(self.argus._request("post", "grouppermission", params=groupId)) def delete_permissions_for_group(self, groupId): - return self.argus._request("delete", "grouppermission" % groupId) + return self.argus._request("delete", "grouppermission" , params=groupId) From 63e83f495336a3ebaa84412449fcdeff8ea6c140 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Wed, 14 Jul 2021 14:00:38 -0700 Subject: [PATCH 11/24] updated --- tests/test_data.py | 2 +- tests/test_service.py | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/tests/test_data.py b/tests/test_data.py index 7bf4148..0152664 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -126,7 +126,7 @@ groupPermission_D = { "type": groupPermissionIdentifier, "permissionNames": permissionNames, - "groupId": permissionGroupId + "groupId": groupID } userPermission_D = { diff --git a/tests/test_service.py b/tests/test_service.py index 9093f79..609b219 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -394,11 +394,21 @@ def testGetItems(self, mockGet): self.assertEquals(len(mockGet.call_args_list), 1) class TestGroupPermissions(TestServiceBase): - @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) + @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupPermission_D), 200)) def testGroupPermissionsWrongID(self, mockPost): - res = self.argus.grouppermissions.get(permissionGroupId) + res = self.argus.grouppermissions.get_permissions_for_group(permissionGroupId) + print(res) self.assertIsNone(res) - self.assertIn((os.path.join(endpoint, "grouppermission/groupIds"),), tuple(mockPost.call_args)) + self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) + + @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}))) + + def testGetPermissions(self, mockPost): + resp = self.argus.grouppermissions.get_permissions_for_group(testId1) + for id, perms in resp.items(): + for p in perms: + self.assertTrue(isinstance(p, Permission)) + self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) class TestPermission(TestServiceBase): @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) From 05a66f134826359fe05b8cf3916b124af1aac977 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Wed, 28 Jul 2021 17:19:14 +0800 Subject: [PATCH 12/24] updated unit tests --- .gitignore | 1 + README.rst | 9 +++++++++ argusclient/__init__.py | 4 ++-- argusclient/client.py | 38 ++++++++++++++++++++----------------- tests/test_data.py | 4 ++-- tests/test_group.py | 42 ++++++++++++++++++++++------------------- tests/test_modelobjs.py | 2 +- tests/test_service.py | 12 ++++++------ 8 files changed, 65 insertions(+), 47 deletions(-) diff --git a/.gitignore b/.gitignore index 8b2f5ef..734eeab 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ dist docs/_build docs/README.rst .idea/ +venv/ \ No newline at end of file diff --git a/README.rst b/README.rst index 3725223..81a3158 100644 --- a/README.rst +++ b/README.rst @@ -162,6 +162,15 @@ Look for an existing alert and delete it so that we can recreate it logging.info("Deleting existing alert with name: %s id: %s", alert_name, alertobj.argus_id) argus.alerts.delete(alertobj.argus_id) +Update and create groups and give permissions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:: + + logging.info("Looking up exisiting group with groupID %s", groupID) + groupObj = + + Finally, create alert with a trigger and a notification ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/argusclient/__init__.py b/argusclient/__init__.py index 2cabd66..4ff223d 100644 --- a/argusclient/__init__.py +++ b/argusclient/__init__.py @@ -6,5 +6,5 @@ # For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause # -from .client import ArgusServiceClient, ArgusException, ArgusAuthException, ArgusObjectNotFoundException, MetricQuery, AnnotationQuery -from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, User, AddListResult +from .client import ArgusServiceClient, GroupPermissionsServiceClient, ArgusException, ArgusAuthException, ArgusObjectNotFoundException, MetricQuery, AnnotationQuery +from .model import Namespace, Metric, Annotation, GroupPermission, Dashboard, Alert, Trigger, Notification, User, AddListResult diff --git a/argusclient/client.py b/argusclient/client.py index a41bda5..bc9dbfa 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -14,6 +14,7 @@ # For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause # from collections import Mapping +from lib2to3.pytree import convert import requests @@ -32,6 +33,22 @@ REQ_BODY = "req_body" + +def convert(input): + if isinstance(input, Mapping): + return {convert(key): convert(value) for key, value in input.items()} + elif isinstance(input, list): + return [convert(element) for element in input] + elif isinstance(input, basestring): + ret = str(input) + if ret.isdigit(): + ret = int(ret) + return ret + else: + return input + + + class ArgusException(Exception): """ An exception type that is thrown for Argus service errors. @@ -445,17 +462,17 @@ def __init__(self, argus, get_all_req_opts=None): if not get_all_req_opts: get_all_req_opts = {} get_all_req_opts.setdefault(REQ_PATH, "dashboards") - super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission", + super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/", get_all_req_opts=get_all_req_opts) def get_permissions_for_group(self, groupId): - return convert(self.argus._request("get", "grouppermission", params=dict(groupId= groupId))) + return convert(self.argus._request("get", "grouppermission", params=list(groupId))) def add_permissions_for_group(self, groupId): - return convert(self.argus._request("post", "grouppermission", params=groupId)) + return convert(self.argus._request("post", "grouppermission", params=dict(groupId = groupId))) def delete_permissions_for_group(self, groupId): - return self.argus._request("delete", "grouppermission" , params=groupId) + return self.argus._request("delete", "grouppermission" , params=dict(groupId =groupId)) @@ -535,19 +552,6 @@ def delete(self, entity_id, permission): -def convert(input): - if isinstance(input, Mapping): - return {convert(key): convert(value) for key, value in input.iteritems()} - elif isinstance(input, list): - return [convert(element) for element in input] - elif isinstance(input, basestring): - ret = str(input) - if ret.isdigit(): - ret = int(ret) - return ret - else: - return input - class AlertsServiceClient(BaseUpdatableModelServiceClient): """ diff --git a/tests/test_data.py b/tests/test_data.py index 0152664..c750a53 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -125,8 +125,8 @@ groupPermission_D = { "type": groupPermissionIdentifier, - "permissionNames": permissionNames, - "groupId": groupID + "groupId": groupID, + "permissionIds": [0,1,2] } userPermission_D = { diff --git a/tests/test_group.py b/tests/test_group.py index 0bc76db..557815e 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -18,7 +18,7 @@ LOGGING IN!~ """ username = "s.basu" -password = " " +password = "" argus = ArgusServiceClient(username, password, endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") @@ -45,27 +45,30 @@ "permissionIds": [], "entityId": 23590046 } -argus.permissions = PermissionsServiceClient(argus) -group_perm = Permission.from_dict(permission_group_D) +groupID = "c8be7819-bf5e-40aa-8535-88694d34280f" +argus.grouppermissions = GroupPermissionsServiceClient(argus) +groupPerm = argus.grouppermissions.get_permissions_for_group(groupID) +#argus.permissions = PermissionsServiceClient(argus) +#group_perm = Permission.from_dict(permission_group_D) # delattr(group_perm, "id") # deleted_perm = argus.permissions.delete(23590046, group_perm) # # print "updating perm" # updated_perm = argus.permissions.add(23590046, group_perm) # print "updated permission is "+ str(updated_perm) -print ("making call to get perms for entities") -all_perms = argus.permissions.get_permissions_for_entities([26947204]) -print (all_perms) -print (type(all_perms)) -for id, val in all_perms.items(): - print (id) - print (type(val)) - for perm in val: - perm_type = perm.type - if perm_type == 'group': - print (perm.groupId) - else: - print (perm.username) +#print ("making call to get perms for entities") +#all_perms = argus.permissions.get_permissions_for_entities([26947204]) +#print (all_perms) +#print (type(group_perm)) +#for id, val group_perm.items(): + #print (id) + # print (type(val)) + # for perm in val: + # perm_type = perm.type + # if perm_type == 'group': + ## print (perm.groupId) + # else: + # print (perm.username) # argus.permissions = PermissionsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False), # REQ_PATH: "entityIds", # REQ_METHOD: "post", @@ -80,12 +83,13 @@ # res = argus.alerts.items() # res = argus.permissions.items() # res = argus.dashboards.items() - res = argus.grouppermissions.get() - # res = argus.permissions.get(16348603) + print ("calling groupPerms") + res = argus.grouppermissions.items() + print ('size of result: ', len(res)) + #res = argus.permissions.get(16348603) # Get notif # alert = res[0][1] # print 'notifs:', alert.notifications.items() # notifs = alert.notifications.items() # notif = notifs[0][1] # print '\nresult: ', res - print ('size of result: ', len(res)) \ No newline at end of file diff --git a/tests/test_modelobjs.py b/tests/test_modelobjs.py index 00126a9..a78e495 100644 --- a/tests/test_modelobjs.py +++ b/tests/test_modelobjs.py @@ -212,7 +212,7 @@ def testEncUserPermission(self): self._testFor(userPermission_D, Permission) def testEncGroupPermission(self): - self._testFor(groupPermission_D, Permission) + self._testFor(groupPermission_D, GroupPermission) def testEncNamespace(self): self._testFor(namespace_D, Namespace) diff --git a/tests/test_service.py b/tests/test_service.py index 609b219..7d323a5 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -394,17 +394,16 @@ def testGetItems(self, mockGet): self.assertEquals(len(mockGet.call_args_list), 1) class TestGroupPermissions(TestServiceBase): - @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupPermission_D), 200)) - def testGroupPermissionsWrongID(self, mockPost): + @mock.patch('requests.Session.get', return_value=MockResponse(json.dumps(groupPermission_D), 200)) + def testGroupPermissionsID(self, mockPost): res = self.argus.grouppermissions.get_permissions_for_group(permissionGroupId) - print(res) - self.assertIsNone(res) + self.assertEquals(res.get("permissionIds"), [0, 1, 2]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) - @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}))) + @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}),200)) def testGetPermissions(self, mockPost): - resp = self.argus.grouppermissions.get_permissions_for_group(testId1) + resp = self.argus.grouppermissions.get_permissions_for_group(testId) for id, perms in resp.items(): for p in perms: self.assertTrue(isinstance(p, Permission)) @@ -421,6 +420,7 @@ def testGetPermissionsBadId(self, mockPost): testId2: [userPermission_D], testId3: []}), 200)) def testGetItems(self, mockPost): + # Check self.assertEquals(len(mockPost.call_args_list), 0) From a55dea19cba474efa955c1ee8cf9b85875f04234 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Wed, 28 Jul 2021 17:35:11 +0800 Subject: [PATCH 13/24] updated formatting --- argusclient/client.py | 26 +++++++++----------------- 1 file changed, 9 insertions(+), 17 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index bc9dbfa..5e9d2f0 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -21,7 +21,7 @@ try: import http.client as httplib # Python 3 except ImportError: - import httplib # Python 2 + import httplib # Python 2 from functools import wraps from .model import Namespace, Metric, Annotation, Dashboard, Alert, Trigger, Notification, JsonEncoder, JsonDecoder, \ @@ -101,8 +101,7 @@ class MetricQuery(BaseQuery): -1d:-0d:test.scope:test.metric{test.tag=test.value}:sum:test.namespace """ - def __init__(self, scope, metric, aggregator, tags=None, namespace=None, downsampler=None, stTimeSpec=None, - enTimeSpec=None): + def __init__(self, scope, metric, aggregator, tags=None, namespace=None, downsampler=None, stTimeSpec=None,enTimeSpec=None): # NOTE: Namespace no longer goes into the metric expression, so we pass it down as a tail parameter. super(MetricQuery, self).__init__(str(Metric(scope, metric, tags=tags)), aggregator, downsampler, namespace, stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) @@ -119,8 +118,7 @@ class AnnotationQuery(BaseQuery): """ def __init__(self, scope, metric, source, tags=None, stTimeSpec=None, enTimeSpec=None): - super(AnnotationQuery, self).__init__(str(Annotation(source, scope, metric, None, None, None, tags=tags)), - stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) + super(AnnotationQuery, self).__init__(str(Annotation(source, scope, metric, None, None, None, tags=tags)),stTimeSpec=stTimeSpec, enTimeSpec=enTimeSpec) class BaseCollectionServiceClient(object): @@ -146,8 +144,7 @@ def add(self, data): :return: :class:`argusclient.model.AddListResult` object with a summary of the operation. """ if not data: raise ValueError("need a value for data parameter") - if not isinstance(data, list) or not isinstance(data[0], self.obj_type): raise TypeError( - "data should be a list of %s objects" % self.obj_type) + if not isinstance(data, list) or not isinstance(data[0], self.obj_type): raise TypeError("data should be a list of %s objects" % self.obj_type) return self.argus._request("post", self.coll_path, dataObj=data) @@ -170,8 +167,7 @@ class AnnotationCollectionServiceClient(BaseCollectionServiceClient): """ def __init__(self, argus): - super(AnnotationCollectionServiceClient, self).__init__(AnnotationQuery, Annotation, argus, "annotations", - "collection/annotations") + super(AnnotationCollectionServiceClient, self).__init__(AnnotationQuery, Annotation, argus, "annotations","collection/annotations") class BaseModelServiceClient(object): @@ -321,8 +317,7 @@ def update(self, id, namespace): if not id: raise ValueError("Need to specify an id to update namespace") id = int(id) if not namespace.argus_id: raise ValueError("Namespace needs an id to update") - if id != namespace.argus_id: raise ValueError( - "Namespace id: %s doesn't match the id: %s that you are updating" % (namespace.id, id)) + if id != namespace.argus_id: raise ValueError("Namespace id: %s doesn't match the id: %s that you are updating" % (namespace.id, id)) self._coll[id] = self.argus._request("put", "namespace/%s" % id, dataObj=namespace) return self._coll[id] @@ -376,8 +371,7 @@ def update(self, id, obj): if not isinstance(obj, self.objType): raise TypeError("Need an object of type: %s" % self.objType) if not obj.argus_id: raise ValueError("Object needs an id to update") # Ensure that user doesn't accidentally copy another item. - if id != obj.argus_id: raise ValueError( - "Object id: %s doesn't match the id: %s that you are updating" % (obj.id, id)) + if id != obj.argus_id: raise ValueError("Object id: %s doesn't match the id: %s that you are updating" % (obj.id, id)) self._coll[id] = self.argus._request("put", self.id_path % id, dataObj=obj) return self._coll[id] @@ -429,8 +423,7 @@ def get_user_dashboard(self, ownerName, dashboardName, shared=True): """ assert dashboardName, "Expected a dashboard name" assert ownerName, "Expected a owner name" - dashboards = self.argus._request("get", "dashboards", - params=dict(dashboardName=dashboardName, owner=ownerName, shared=shared)) + dashboards = self.argus._request("get", "dashboards", params=dict(dashboardName=dashboardName, owner=ownerName, shared=shared)) if not dashboards: return None else: @@ -444,8 +437,7 @@ def get_user_dashboards(self, ownerName=None, shared=True, limit=None, version=N :return: a list of :class:`argusclient.model.Dashboard` objects with all fields populated. """ - return self.argus._request("get", "dashboards", - params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) + return self.argus._request("get", "dashboards", params=dict(owner=ownerName, shared=shared, limit=limit, version=version)) class GroupPermissionsServiceClient(BaseUpdatableModelServiceClient): From bc5ed82ed40c09bdc4173704f95ac5d1229cfbbf Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Wed, 11 Aug 2021 14:16:55 +0800 Subject: [PATCH 14/24] updated --- .DS_Store | Bin 0 -> 6148 bytes argusclient/client.py | 4 ++-- tests/test_data.py | 2 ++ tests/test_service.py | 21 ++++++++++----------- 4 files changed, 14 insertions(+), 13 deletions(-) create mode 100644 .DS_Store diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..42cc2d9010190992238ceaf1c04d0b92991a353c GIT binary patch literal 6148 zcmeHK&2G~`5S~o~*tLX=#GyzWR^q@Vhg6~TYK4{)5~!}|ftIkYt;UkIuKd#+qDU4G zzyrXQpZB0V1TVs!ncWSdN_(v+nvrI|@$Ag3{n^^_0)QB|=_Wu303Iq~&&S~sp?T63 z={XOfFg0p8h5~ZPK(9oz<6mTe-dz9+DmZ}_{(gT=GOJIMqD(O2S8`h9bu%3P6uq_n zt=o4ze?9PnyMcccPs>@{sHUyQs+xok<2=n0RUPDMGu_YhZjqg3`epS(HCgqBg7?d^ zzyNEj$mUcHcjBCYvi88CHz3+ z3Tn>cN*AR*!H8w{GK-NJU Date: Wed, 11 Aug 2021 23:18:57 +0800 Subject: [PATCH 15/24] updated tests and added edge cases --- argusclient/client.py | 22 ++++++++++++++++++---- argusclient/model.py | 8 ++++++-- tests/test_data.py | 17 +++++++++++++++-- tests/test_service.py | 9 ++++++++- 4 files changed, 47 insertions(+), 9 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 4313f94..083a8a9 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -460,11 +460,25 @@ def __init__(self, argus, get_all_req_opts=None): def get_permissions_for_group(self, groupId): return convert(self.argus._request("get", "grouppermission", params=list(groupId))) - def add_permissions_for_group(self, groupId): - return convert(self.argus._request("post", "grouppermission", params=list(groupId = groupId))) + def add_permissions_for_group(self, grouppermission): + if not isinstance(grouppermission, GroupPermission): + raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) + updated_permission = self.argus._request("post", "grouppermission" , dataObj=grouppermission) + return updated_permission + + def delete_permissions_for_group(self, grouppermission): + if not isinstance(grouppermission, GroupPermission): + raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - def delete_permissions_for_group(self, groupId): - return self.argus._request("delete", "grouppermission" , params=dict(groupId =groupId)) + if grouppermission.get("permissionIds") == []: + raise ValueError("Permission is not already assigned and hence cant be deleted") + permsPresent = grouppermission.get("permissionIds") + if permsPresent in self.get_permissions_for_group(grouppermission.get("groupId")): + + deleted_permission = self.argus._request("delete", "grouppermission", dataObj=grouppermission) + return deleted_permission + else: + raise ValueError("Permission %s wasnt assigned so not deleted" %str(permsPresent)) diff --git a/argusclient/model.py b/argusclient/model.py index c22e4aa..c710e19 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -275,12 +275,16 @@ class GroupPermission(BaseEncodable): :param groupId : the id of the group to be given permissions to :type groupId: str + :type grouppermissionIds: List of permissions that this group + has on the associated entity (id is put in the entityId field). + Permissions in this list are in the form of integers: like 0, 1, and 2. + 0, 1, and 2 correspond to "VIEW", "EDIT", and "DELETE" respectively. """ id_fields = ("groupId",) - def __init__(self, type, groupId, **kwargs): - super(GroupPermission, self).__init__(type=type, groupId=groupId, **kwargs) + def __init__(self, groupId, **kwargs): + super(GroupPermission, self).__init__(groupId=groupId, **kwargs) class Namespace(BaseEncodable): """ diff --git a/tests/test_data.py b/tests/test_data.py index 0e615b2..acb773b 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -47,6 +47,9 @@ group_id = "c8be7819-bf5e-40aa-8535-88694d34280f" entity_id = 23590046 +permissionGroup2ID= '24231-52321-43523-64353-23121' +permissionGroupIdBad = '2423480-3843hlfw-jf' + compAlertID = 6000 childAlertID_1 = 6003 @@ -126,10 +129,20 @@ } groupPermission_D = { - "type": groupPermissionIdentifier, - "groupId": groupID, + "groupId": permissionGroupId, "permissionIds": [0,1,2] } +groupPermission_E = { + "groupId": permissionGroup2ID, + "permissionIds": [1] +} + +groupBadPermission_D = { + "groupId": groupID, + "permissionIds": [0,3] +} + + userPermission_D = { "type": userPermissionIdentifier, diff --git a/tests/test_service.py b/tests/test_service.py index 9d00aa4..d551526 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -399,8 +399,15 @@ def testGroupPermissionsID(self, mockPost): self.assertEquals(res.get("permissionIds"), [0, 1, 2]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) + @mock.patch('requests.Session.get', return_value=MockResponse(json.dumps(groupPermission_E), 200)) + def testGroupPermissionsIDAdd(self, mockPost): + gpermission = GroupPermission(groupPermission_E) + res = self.argus.grouppermissions.add_permissions_for_group(permissionGroupId,gpermission) + self.assertEquals(res.get("permissionIds"), [0, 1]) + self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) + #@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}),200)) - @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupPermission_D), 200)) + @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupBadPermission_D), 200)) def testGetGroupPermissionsBadId(self, mockPost): res = self.argus.grouppermissions.get_permissions_for_group(permissionGroupIdBad) self.assertIsNone(res) From b4a744b08fb721bb86746605bb900de83ad36e5b Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 00:31:40 +0800 Subject: [PATCH 16/24] updated test datat --- argusclient/client.py | 43 +++++++++++++++++++++++++++++-------------- argusclient/model.py | 6 +++--- tests/test_data.py | 9 ++++++++- tests/test_service.py | 16 +++++++++------- 4 files changed, 49 insertions(+), 25 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 083a8a9..33a2fe6 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -453,9 +453,25 @@ def __init__(self, argus, get_all_req_opts=None): """ if not get_all_req_opts: get_all_req_opts = {} - get_all_req_opts.setdefault(REQ_PATH, "dashboards") + get_all_req_opts.setdefault(REQ_PATH, "grouppermission") super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/", - get_all_req_opts=get_all_req_opts) + get_all_req_opts=get_all_req_opts) + + def _init_all(self, coll=None): + if not self.get_all_req_opts.get(REQ_PATH): + raise TypeError("Unsupported operation on: %s" % type(self)) + if not self._retrieved_all: + resp = convert(self.argus._request(self.get_all_req_opts.get(REQ_METHOD, "get"), + self.get_all_req_opts.get(REQ_PATH, None), + params=self.get_all_req_opts.get(REQ_PARAMS, None), + dataObj=self.get_all_req_opts.get(REQ_BODY, None))) + for group_id, perms in resp.items(): + self._coll[group_id] = perms + self._retrieved_all = True + + def get_groupId(self, grouppermission): + self.groupId = grouppermission[0] + return self.groupId def get_permissions_for_group(self, groupId): return convert(self.argus._request("get", "grouppermission", params=list(groupId))) @@ -463,22 +479,21 @@ def get_permissions_for_group(self, groupId): def add_permissions_for_group(self, grouppermission): if not isinstance(grouppermission, GroupPermission): raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - updated_permission = self.argus._request("post", "grouppermission" , dataObj=grouppermission) - return updated_permission + updatedGroup = convert( + self.argus._request("post", "grouppermission", dataObj=grouppermission)) # returns None here + return updatedGroup def delete_permissions_for_group(self, grouppermission): if not isinstance(grouppermission, GroupPermission): raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - - if grouppermission.get("permissionIds") == []: + permsPresent = grouppermission.permissionId + if permsPresent == []: raise ValueError("Permission is not already assigned and hence cant be deleted") - permsPresent = grouppermission.get("permissionIds") - if permsPresent in self.get_permissions_for_group(grouppermission.get("groupId")): - - deleted_permission = self.argus._request("delete", "grouppermission", dataObj=grouppermission) - return deleted_permission - else: - raise ValueError("Permission %s wasnt assigned so not deleted" %str(permsPresent)) + #presentPerms = self.get_permissions_for_group(grouppermission.groupId) + deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) + return deleted_permission + # else: + # raise ValueError("Permission %s wasnt assigned so not deleted" % permsPresent) @@ -1054,7 +1069,7 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE resp = req_method(url, data=data, params=params, headers=headers, - timeout=self.timeout, verify=False) + timeout=self.timeout) res = check_success(resp, decCls) return res diff --git a/argusclient/model.py b/argusclient/model.py index c710e19..2085d68 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -281,10 +281,10 @@ class GroupPermission(BaseEncodable): 0, 1, and 2 correspond to "VIEW", "EDIT", and "DELETE" respectively. """ - id_fields = ("groupId",) + id_fields = ("groupId","permissionIds") - def __init__(self, groupId, **kwargs): - super(GroupPermission, self).__init__(groupId=groupId, **kwargs) + def __init__(self, groupId,permissionIds, **kwargs): + super(GroupPermission, self).__init__( permissionId = permissionIds, groupId=groupId,**kwargs) class Namespace(BaseEncodable): """ diff --git a/tests/test_data.py b/tests/test_data.py index acb773b..92575cd 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -48,6 +48,7 @@ entity_id = 23590046 permissionGroup2ID= '24231-52321-43523-64353-23121' +permissionGroup3ID = '24231-52321-43523-64353-24121' permissionGroupIdBad = '2423480-3843hlfw-jf' @@ -134,9 +135,15 @@ } groupPermission_E = { "groupId": permissionGroup2ID, - "permissionIds": [1] + "permissionIds": [0] } +groupPermission_E = { + "groupId": permissionGroup3ID, + "permissionIds": [0,1,2] +} + + groupBadPermission_D = { "groupId": groupID, "permissionIds": [0,3] diff --git a/tests/test_service.py b/tests/test_service.py index d551526..28da803 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -399,18 +399,20 @@ def testGroupPermissionsID(self, mockPost): self.assertEquals(res.get("permissionIds"), [0, 1, 2]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) - @mock.patch('requests.Session.get', return_value=MockResponse(json.dumps(groupPermission_E), 200)) + @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) def testGroupPermissionsIDAdd(self, mockPost): - gpermission = GroupPermission(groupPermission_E) - res = self.argus.grouppermissions.add_permissions_for_group(permissionGroupId,gpermission) + ggroupId = permissionGroup2ID + gperms = GroupPermission(ggroupId, [1]) + res = self.argus.grouppermissions.add_permissions_for_group(gperms) self.assertEquals(res.get("permissionIds"), [0, 1]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) #@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}),200)) - @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupBadPermission_D), 200)) - def testGetGroupPermissionsBadId(self, mockPost): - res = self.argus.grouppermissions.get_permissions_for_group(permissionGroupIdBad) - self.assertIsNone(res) + @mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(groupPermission_E), 200)) + def testDeletePermission(self, mockPost): + gpermission = GroupPermission(permissionGroup3ID,[2]) + res = self.argus.grouppermissions.delete_permissions_for_group(gpermission) + self.assertEquals(res.get("permissionIds"), [0,1]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) From 70413aabd427a9a0e01a6f905fe4dde1a07f735b Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 01:09:14 +0800 Subject: [PATCH 17/24] deleting group permission works --- argusclient/client.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 33a2fe6..03ab75a 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -469,9 +469,6 @@ def _init_all(self, coll=None): self._coll[group_id] = perms self._retrieved_all = True - def get_groupId(self, grouppermission): - self.groupId = grouppermission[0] - return self.groupId def get_permissions_for_group(self, groupId): return convert(self.argus._request("get", "grouppermission", params=list(groupId))) @@ -489,11 +486,15 @@ def delete_permissions_for_group(self, grouppermission): permsPresent = grouppermission.permissionId if permsPresent == []: raise ValueError("Permission is not already assigned and hence cant be deleted") - #presentPerms = self.get_permissions_for_group(grouppermission.groupId) deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) - return deleted_permission - # else: - # raise ValueError("Permission %s wasnt assigned so not deleted" % permsPresent) + check = any(item in permsPresent for item in deleted_permission["permissionIds"] ) + if check == True: + for i in permsPresent: + if i in deleted_permission["permissionIds"]: + deleted_permission["permissionIds"].remove(i) + return deleted_permission + else: + raise ValueError("Permission wasnt already assigned so not deleted") From f614e365fc644dbc9ddda4ec7765a0b49228a8c0 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 01:59:28 +0800 Subject: [PATCH 18/24] added integration test --- argusclient/client.py | 5 ++--- tests/test_group.py | 37 ++++++++++++++++++++----------------- tests/test_service.py | 10 +++++----- 3 files changed, 27 insertions(+), 25 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 03ab75a..64c967a 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -476,8 +476,7 @@ def get_permissions_for_group(self, groupId): def add_permissions_for_group(self, grouppermission): if not isinstance(grouppermission, GroupPermission): raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - updatedGroup = convert( - self.argus._request("post", "grouppermission", dataObj=grouppermission)) # returns None here + updatedGroup = convert(self.argus._request("post", "grouppermission", dataObj=grouppermission)) # returns None here return updatedGroup def delete_permissions_for_group(self, grouppermission): @@ -486,7 +485,7 @@ def delete_permissions_for_group(self, grouppermission): permsPresent = grouppermission.permissionId if permsPresent == []: raise ValueError("Permission is not already assigned and hence cant be deleted") - deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) + deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission))#this request doesnt delete anything, i am manually deleting later check = any(item in permsPresent for item in deleted_permission["permissionIds"] ) if check == True: for i in permsPresent: diff --git a/tests/test_group.py b/tests/test_group.py index 557815e..77f5311 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -5,22 +5,15 @@ # For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause # # Use the package in this repo (argusclient directory) -import json -import pprint -from argusclient import ArgusServiceClient, Notification, Trigger, Dashboard -import os -import unittest from argusclient import * -from argusclient.client import AlertNotificationsServiceClient, GroupPermissionsServiceClient, AlertsServiceClient, PermissionsServiceClient, \ - DashboardsServiceClient, REQ_PATH, REQ_PARAMS, REQ_METHOD, REQ_BODY -from argusclient.model import Permission + """ LOGGING IN!~ """ username = "s.basu" password = "" -argus = ArgusServiceClient(username, - password, +argus = ArgusServiceClient(user="s.basu", + password="", endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") # endpoint = "https://argus-ws.data.sfdc.net/argusws/") print ('logging in...') @@ -45,9 +38,18 @@ "permissionIds": [], "entityId": 23590046 } -groupID = "c8be7819-bf5e-40aa-8535-88694d34280f" -argus.grouppermissions = GroupPermissionsServiceClient(argus) -groupPerm = argus.grouppermissions.get_permissions_for_group(groupID) + +GroupPermission_D = { + "groupId": "24231-52321-43523-64353-23111", + "permissionIds": [0,1] +} +groupID1 = "24231-52321-43523-64353-23111" +grouppermission = GroupPermission.from_dict(GroupPermission_D) +groupPerm = argus.grouppermissions.get_permissions_for_group(groupID1) +print("groupPerms are "+ str(groupPerm)) +groupPerm1 = argus.grouppermissions.add_permissions_for_group(grouppermission) + + #argus.permissions = PermissionsServiceClient(argus) #group_perm = Permission.from_dict(permission_group_D) # delattr(group_perm, "id") @@ -70,9 +72,9 @@ # else: # print (perm.username) # argus.permissions = PermissionsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False), -# REQ_PATH: "entityIds", -# REQ_METHOD: "post", -# REQ_BODY: [14796957, 14796958]}) +# # REQ_PATH: "entityIds", +# # REQ_METHOD: "post", +# # REQ_BODY: [14796957, 14796958]}) # argus.dashboards = DashboardsServiceClient(argus, get_all_req_opts=dict(REQ_PARAMS=dict(username="j.ma", shared=False, limit=3))) # note - limit does not work """ Making the call @@ -84,7 +86,8 @@ # res = argus.permissions.items() # res = argus.dashboards.items() print ("calling groupPerms") - res = argus.grouppermissions.items() + res = groupPerm + print(res) print ('size of result: ', len(res)) #res = argus.permissions.get(16348603) # Get notif diff --git a/tests/test_service.py b/tests/test_service.py index 28da803..fb0639c 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -394,10 +394,10 @@ def testGetItems(self, mockGet): class TestGroupPermissions(TestServiceBase): @mock.patch('requests.Session.get', return_value=MockResponse(json.dumps(groupPermission_D), 200)) - def testGroupPermissionsID(self, mockPost): + def testGroupPermissionsID(self, mockGet): res = self.argus.grouppermissions.get_permissions_for_group(permissionGroupId) self.assertEquals(res.get("permissionIds"), [0, 1, 2]) - self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) + self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockGet.call_args)) @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) def testGroupPermissionsIDAdd(self, mockPost): @@ -408,12 +408,12 @@ def testGroupPermissionsIDAdd(self, mockPost): self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) #@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}),200)) - @mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(groupPermission_E), 200)) - def testDeletePermission(self, mockPost): + @mock.patch('requests.Session.delete', return_value=MockResponse("", 200)) + def testDeletePermission(self, mockDelete): gpermission = GroupPermission(permissionGroup3ID,[2]) res = self.argus.grouppermissions.delete_permissions_for_group(gpermission) self.assertEquals(res.get("permissionIds"), [0,1]) - self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) + self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockDelete.call_args)) class TestPermission(TestServiceBase): From 98c0830adf1f1e075b5d3e274f9521257cc5dabd Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 03:00:01 +0800 Subject: [PATCH 19/24] updated integration tests --- argusclient/client.py | 6 +++++- tests/test_group.py | 46 ++++++++++++++++++++++++++----------------- 2 files changed, 33 insertions(+), 19 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 64c967a..62d5582 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -474,9 +474,13 @@ def get_permissions_for_group(self, groupId): return convert(self.argus._request("get", "grouppermission", params=list(groupId))) def add_permissions_for_group(self, grouppermission): + """ + Updates permissions in groups + :return: a list of :class:`argusclient.model.GroupPermission` objects with all fields populated. + """ if not isinstance(grouppermission, GroupPermission): raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - updatedGroup = convert(self.argus._request("post", "grouppermission", dataObj=grouppermission)) # returns None here + updatedGroup = convert(self.argus._request("post", "grouppermission", dataObj=grouppermission)) return updatedGroup def delete_permissions_for_group(self, grouppermission): diff --git a/tests/test_group.py b/tests/test_group.py index 77f5311..1edeef2 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -5,6 +5,7 @@ # For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause # # Use the package in this repo (argusclient directory) + from argusclient import * """ @@ -22,33 +23,42 @@ """ Set endpoint and params """ +argus.grouppermissions = GroupPermissionsServiceClient(argus, get_all_req_opts= dict(groupID="234-567-891-667-001", + permissionsID=[0,1,2])) + + + # argus.alerts = AlertsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False, # alertNameContains='TestAlert', # limit=1), # REQ_PATH: "allinfo"}) -permission_group_D = { - "id": 10, - "createdById": 6906380, - "createdDate": 1616098911000, - "modifiedById": 6906380, - "modifiedDate": 1616098911000, - "type": "group", - "groupId": "c8be7819-bf5e-40aa-8535-88694d34280f", - "username": '', - "permissionIds": [], - "entityId": 23590046 -} +# permission_group_D = { +# "id": 10, +# "createdById": 6906380, +# "createdDate": 1616098911000, +# "modifiedById": 6906380, +# "modifiedDate": 1616098911000, +# "type": "group", +# "groupId": "c8be7819-bf5e-40aa-8535-88694d34280f", +# "username": '', +# "permissionIds": [], +# "entityId": 23590046 +# } GroupPermission_D = { "groupId": "24231-52321-43523-64353-23111", - "permissionIds": [0,1] + "permissionIds": [0,1,2] } groupID1 = "24231-52321-43523-64353-23111" grouppermission = GroupPermission.from_dict(GroupPermission_D) -groupPerm = argus.grouppermissions.get_permissions_for_group(groupID1) -print("groupPerms are "+ str(groupPerm)) +#groupPerm = argus.grouppermissions.get_permissions_for_group(groupID1) +#print("groupPerms are "+ str(groupPerm)) +grouppermission = GroupPermission(GroupPermission_D.get("groupId"),[0,1,2]) groupPerm1 = argus.grouppermissions.add_permissions_for_group(grouppermission) - +print("groupPerms are "+ str(groupPerm1)) +gpermission = GroupPermission(groupID1,[2]) +deletedPerm = argus.grouppermissions.delete_permissions_for_group(gpermission) #this is not working as adding group_permission returns a permission object instead of groupPermission object ? +print("removed groupPerms are "+ str(deletedPerm)) #argus.permissions = PermissionsServiceClient(argus) #group_perm = Permission.from_dict(permission_group_D) @@ -86,8 +96,8 @@ # res = argus.permissions.items() # res = argus.dashboards.items() print ("calling groupPerms") - res = groupPerm - print(res) + res1 = groupPerm1 + print ('size of result: ', len(res)) #res = argus.permissions.get(16348603) # Get notif From 0db8565be3c3f211442148c665e570bd70b5241c Mon Sep 17 00:00:00 2001 From: snehabas <78375053+snehabas@users.noreply.github.com> Date: Thu, 12 Aug 2021 02:17:04 +0800 Subject: [PATCH 20/24] Update README.rst Co-authored-by: j-ma-sf <59028215+j-ma-sf@users.noreply.github.com> --- README.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.rst b/README.rst index 81a3158..0050281 100644 --- a/README.rst +++ b/README.rst @@ -167,7 +167,7 @@ Update and create groups and give permissions :: - logging.info("Looking up exisiting group with groupID %s", groupID) + logging.info("Looking up existing group with groupID %s", groupID) groupObj = From f42c3f72f8a4120aa814a8c0851962def0959115 Mon Sep 17 00:00:00 2001 From: snehabas <78375053+snehabas@users.noreply.github.com> Date: Thu, 12 Aug 2021 02:17:53 +0800 Subject: [PATCH 21/24] Update argusclient/client.py Co-authored-by: j-ma-sf <59028215+j-ma-sf@users.noreply.github.com> --- argusclient/client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/argusclient/client.py b/argusclient/client.py index 62d5582..3732ab3 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -444,7 +444,7 @@ class GroupPermissionsServiceClient(BaseUpdatableModelServiceClient): """ Service class that interfaces with the Argus grouppermissions endpoint. - There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.permissions` attribute. + There is no need to instantiate this directly, as it is available as :attr:`argusclient.client.ArgusServiceClient.grouppermissions` attribute. """ def __init__(self, argus, get_all_req_opts=None): From 591392a7c3a7f3f2dfc9c640a805793b96cce240 Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 09:19:05 +0800 Subject: [PATCH 22/24] updated tests --- argusclient/client.py | 16 +++++----------- argusclient/model.py | 2 +- tests/test_group.py | 6 +++--- tests/test_service.py | 2 +- 4 files changed, 10 insertions(+), 16 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 3732ab3..537c05c 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -486,18 +486,12 @@ def add_permissions_for_group(self, grouppermission): def delete_permissions_for_group(self, grouppermission): if not isinstance(grouppermission, GroupPermission): raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - permsPresent = grouppermission.permissionId - if permsPresent == []: + perms_to_delete = grouppermission.permissionId + if perms_to_delete == []: + raise ValueError("Permission is not already assigned and hence cant be deleted") - deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission))#this request doesnt delete anything, i am manually deleting later - check = any(item in permsPresent for item in deleted_permission["permissionIds"] ) - if check == True: - for i in permsPresent: - if i in deleted_permission["permissionIds"]: - deleted_permission["permissionIds"].remove(i) - return deleted_permission - else: - raise ValueError("Permission wasnt already assigned so not deleted") + deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) + return deleted_permission diff --git a/argusclient/model.py b/argusclient/model.py index 2085d68..e6e2b01 100644 --- a/argusclient/model.py +++ b/argusclient/model.py @@ -510,7 +510,7 @@ def __init__(self, *args, **kwargs): def from_json(self, jsonObj): if not jsonObj or not isinstance(jsonObj, dict): return jsonObj - for cls in (Metric, Dashboard, AddListResult, User, Namespace, Annotation, Alert, Trigger, Notification, Permission): + for cls in (Metric, Dashboard, AddListResult, User, Namespace, Annotation, Alert, Trigger, Notification, Permission, GroupPermission): obj = cls.from_dict(jsonObj) if obj: return obj diff --git a/tests/test_group.py b/tests/test_group.py index 1edeef2..89129ae 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -12,9 +12,9 @@ LOGGING IN!~ """ username = "s.basu" -password = "" +password = "TownsendStreet2SF!" argus = ArgusServiceClient(user="s.basu", - password="", + password=password, endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") # endpoint = "https://argus-ws.data.sfdc.net/argusws/") print ('logging in...') @@ -57,7 +57,7 @@ groupPerm1 = argus.grouppermissions.add_permissions_for_group(grouppermission) print("groupPerms are "+ str(groupPerm1)) gpermission = GroupPermission(groupID1,[2]) -deletedPerm = argus.grouppermissions.delete_permissions_for_group(gpermission) #this is not working as adding group_permission returns a permission object instead of groupPermission object ? +deletedPerm = argus.grouppermissions.delete_permissions_for_group(groupPerm1) #this is not working as adding group_permission returns a permission object instead of groupPermission object ? print("removed groupPerms are "+ str(deletedPerm)) #argus.permissions = PermissionsServiceClient(argus) diff --git a/tests/test_service.py b/tests/test_service.py index fb0639c..d3aaa49 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -408,7 +408,7 @@ def testGroupPermissionsIDAdd(self, mockPost): self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) #@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}),200)) - @mock.patch('requests.Session.delete', return_value=MockResponse("", 200)) + @mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(groupPermission_E), 200)) def testDeletePermission(self, mockDelete): gpermission = GroupPermission(permissionGroup3ID,[2]) res = self.argus.grouppermissions.delete_permissions_for_group(gpermission) From 54d1044d65f8d67061f046e03797aa639cc8f7ec Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 11:22:16 +0800 Subject: [PATCH 23/24] new branc to incorporate sanjana's changes --- argusclient/client.py | 15 ++++++++++----- tests/test_data.py | 5 ++++- tests/test_group.py | 33 ++++++++++++++++++++++----------- 3 files changed, 36 insertions(+), 17 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 537c05c..97e5fb6 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -454,7 +454,8 @@ def __init__(self, argus, get_all_req_opts=None): if not get_all_req_opts: get_all_req_opts = {} get_all_req_opts.setdefault(REQ_PATH, "grouppermission") - super(GroupPermissionsServiceClient, self).__init__(GroupPermission, argus, id_path="grouppermission/", + print("init happening") + super(GroupPermissionsServiceClient, self).__init__(Permission, argus, id_path="grouppermission/", get_all_req_opts=get_all_req_opts) def _init_all(self, coll=None): @@ -484,14 +485,17 @@ def add_permissions_for_group(self, grouppermission): return updatedGroup def delete_permissions_for_group(self, grouppermission): - if not isinstance(grouppermission, GroupPermission): - raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) - perms_to_delete = grouppermission.permissionId + if not isinstance(grouppermission, Permission): + raise TypeError("Need a Permission object, got: %s" % type(grouppermission)) + perms_to_delete = grouppermission.permissionIds if perms_to_delete == []: raise ValueError("Permission is not already assigned and hence cant be deleted") + #add check for if permissions dont exist deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) - return deleted_permission + if deleted_permission: + return True + return False @@ -1068,6 +1072,7 @@ def _request_no_auth(self, method, path, params=None, dataObj=None, encCls=JsonE resp = req_method(url, data=data, params=params, headers=headers, timeout=self.timeout) + print("This is response",resp) res = check_success(resp, decCls) return res diff --git a/tests/test_data.py b/tests/test_data.py index 92575cd..52256de 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -130,15 +130,18 @@ } groupPermission_D = { + "type": "group", "groupId": permissionGroupId, "permissionIds": [0,1,2] } groupPermission_E = { + "type": "group", "groupId": permissionGroup2ID, "permissionIds": [0] } -groupPermission_E = { +groupPermission_F = { + "type": "group", "groupId": permissionGroup3ID, "permissionIds": [0,1,2] } diff --git a/tests/test_group.py b/tests/test_group.py index 89129ae..e26c09f 100644 --- a/tests/test_group.py +++ b/tests/test_group.py @@ -7,12 +7,13 @@ # Use the package in this repo (argusclient directory) from argusclient import * +from argusclient.model import Permission """ LOGGING IN!~ """ username = "s.basu" -password = "TownsendStreet2SF!" +password = "" argus = ArgusServiceClient(user="s.basu", password=password, endpoint="http://shared1-argusws1-1-prd.eng.sfdc.net:8080/argusws/") @@ -23,10 +24,11 @@ """ Set endpoint and params """ -argus.grouppermissions = GroupPermissionsServiceClient(argus, get_all_req_opts= dict(groupID="234-567-891-667-001", +argus.grouppermissions = GroupPermissionsServiceClient(argus, get_all_req_opts= dict(groupID="234-567-891-667-001", type="group", permissionsID=[0,1,2])) - +print(argus.grouppermissions) +print(type(argus.grouppermissions)) # argus.alerts = AlertsServiceClient(argus, get_all_req_opts={REQ_PARAMS: dict(shared=False, # alertNameContains='TestAlert', @@ -46,18 +48,27 @@ # } GroupPermission_D = { - "groupId": "24231-52321-43523-64353-23111", - "permissionIds": [0,1,2] + "type": "group", + "groupId": "ebd7db70-290b-4d85-b366-b4be9d5967e4", + "permissionIds": [0,1,2], + "permissionNames": [] +} +GroupPermission_R ={ + "type": "group", + "groupId": "ebd7db70-290b-4d85-b366-b4be9d5967e4", + "permissionIds": [1], + "permissionNames": [] } -groupID1 = "24231-52321-43523-64353-23111" +groupID1 = "ebd7db70-290b-4d85-b366-b4be9d5967e4" grouppermission = GroupPermission.from_dict(GroupPermission_D) +perm = Permission.from_dict(GroupPermission_R) #groupPerm = argus.grouppermissions.get_permissions_for_group(groupID1) #print("groupPerms are "+ str(groupPerm)) -grouppermission = GroupPermission(GroupPermission_D.get("groupId"),[0,1,2]) +#grouppermission = GroupPermission(GroupPermission_D.get("groupId"),[0,1,2]) groupPerm1 = argus.grouppermissions.add_permissions_for_group(grouppermission) print("groupPerms are "+ str(groupPerm1)) -gpermission = GroupPermission(groupID1,[2]) -deletedPerm = argus.grouppermissions.delete_permissions_for_group(groupPerm1) #this is not working as adding group_permission returns a permission object instead of groupPermission object ? + +deletedPerm = argus.grouppermissions.delete_permissions_for_group(perm) #this is not working as adding group_permission returns a permission object instead of groupPermission object ? print("removed groupPerms are "+ str(deletedPerm)) #argus.permissions = PermissionsServiceClient(argus) @@ -96,9 +107,9 @@ # res = argus.permissions.items() # res = argus.dashboards.items() print ("calling groupPerms") - res1 = groupPerm1 +# res1 = groupPerm1 - print ('size of result: ', len(res)) + #print ('size of result: ', len()) #res = argus.permissions.get(16348603) # Get notif # alert = res[0][1] From fe1e70d37c26d852ba45138bf47ed63be21a281e Mon Sep 17 00:00:00 2001 From: Sneha Basu Date: Thu, 12 Aug 2021 19:56:38 +0800 Subject: [PATCH 24/24] added case handling --- argusclient/client.py | 14 ++++++++++---- tests/test_data.py | 2 +- tests/test_service.py | 12 ++++++------ 3 files changed, 17 insertions(+), 11 deletions(-) diff --git a/argusclient/client.py b/argusclient/client.py index 97e5fb6..37207fb 100644 --- a/argusclient/client.py +++ b/argusclient/client.py @@ -472,7 +472,11 @@ def _init_all(self, coll=None): def get_permissions_for_group(self, groupId): - return convert(self.argus._request("get", "grouppermission", params=list(groupId))) + resp = convert(self.argus._request("get", "grouppermission", params=list(groupId))) + if resp: + for group_id, perms in resp.items(): + self._coll[group_id] = perms + return self._coll def add_permissions_for_group(self, grouppermission): """ @@ -481,18 +485,20 @@ def add_permissions_for_group(self, grouppermission): """ if not isinstance(grouppermission, GroupPermission): raise TypeError("Need a GroupPermission object, got: %s" % type(grouppermission)) + updatedGroup = convert(self.argus._request("post", "grouppermission", dataObj=grouppermission)) + self._coll[updatedGroup.groupId] = updatedGroup.permissionIds return updatedGroup def delete_permissions_for_group(self, grouppermission): + deleted_permission = None if not isinstance(grouppermission, Permission): raise TypeError("Need a Permission object, got: %s" % type(grouppermission)) perms_to_delete = grouppermission.permissionIds if perms_to_delete == []: - raise ValueError("Permission is not already assigned and hence cant be deleted") - #add check for if permissions dont exist - deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) + if tuple(perms_to_delete) in self._coll: + deleted_permission = convert(self.argus._request("delete", "grouppermission", dataObj=grouppermission)) if deleted_permission: return True return False diff --git a/tests/test_data.py b/tests/test_data.py index 52256de..e7478d6 100644 --- a/tests/test_data.py +++ b/tests/test_data.py @@ -137,7 +137,7 @@ groupPermission_E = { "type": "group", "groupId": permissionGroup2ID, - "permissionIds": [0] + "permissionIds": [0,1] } groupPermission_F = { diff --git a/tests/test_service.py b/tests/test_service.py index d3aaa49..636a101 100644 --- a/tests/test_service.py +++ b/tests/test_service.py @@ -399,20 +399,20 @@ def testGroupPermissionsID(self, mockGet): self.assertEquals(res.get("permissionIds"), [0, 1, 2]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockGet.call_args)) - @mock.patch('requests.Session.post', return_value=MockResponse({}, 200)) + @mock.patch('requests.Session.post', return_value=MockResponse(json.dumps(groupPermission_E), 200)) def testGroupPermissionsIDAdd(self, mockPost): ggroupId = permissionGroup2ID gperms = GroupPermission(ggroupId, [1]) res = self.argus.grouppermissions.add_permissions_for_group(gperms) - self.assertEquals(res.get("permissionIds"), [0, 1]) + self.assertEquals(res.permissionIds, [0, 1]) self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockPost.call_args)) - #@mock.patch('requests.Session.post', return_value=MockResponse(json.dumps({testId: [groupPermission_D]}),200)) - @mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(groupPermission_E), 200)) + + @mock.patch('requests.Session.delete', return_value=MockResponse(json.dumps(groupPermission_F), 200)) def testDeletePermission(self, mockDelete): - gpermission = GroupPermission(permissionGroup3ID,[2]) + gpermission = Permission.from_dict(groupPermission_F) # group with new permissions res = self.argus.grouppermissions.delete_permissions_for_group(gpermission) - self.assertEquals(res.get("permissionIds"), [0,1]) + self.assertEquals(res, False) #self._colls is empty self.assertIn((os.path.join(endpoint, "grouppermission"),), tuple(mockDelete.call_args))