Esempio n. 1
0
def add_sample_group(authn):  # pylint: disable=too-many-locals
    """Add sample group."""
    # Validate input
    try:
        data = request.get_json()
        name = data['name']
        organization = Organization.query.filter_by(
            name=data['organization_name']).first()
    except TypeError as exc:
        current_app.logger.exception(f'Sample Group creation error:\n{exc}')
        raise ParseError(f'Missing Sample Group creation payload.\n{exc}')
    except KeyError:
        raise ParseError('Invalid Sample Group creation payload.')
    authn_user = User.query.filter_by(uuid=authn.sub).first()
    if authn_user.uuid not in organization.writer_uuids():
        raise PermissionDenied(
            'You do not have permission to write to that organization.')

    # Create Sample Group
    try:
        sample_group = SampleGroup(
            name=name,
            organization_uuid=organization.uuid,
            description=data.get('description', False),
            is_library=data.get('is_library', False),
            is_public=data.get('is_public', False),
        ).save()
        return sample_group.serializable(), 201
    except IntegrityError as integrity_error:
        current_app.logger.exception('Sample Group could not be created.')
        raise ParseError('Duplicate group name.')
Esempio n. 2
0
def get_group_analysis_result_fields_by_name(group_name, module_name):
    """Get all fields of the specified analysis result."""
    try:
        group = SampleGroup.from_name(group_name)
        analysis_result = SampleGroupAnalysisResult.from_name_group(
            module_name, group.uuid)
        result = {
            field.field_name: field.data
            for field in analysis_result.module_fields
        }
        return result, 200
    except NoResultFound:
        raise NotFound('Analysis Result does not exist.')
Esempio n. 3
0
def get_samples_for_group_by_name(group_name):
    """Get single sample group's list of samples."""
    try:
        sample_group = SampleGroup.from_name(group_name)
        result = {
            'samples':
            [sample.serializable() for sample in sample_group.samples],
        }
        return result, 200
    except ValueError:
        raise ParseError('Invalid Sample Group UUID.')
    except NoResultFound:
        raise NotFound('Sample Group does not exist')
Esempio n. 4
0
 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])
Esempio n. 5
0
def get_analysis_result_fields_by_name(lib_name, sample_name, module_name):
    """Get all fields of the specified analysis result."""
    try:
        library = SampleGroup.from_name(lib_name)
        sample = Sample.from_name_library(sample_name, library.uuid)
        analysis_result = SampleAnalysisResult.from_name_sample(
            module_name, sample.uuid)
        result = {
            field.field_name: field.data
            for field in analysis_result.module_fields
        }
        return result, 200
    except NoResultFound:
        raise NotFound('Analysis Result does not exist.')
Esempio n. 6
0
def add_sample(_):
    """Add sample."""
    try:
        post_data = request.get_json()
        library = SampleGroup.from_uuid(post_data['library_uuid'])
        sample = library.sample(post_data['name'], force_new=True)
    except TypeError:
        raise ParseError('Missing Sample creation payload.')
    except KeyError:
        raise ParseError('Invalid Sample creation payload.')
    except NoResultFound:
        raise InvalidRequest('Library does not exist!')
    except IntegrityError:
        raise InvalidRequest(
            'A Sample with that name already exists in the library.')
    return sample.serializable(), 201
Esempio n. 7
0
    def sample_group(self,
                     name,
                     description='',
                     is_library=False,
                     is_public=True):
        """Return a SampleGroup bound to this organization.

        Create and save the SampleGroup if it does not already exist.
        """
        sample_groups = [sg for sg in self.sample_groups if sg.name == name]
        if sample_groups:
            sample_group = sample_groups[0]
        else:
            sample_group = SampleGroup(name,
                                       self.uuid,
                                       description=description,
                                       is_library=is_library,
                                       is_public=is_public).save()
        return sample_group
Esempio n. 8
0
 def test_single_organization_sample_groups(self):
     """Ensure getting sample groups for an organization behaves correctly."""
     user = add_user('new_user WEDFVBN', '*****@*****.**',
                     'somepassword')
     org = Organization.from_user(user, 'Test Org WEDFVBN')
     group = SampleGroup(name=f'SampleGroup WEDFVBN',
                         organization_uuid=org.uuid).save()
     with self.client:
         response = self.client.get(
             f'/api/v1/organizations/{org.uuid}/sample_groups',
             content_type='application/json',
         )
         data = json.loads(response.data.decode())
         self.assertEqual(response.status_code, 200)
         self.assertIn('success', data['status'])
         self.assertEqual(len(data['data']['sample_groups']), 1)
         self.assertEqual(
             data['data']['sample_groups'][0]['sample_group']['name'],
             group.name)
Esempio n. 9
0
 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'])
Esempio n. 10
0
def post_group_analysis_result_field_by_name(group_name, module_name,
                                             field_name):
    """Store the payload in the specified analysis result field.

    Create the analysis result if it does not exist but do not create
    the sample or library.
    """
    try:
        group = SampleGroup.from_name(group_name)
    except NoResultFound:
        raise NotFound('Analysis Result does not exist.')
    try:
        analysis_result = group.analysis_result(module_name)
        post_data = request.get_json()
        field = analysis_result.field(field_name)
        field.set_data(post_data[field_name])
        result = field.serializable()
        return result, 201
    except TypeError:
        raise ParseError('Missing registration payload.')
    except KeyError:
        raise ParseError('Invalid registration payload.')
Esempio n. 11
0
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