def test_add_organziation_duplicate_name(self): """Ensure duplicate names are not allowed.""" user = add_user('justatest', '*****@*****.**', 'test') Organization.from_user(user, 'Test Organization') self.assertRaises( IntegrityError, lambda: Organization.from_user(user, 'Test Organization'))
def _test_get_group_uuid_from_name(self): """Ensure get sample uuid behaves correctly.""" user = add_user('new_user RRR', '*****@*****.**', 'somepassword') organization = Organization.from_user(user, 'Test Org RRR') sample_group_name = 'Sample Group One RRR' group = add_sample_group(name=sample_group_name, org=organization) sample_group_uuid = str(group.uuid) sample00 = group.sample('SMPL_00 RRR') sample01 = group.sample('SMPL_01 RRR') group.samples = [sample00, sample01] with self.client: response = self.client.get( (f'/api/v1/sample_groups?name={sample_group_name}' f'&owner_name={organization.name}'), content_type='application/json', ) data = json.loads(response.data.decode()) self.assertEqual(response.status_code, 200) self.assertIn('success', data['status']) self.assertEqual(sample_group_uuid, data['data']['sample_group']['uuid']) self.assertEqual(sample_group_name, data['data']['sample_group']['name'])
def test_add_admin_user_to_organization(self): # pylint: disable=invalid-name """Ensure user can be added to organization.""" user1 = add_user('just test1', '*****@*****.**', 'test1') org = Organization.from_user(user1, 'Test Organization') user2 = add_user('just test2', '*****@*****.**', 'test2') org.add_user(user2, role_in_org='admin') self.assertIn(user2.uuid, [el.uuid for el in org.users])
def add_organization_user(authn, organization_uuid): # pylint: disable=too-many-return-statements """Add user to organization.""" try: post_data = request.get_json() organization = Organization.from_uuid(UUID(organization_uuid)) admin = User.from_uuid(authn.sub) except TypeError: raise ParseError('Missing membership payload.') except ValueError: raise ParseError('Invalid organization UUID.') except NoResultFound: raise NotFound('Organization does not exist') try: user = User.from_uuid(post_data['user_uuid']) except KeyError: raise ParseError('Invalid membership payload.') except NoResultFound: raise NotFound('User does not exist') if admin.uuid in organization.admin_uuids(): if user.uuid in organization.reader_uuids(): raise InvalidRequest('User is already part of organization.') role = post_data.get('role', 'read') try: organization.add_user(user, role_in_org=role) result = {'message': f'${user.username} added to ${organization.name}'} return result, 200 except IntegrityError as integrity_error: current_app.logger.exception('IntegrityError encountered.') raise InternalError(str(integrity_error)) raise PermissionDenied('You do not have permission to add a user to that organization.')
def test_add_sample_group(self, auth_headers, login_user): """Ensure a new sample group can be added to the database.""" org = Organization.from_user(login_user, 'Test Org') group_name = 'The Most Sampled of Groups' with self.client: response = self.client.post( '/api/v1/sample_groups', headers=auth_headers, data=json.dumps( dict( name=group_name, organization_name=org.name, )), content_type='application/json', ) data = json.loads(response.data.decode()) self.assertEqual(response.status_code, 201) self.assertIn('success', data['status']) self.assertEqual(group_name, data['data']['sample_group']['name']) # Ensure Analysis Result was created sample_group_id = data['data']['sample_group']['uuid'] sample_group = SampleGroup.query.filter_by( uuid=sample_group_id).one() self.assertTrue(sample_group.analysis_result)
def test_add_organization(self): """Ensure organization model is created correctly.""" user = add_user('justatest', '*****@*****.**', 'test') org = Organization.from_user(user, 'Test Organization') self.assertTrue(org.uuid) self.assertEqual(org.name, 'Test Organization') self.assertEqual(org.primary_admin_uuid, user.uuid) self.assertTrue(org.created_at)
def get_single_organization(organization_uuid): """Get single organization details.""" try: org = Organization.from_uuid(UUID(organization_uuid)) return org.serializable(), 200 except ValueError: raise ParseError('Invalid organization UUID.') except NoResultFound: raise NotFound('Organization does not exist')
def get_organization_users(authn, organization_uuid): """Get single organization's users.""" org = Organization.from_uuid(organization_uuid) authn_user = User.from_uuid(authn.sub) if authn else None if (authn_user and authn_user.uuid in org.reader_uuids()) or org.is_public: result = { 'users': [user.serializable() for user in org.users], } return result, 200 raise PermissionDenied('You do not have permission to see that group.')
def test_unauthorized_add_group_with_organization(self, auth_headers, login_user): # pylint: disable=invalid-name """ Ensure a new sample group cannot be added to an organization to the user is not part of. """ user = add_user('theowner', f'*****@*****.**', 'test') organization = Organization.from_user(user, 'My Test Org') response = self.create_group_for_organization(auth_headers, organization.name) data = json.loads(response.data.decode()) self.assertEqual(response.status_code, 403) self.assertIn('error', data['status']) self.assertEqual( 'You do not have permission to write to that organization.', data['message'])
def get_organizations(): """Get all organizations.""" if 'name' in request.args: name_query = request.args.get('name') try: organization = Organization.from_name(name_query) except NoResultFound: raise NotFound('Organization does not exist') return organization.serializable(), 200 limit = request.args.get('limit', PAGE_SIZE) offset = request.args.get('offset', 0) organizations = Organization.query.all() organizations = sorted(organizations, key=lambda el: str(User.created_at)) organizations = organizations[offset:(offset + limit)] result = {'organizations': [org.serializable() for org in organizations]} return result, 200
def add_organization(authn): """Add organization.""" try: post_data = request.get_json() org_name = post_data['name'] primary_admin = User.from_uuid(authn.sub) is_public = post_data.get('is_public', True) except NoResultFound: raise NotFound('User does not exist') except TypeError: raise ParseError('Missing organization payload.') except KeyError: raise ParseError('Invalid organization payload.') try: org = Organization.from_user(primary_admin, org_name, is_public=is_public) return org.serializable(), 201 except IntegrityError: current_app.logger.exception('There was a problem adding an organization.') raise InternalError(str(integrity_error))
def test_add_duplicate_sample_group(self, auth_headers, login_user): """Ensure failure for non-unique Sample Group name.""" org = Organization.from_user(login_user, 'My Org 123ABGFhCD') grp = SampleGroup(name='mylibrary334123', organization_uuid=org.uuid).save() with self.client: response = self.client.post( '/api/v1/sample_groups', headers=auth_headers, data=json.dumps( dict( name=grp.name, organization_name=org.name, )), content_type='application/json', ) data = json.loads(response.data.decode()) self.assertEqual(response.status_code, 400) self.assertIn('error', data['status']) self.assertEqual('Duplicate group name.', data['message'])
def add_sample_group(name=None, owner=None, org_name=None, is_library=False, org=None, created_at=datetime.datetime.utcnow()): """Wrap functionality for adding sample group.""" if owner is None: owner_name = rand_string() owner = add_user(owner_name, f'{owner_name}@test.com', 'test') if org is None: org = Organization.from_user( owner, org_name if org_name else f'Test Organization {rand_string()}') group = SampleGroup( name=f'SampleGroup {rand_string()}' if name is None else name, organization_uuid=org.uuid, is_library=is_library, created_at=created_at) db.session.add(group) db.session.commit() return group
def test_add_samples_to_group(self, auth_headers, login_user): """Ensure samples can be added to a sample group.""" org = Organization.from_user(login_user, 'My Org 123ABCD') library = SampleGroup(name='mylibrary123123', organization_uuid=org.uuid, is_library=True).save() sample = library.sample('SMPL_01') sample_group = SampleGroup(name='mygrp123123', organization_uuid=org.uuid).save() endpoint = f'/api/v1/sample_groups/{str(sample_group.uuid)}/samples' with self.client: response = self.client.post( endpoint, headers=auth_headers, data=json.dumps(dict(sample_uuids=[str(sample.uuid)], )), content_type='application/json', ) self.assertEqual(response.status_code, 200) data = json.loads(response.data.decode()) self.assertIn('success', data['status']) self.assertIn(sample.uuid, [samp.uuid for samp in sample_group.samples])
def test_add_duplicate_users_to_organization(self): # pylint: disable=invalid-name """Ensure user can only be added to organization once.""" user = add_user('justatest', '*****@*****.**', 'test') org = Organization.from_user(user, 'Test Organization') self.assertRaises(IntegrityError, lambda: org.add_user(user))
def test_add_user_to_organization(self): """Ensure user can be added to organization.""" user = add_user('justatest', '*****@*****.**', 'test') org = Organization.from_user(user, 'Test Organization') print(org.memberships) self.assertIn(user, org.users)