def test_it_creates_the_project_and_reports_folder_errors( do_gql_post, gql_query, mk_gql_variables, syn_test_helper, mocker): gql_variables = mk_gql_variables(with_folders=True) folders = gql_variables['folders'] assert len(folders) > 0 _real_store = Synapse.client().store def _store_proxy(obj, **kwargs): if isinstance(obj, synapseclient.Folder) or isinstance( obj, synapseclient.Wiki): raise Exception('some random error') return _real_store(obj, **kwargs) with mocker.mock_module.patch.object(Synapse.client(), 'store', new=_store_proxy): body = do_gql_post(gql_query, gql_variables).get('body') assert dispose_syn_project_from_body(body, syn_test_helper) assert body.get('errors', None) is None jerrors = body['data']['createSynProject']['errors'] assert jerrors for folder_path in folders: for folder_part in list(filter(None, folder_path.split('/'))): assert 'Error creating project folder: {0}.'.format( folder_part) in jerrors
def mutate(self, info, name, permissions, annotations, wiki, folders, posts): # Build the annotations project_annotations = {} if annotations: for annotation in annotations: project_annotations[annotation['key']] = annotation['value'] # Create the Project project = Synapse.client().store( Project(name=name, annotations=project_annotations) ) # Add the permissions if permissions: for permission in permissions: principal_id = permission['principal_id'] access = permission['access'] access_type = getattr(Synapse, '{0}_PERMS'.format(access)) Synapse.client().setPermissions( project, principal_id, accessType=access_type, warn_if_inherits=False ) # Add the the folders if folders: for folder_name in folders: Synapse.client().store(Folder(name=folder_name, parent=project)) # Add the posts if posts: forum_id = Synapse.client().restGET( '/project/{0}/forum'.format(project.id)).get('id') for post in posts: body = { 'forumId': forum_id, 'title': post['title'], 'messageMarkdown': post['message_markdown'] } Synapse.client().restPOST("/thread", body=json.dumps(body)) # Add the wiki if wiki: Synapse.client().store(Wiki(title=wiki.title, markdown=wiki.markdown, owner=project)) new_syn_project = SynProject.from_project(project) return CreateSynProject(syn_project=new_syn_project)
def test_it_adds_and_removes_permissions(do_gql_post, gql_query, mk_gql_variables, syn_test_helper, syn_client): project = syn_test_helper.create_project() gql_variables = mk_gql_variables(project, with_permissions=True) permissions = gql_variables.get('permissions') assert len(permissions) > 0 body = do_gql_post(gql_query, gql_variables).get('body') assert body.get('errors', None) is None for permission in permissions: principal_id = permission['principalId'] access = permission['access'] access_type = getattr(Synapse, '{0}_PERMS'.format(access)) perms = syn_client.getPermissions(project, principal_id) assert set(perms) == set(access_type) # Make sure permissions are removed removed_perm = permissions.pop() body = do_gql_post(gql_query, gql_variables).get('body') assert body.get('errors', None) is None acl = Synapse.client()._getACL(project) current_principal_ids = [ int(r['principalId']) for r in acl['resourceAccess'] ] assert int(removed_perm['principalId']) not in current_principal_ids
def test_update_syn_project(syn_client, syn_test_helper): project = syn_test_helper.create_project() team = syn_test_helper.create_team() id = project.id name = syn_test_helper.uniq_name(prefix='New Project Name ') permissions = [{"principalId": int(team.id), "access": "CAN_EDIT"}] other_test_user_id = ParamStore._get_from_os('SYNAPSE_OTHER_USER_ID') if other_test_user_id: permissions.append({ "principalId": int(other_test_user_id), "access": "CAN_EDIT" }) else: print('WARNING: SYNAPSE_OTHER_USER_ID environment variable not set.') q = ''' mutation UpdateSynProject($id: String!, $name: String, $permissions: [PermissionDataInput]) { updateSynProject(id: $id, name: $name, permissions: $permissions) { synProject { id name } } } ''' v = {"id": id, "name": name, "permissions": permissions} body = do_post(q, v).get('body') assert not body.get('errors', None) jsyn_project = body['data']['updateSynProject']['synProject'] assert jsyn_project['name'] == name # Reload the project project = syn_client.get(project) assert project.name == name # Permissions for permission in permissions: principal_id = permission['principalId'] access = permission['access'] access_type = getattr(Synapse, '{0}_PERMS'.format(access)) perms = syn_client.getPermissions(project, principal_id) assert set(perms) == set(access_type) # Make sure permissions are removed removed_perm = permissions.pop() body = do_post(q, v).get('body') assert not body.get('errors', None) acl = Synapse.client()._getACL(project) current_principal_ids = [ int(r['principalId']) for r in acl['resourceAccess'] ] assert int(removed_perm['principalId']) not in current_principal_ids
def create_team(self, **kwargs): """ Creates a new Team and adds it to the trash queue. """ if not 'name' in kwargs: kwargs['name'] = self.uniq_name(prefix=kwargs.get('prefix', '')) kwargs.pop('prefix', None) team = Synapse.client().store(Team(**kwargs)) self.dispose_of(team) return team
def create_file(self, **kwargs): """ Creates a new File and adds it to the trash queue. """ if not 'name' in kwargs: kwargs['name'] = self.uniq_name(prefix=kwargs.get('prefix', '')) kwargs.pop('prefix', None) file = Synapse.client().store(File(**kwargs)) self.dispose_of(file) return file
def create_project(self, **kwargs): """ Creates a new Project and adds it to the trash queue. """ if not 'name' in kwargs: kwargs['name'] = self.uniq_name(prefix=kwargs.get('prefix', '')) kwargs.pop('prefix', None) project = Synapse.client().store(Project(**kwargs)) self.dispose_of(project) return project
def dispose_syn_project_from_body(body, syn_test_helper): if body is None: return project_id = body.get('data', {}).get('createSynProject', {}).get('synProject', {}).get('id', None) if project_id: syn_project = Synapse.client().get(project_id) syn_test_helper.dispose_of(syn_project) return syn_project else: return None
def create_wiki(self, **kwargs): """ Creates a new Wiki and adds it to the trash queue. """ if not 'title' in kwargs: kwargs['title'] = self.uniq_name(prefix=kwargs.get('prefix', '')) kwargs.pop('prefix', None) if not 'markdown' in kwargs: kwargs['markdown'] = 'My Wiki {0}'.format(kwargs['title']) wiki = Synapse.client().store(Wiki(**kwargs)) self.dispose_of(wiki) return wiki
def test_it_creates_the_project_and_reports_wiki_errors( do_gql_post, gql_query, mk_gql_variables, syn_test_helper, mocker): gql_variables = mk_gql_variables(with_wiki=True) wiki = gql_variables['wiki'] assert wiki _real_store = Synapse.client().store def _store_proxy(obj, **kwargs): if isinstance(obj, synapseclient.Folder) or isinstance( obj, synapseclient.Wiki): raise Exception('some random error') return _real_store(obj, **kwargs) with mocker.mock_module.patch.object(Synapse.client(), 'store', new=_store_proxy): body = do_gql_post(gql_query, gql_variables).get('body') assert dispose_syn_project_from_body(body, syn_test_helper) assert body.get('errors', None) is None jerrors = body['data']['createSynProject']['errors'] assert jerrors assert 'Error creating project wiki.' in jerrors
def test_it_updates_the_project_and_reports_permission_errors( do_gql_post, gql_query, mk_gql_variables, syn_test_helper, mocker): project = syn_test_helper.create_project() gql_variables = mk_gql_variables(project, with_permissions=True) permissions = gql_variables['permissions'] assert len(permissions) > 0 # User/Team does not exist error. with mocker.mock_module.patch.object(Synapse.client(), 'setPermissions') as mock: mock.side_effect = Exception('a foreign key constraint fails') gql_variables['name'] = syn_test_helper.uniq_name( prefix='New Project Name ') body = do_gql_post(gql_query, gql_variables).get('body') assert body.get('errors', None) is None jerrors = body['data']['updateSynProject']['errors'] assert jerrors for permission in permissions: assert 'User or Team ID: ' \ '{0} does not exist.'.format(permission['principalId']) in jerrors # General unknown error. with mocker.mock_module.patch.object(Synapse.client(), 'setPermissions') as mock: mock.side_effect = Exception('some random error') gql_variables['name'] = syn_test_helper.uniq_name( prefix='New Project Name ') body = do_gql_post(gql_query, gql_variables).get('body') assert body.get('errors', None) is None jerrors = body['data']['updateSynProject']['errors'] assert jerrors for permission in permissions: assert 'Error setting permission for User or Team ID: {0}'.format( permission['principalId']) in jerrors
def mutate(self, info, id, name, permissions): # Create the Project project = Synapse.client().get(id) if name: project.name = name if permissions: for permission in permissions: principal_id = permission['principal_id'] access = permission['access'] access_type = getattr(Synapse, '{0}_PERMS'.format(access)) # Only add permissions, do not update permissions. current_perms = Synapse.client().getPermissions( project, principal_id) if not current_perms: Synapse.client().setPermissions(project, principal_id, accessType=access_type, warn_if_inherits=False) # Remove permissions new_principal_ids = [int(p['principal_id']) for p in permissions] acl = Synapse.client()._getACL(project) current_principal_ids = [ int(r['principalId']) for r in acl['resourceAccess'] ] for current_principal_id in current_principal_ids: if current_principal_id == int(project.createdBy): continue if not current_principal_id in new_principal_ids: Synapse.client().setPermissions(project, current_principal_id, accessType=None, warn_if_inherits=False) project = Synapse.client().store(project) updated_syn_project = SynProject.from_project(project) return UpdateSynProject(syn_project=updated_syn_project)
def mutate(self, info, name, **kwargs): errors = [] permissions = kwargs.get('permissions', None) annotations = kwargs.get('annotations', None) wiki = kwargs.get('wiki', None) folders = kwargs.get('folders', None) posts = kwargs.get('posts', None) # Check if a project with the same name already exists. project_name_taken = Synapse.client().findEntityId(name) is not None if project_name_taken: raise ValueError( 'Another Synapse project with the name: {0} already exists.'. format(name)) # Build the annotations project_annotations = {} if annotations: for annotation in annotations: project_annotations[annotation['key']] = annotation['value'] # Create the Project project = Synapse.client().store( Project(name=name, annotations=project_annotations)) # Add the permissions if permissions: for permission in permissions: try: principal_id = permission.get('principal_id') access = permission.get('access') access_type = getattr(Synapse, '{0}_PERMS'.format(access)) try: Synapse.client().setPermissions(project, principal_id, accessType=access_type, warn_if_inherits=False) except Exception as syn_ex: logger.exception( 'Error setting permission: {0} - {1}'.format( permission, syn_ex)) if 'a foreign key constraint fails' in str(syn_ex): errors.append( 'User or Team ID: {0} does not exist.'.format( principal_id)) else: errors.append( 'Error setting permission for User or Team ID: {0}' .format(principal_id)) except Exception as ex: logger.exception( 'Error creating project permissions: {0} - {1}'.format( permission, ex)) errors.append('Error creating project permissions.') # Add the the folders if folders: for folder_path in folders: folder_path_parts = list(filter(None, folder_path.split('/'))) parent = project for folder_name in folder_path_parts: try: parent = Synapse.client().store( Folder(name=folder_name, parent=parent)) except Exception as syn_ex: logger.exception( 'Error creating project folder: {0} - {1}'.format( folder_name, syn_ex)) errors.append( 'Error creating project folder: {0}.'.format( folder_name)) # Add the posts if posts: try: forum_id = Synapse.client().restGET( '/project/{0}/forum'.format(project.id)).get('id') for post in posts: try: body = { 'forumId': forum_id, 'title': post.get('title'), 'messageMarkdown': post.get('message_markdown') } Synapse.client().restPOST('/thread', body=json.dumps(body)) except Exception as syn_ex: logger.exception( 'Error creating project post: {0} - {1}'.format( post, syn_ex)) errors.append( 'Error creating project post: {0}.'.format( post.get('title', None))) except Exception as ex: logger.exception( 'Error creating project posts: {1} - {0}'.format( posts, ex)) errors.append('Error creating projects posts.') # Add the wiki if wiki: try: Synapse.client().store( Wiki(title=wiki.title, markdown=wiki.markdown, owner=project)) except Exception as syn_ex: logger.exception( 'Error creating project wiki: {0} - {1}'.format( wiki, syn_ex)) errors.append('Error creating project wiki.') new_syn_project = SynProject.from_project(project) return CreateSynProject(syn_project=new_syn_project, errors=(errors if errors else None))
def resolve_syn_project(self, info, id): project = Synapse.client().get(id) if project: return SynProject.from_project(project) else: return None
def mutate(self, info, id, **kwargs): errors = [] name = kwargs.get('name', None) permissions = kwargs.get('permissions', None) # Get the Project project = Synapse.client().get(id) if name: project.name = name project = Synapse.client().store(project) # An empty list means remove all permissions. # A null list means don't remove any permissions. if permissions is not None: for permission in permissions: try: principal_id = permission['principal_id'] access = permission['access'] access_type = getattr(Synapse, '{0}_PERMS'.format(access)) # Only add permissions, do not update permissions. current_perms = Synapse.client().getPermissions( project, principal_id) if not current_perms: try: Synapse.client().setPermissions( project, principal_id, accessType=access_type, warn_if_inherits=False) except Exception as syn_ex: logger.exception( 'Error setting permission: {0} - {1}'.format( permission, syn_ex)) if 'a foreign key constraint fails' in str(syn_ex): errors.append( 'User or Team ID: {0} does not exist.'. format(principal_id)) else: errors.append( 'Error setting permission for User or Team ID: {0}' .format(principal_id)) except Exception as ex: logger.exception( 'Error creating project permissions: {0} - {1}'.format( permission, ex)) errors.append('Error creating project permissions.') # Remove permissions try: new_principal_ids = [ int(p['principal_id']) for p in permissions ] acl = Synapse.client()._getACL(project) current_principal_ids = [ int(r['principalId']) for r in acl['resourceAccess'] ] for current_principal_id in current_principal_ids: if current_principal_id == int(project.createdBy): continue if current_principal_id not in new_principal_ids: Synapse.client().setPermissions(project, current_principal_id, accessType=None, warn_if_inherits=False) except Exception as ex: logger.exception( 'Error removing project permissions: {0}'.format(ex)) errors.append('Error removing project permissions.') # Get the latest version of the project. project = Synapse.client().get(id) updated_syn_project = SynProject.from_project(project) return UpdateSynProject(syn_project=updated_syn_project, errors=(errors if errors else None))
def syn_client(): return Synapse.client()
def dispose(self): """ Cleans up any Synapse objects that were created during testing. This method needs to be manually called after each or all tests are done. """ projects = [] folders = [] files = [] teams = [] wikis = [] others = [] for obj in self._trash: if isinstance(obj, Project): projects.append(obj) elif isinstance(obj, Folder): folders.append(obj) elif isinstance(obj, File): files.append(obj) elif isinstance(obj, Team): teams.append(obj) elif isinstance(obj, Wiki): wikis.append(obj) else: others.append(obj) for syn_obj in wikis: try: Synapse.client().delete(syn_obj) except: pass self._trash.remove(syn_obj) for syn_obj in files: try: Synapse.client().delete(syn_obj) except: pass self._trash.remove(syn_obj) for syn_obj in folders: try: Synapse.client().delete(syn_obj) except: pass self._trash.remove(syn_obj) for syn_obj in projects: try: Synapse.client().delete(syn_obj) except: pass self._trash.remove(syn_obj) for syn_obj in teams: try: Synapse.client().delete(syn_obj) except: pass self._trash.remove(syn_obj) for obj in others: print('WARNING: Non-Supported object found: {0}'.format(obj)) self._trash.remove(obj)
def test_it_creates_the_project_and_reports_posts_errors( do_gql_post, gql_query, mk_gql_variables, syn_test_helper, mocker): gql_variables = mk_gql_variables(with_posts=True) posts = gql_variables['posts'] assert len(posts) > 0 _real_restGET = Synapse.client().restGET def _restGET_proxy(uri, endpoint=None, headers=None, retryPolicy={}, **kwargs): if '/forum' in uri: raise Exception('some random error') return _real_restGET(uri, endpoint=endpoint, headers=headers, retryPolicy=retryPolicy, **kwargs) with mocker.mock_module.patch.object(Synapse.client(), 'restGET', new=_restGET_proxy): gql_variables['name'] = syn_test_helper.uniq_name( prefix='New Project Name ') body = do_gql_post(gql_query, gql_variables).get('body') assert dispose_syn_project_from_body(body, syn_test_helper) assert body.get('errors', None) is None jerrors = body['data']['createSynProject']['errors'] assert jerrors assert 'Error creating projects posts.' in jerrors _real_restPOST = Synapse.client().restPOST def _restPOST_proxy(uri, body, endpoint=None, headers=None, retryPolicy={}, **kwargs): if '/thread' in uri: raise Exception('some random error') return _real_restPOST(uri, body, endpoint=endpoint, headers=headers, retryPolicy=retryPolicy, **kwargs) with mocker.mock_module.patch.object(Synapse.client(), 'restPOST', new=_restPOST_proxy): gql_variables['name'] = syn_test_helper.uniq_name( prefix='New Project Name ') body = do_gql_post(gql_query, gql_variables).get('body') assert dispose_syn_project_from_body(body, syn_test_helper) assert body.get('errors', None) is None jerrors = body['data']['createSynProject']['errors'] assert jerrors for post in posts: assert 'Error creating project post: {0}.'.format( post.get('title')) in jerrors
def test_client(): assert Synapse.client() is not None profile = Synapse.client().getUserProfile(refresh=True) assert profile['userName'] == Env.SYNAPSE_USERNAME()
def test_client(): assert Synapse.client() != None profile = Synapse.client().getUserProfile(refresh=True) assert profile['userName'] == ParamStore.SYNAPSE_USERNAME()