def test_has_permission_fail_on_get_info_server_error():
    wsc = create_autospec(Workspace, spec_set=True, instance=True)

    ws = WS(wsc)
    wsc.administer.assert_called_once_with({'command': 'listModRequests'})

    wsc.administer.side_effect = [
        {'perms': [{'a': 'w', 'b': 'r', 'c': 'a'}]},
        ServerError('JSONRPCError', -32500, 'Thanks Obama')]

    with raises(Exception) as got:
        ws.has_permission(UserID('b'), WorkspaceAccessType.READ, upa=UPA('67/8/90'))
    assert_exception_correct(got.value, ServerError('JSONRPCError', -32500, 'Thanks Obama'))
    def run_FamaGenomeProfiling(self, ctx, params):
        """
        Run genome functional profiling module of Fama.
        :param params: instance of type "FamaGenomeProfilingParams"
           (Parameters for genome functional profiling. workspace_name - the
           name of the workspace for input/output genome_refs - references to
           a genome object ref_dataset - the name of Fama reference dataset
           output_result_name - the name of the output DomainAnnotation) ->
           structure: parameter "workspace_name" of String, parameter
           "genome_ref" of list of String, parameter "ref_dataset" of String,
           parameter "output_feature_set_name" of String, parameter
           "output_annotation_name" of String
        :returns: instance of type "ReportResults" (Output report parameters
           report_name - the name of the report object report_ref - the
           reference to the report object) -> structure: parameter
           "report_name" of String, parameter "report_ref" of String
        """
        # ctx is the context object
        # return variables are: output
        #BEGIN run_FamaGenomeProfiling
        # Import protein sequences from input genome_ref
        ws_client = Workspace(self.ws_url)
        input_genome_refs = params['genome_ref']
        fama_reference = params['ref_dataset']
        input_proteins = {}
        name2ref = {}
        for input_genome_ref in input_genome_refs:
            ret = ws_client.get_objects2(
                {'objects': [{
                    'ref': input_genome_ref
                }]})['data'][0]
            obj_data = ret['data']
            obj_name = ret['info'][1]
            obj_type = ret['info'][2].split('.')[1].split('-')[0]
            if obj_type == 'GenomeSet':
                print('GenomeSet data', obj_data)
                genome_refs = []
                if 'elements' in obj_data:
                    genome_refs = [
                        item['ref'] for item in obj_data['elements'].values()
                    ]
                elif 'items' in obj_data:
                    genome_refs = [item['ref'] for item in obj_data['items']]
                for sub_obj_ref in genome_refs:
                    ret = ws_client.get_objects2(
                        {'objects': [{
                            'ref': sub_obj_ref
                        }]})['data'][0]
                    genome_data = ret['data']
                    genome_name = ret['info'][1]
                    if genome_name in name2ref:
                        raise ServerError(
                            'All input genome names must be unique. Check ' +
                            genome_name)
                    name2ref[genome_name] = sub_obj_ref
                    proteins = genome_proteins_to_fasta(
                        genome_data, self.shared_folder)
                    input_proteins[genome_name] = {}
                    input_proteins[genome_name]['fwd'] = proteins
            elif obj_type == 'Genome':
                if obj_name in name2ref:
                    raise ServerError('All input genome names must be unique')
                name2ref[obj_name] = input_genome_ref
                proteins = genome_proteins_to_fasta(obj_data,
                                                    self.shared_folder)
                input_proteins[obj_name] = {}
                input_proteins[obj_name]['fwd'] = proteins
            else:
                raise ServerError('Incompatible object: ' + input_genome_ref +
                                  ' (' + obj_name + ')')

        self.log('Input sequence files:', str(input_proteins))
        self.log('reference: ', fama_reference)
        # Run Fama
        fama_params = {
            'input_proteins': input_proteins,
            'work_dir': self.shared_folder,
            'reference': fama_reference,
            'ws_name': params['workspace_name'],
            'ws_client': ws_client,
            'featureset_name': params['output_feature_set_name'],
            'annotation_prefix': params['output_annotation_name'],
            'name2ref': name2ref
        }
        fama_output = protein_functional_profiling_pipeline(fama_params)
        objects_created = fama_output['objects_created']

        dfu = DataFileUtil(self.callback_url)
        workspace_id = dfu.ws_name_to_id(params['workspace_name'])

        object_type = 'KBaseCollections.FeatureSet'
        save_object_params = {
            'id':
            workspace_id,
            'objects': [{
                'type': object_type,
                'data': fama_output['feature_set_data'],
                'name': params['output_feature_set_name']
            }]
        }

        try:
            dfu_oi = dfu.save_objects(save_object_params)[0]
        except ServerError as dfue:
            # not really any way to test this block
            self.log('Logging exception saving feature set')
            self.log(str(dfue))
            raise
        feature_set_obj_ref = "{}/{}/{}".format(dfu_oi[6], dfu_oi[0],
                                                dfu_oi[4])
        objects_created.append({
            'ref': feature_set_obj_ref,
            'description': 'Filtered genome features'
        })

        self.log('FeatureSet saved to ' + feature_set_obj_ref)

        # Write HTML output to workspace
        message = 'Fama protein functional profiling finished successfully'

        try:
            dfu_output = dfu.file_to_shock(
                {'file_path': fama_output['html_report']})
        except ServerError as dfue:
            # not really any way to test this block
            self.log('Logging exception loading results to shock')
            self.log(str(dfue))
            raise
        self.log('HTML report saved: ' + str(dfu_output))

        html_links = [{
            'shock_id': dfu_output['shock_id'],
            'description': 'HTML report for Fama App',
            'name': 'fama_report.html',
            'label': 'Fama_report'
        }]
        for krona_file in fama_output['krona_charts']:
            try:
                dfu_output = dfu.file_to_shock({'file_path': krona_file})
                html_links.append({
                    'shock_id':
                    dfu_output['shock_id'],
                    'description':
                    'Krona chart for function taxonomy profile',
                    'name':
                    fama_output['krona_charts'][krona_file][0],
                    'label':
                    fama_output['krona_charts'][krona_file][1]
                })
            except ServerError as dfue:
                # not really any way to test this block
                self.log('Logging exception loading results to shock')
                self.log(str(dfue))
                raise

        self.log('Krona chart saved: ' + str(dfu_output))

        # Save report
        report_params = {
            'message': message,
            'objects_created': objects_created,
            'direct_html_link_index': 0,
            'html_links': html_links,
            'file_links': fama_output['report_files'],
            'report_object_name': 'fama_profiling_report_' + str(uuid.uuid4()),
            'workspace_name': params['workspace_name'],
            'html_window_height': 460
        }
        try:
            self.log('Call KBaseReport at ' + str(self.callback_url))
            report = KBaseReport(self.callback_url)
            self.log('Ready to save KBase report: ' + str(report_params))
            report_info = report.create_extended_report(report_params)
        except ServerError as kre:
            # not really any way to test this block
            self.log('Logging exception saving report')
            self.log(str(kre))
            raise

        report_info['report_params'] = report_params
        self.log('KBase report saved: ' + str(report_info))
        output = {
            'report_name': report_info['name'],
            'report_ref': report_info['ref']
        }

        #END run_FamaGenomeProfiling

        # At some point might do deeper type checking...
        if not isinstance(output, dict):
            raise ValueError('Method run_FamaGenomeProfiling return value ' +
                             'output is not type dict as required.')
        # return the results
        return [output]
def test_get_user_workspaces_anonymous_fail_server_error():
    _get_user_workspaces_anonymous_fail_ws_exception(
        ServerError('JSONRPCError', -32500, 'aw crapadoodles'),
        ServerError('JSONRPCError', -32500, 'aw crapadoodles')
    )
def test_get_user_workspaces_fail_invalid_user():
    _get_user_workspaces_fail_ws_exception(
        ServerError('JSONRPCError', -32500, 'User foo is not a valid user'),
        NoSuchUserError('User foo is not a valid user')
    )
def test_has_permission_fail_on_get_perms_server_error():
    _has_permission_fail_ws_exception(
        ServerError('JSONRPCError', -32500, "Things is f'up"),
        ServerError('JSONRPCError', -32500, "Things is f'up")
    )
def test_has_permission_fail_on_get_perms_deleted_workspace():
    _has_permission_fail_ws_exception(
        ServerError('JSONRPCError', -32500, 'Workspace 22 is deleted'),
        NoSuchWorkspaceDataError('Workspace 22 is deleted')
    )
def test_has_permission_fail_on_get_perms_no_workspace():
    _has_permission_fail_ws_exception(
        ServerError('JSONRPCError', -32500, 'No workspace with id 22 exists'),
        NoSuchWorkspaceDataError('No workspace with id 22 exists')
    )
def test_init_fail():
    _init_fail(None, ValueError('client cannot be a value that evaluates to false'))

    wsc = create_autospec(Workspace, spec_set=True, instance=True)
    wsc.administer.side_effect = ServerError('jsonrpcerror', 24, 'poopoo')
    _init_fail(wsc, ServerError('jsonrpcerror', 24, 'poopoo'))
Example #9
0
 def __init__(self, name=None, code=None, message=None, **kw):
     ServerError.__init__(self, name, code, message, **kw)