• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python bootstrap.IonObject类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中pyon.core.bootstrap.IonObject的典型用法代码示例。如果您正苦于以下问题:Python IonObject类的具体用法?Python IonObject怎么用?Python IonObject使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了IonObject类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_create_counter_proposal

    def test_create_counter_proposal(self):

        with self.assertRaises(BadRequest) as cm:
            consumer_accept_sap = Negotiation.create_counter_proposal(proposal_status=ProposalStatusEnum.INITIAL)
        self.assertIn('The negotiation parameter must be a valid Negotiation object',cm.exception.message)

        negotiation_handler = Negotiation(self)

        sap = IonObject(OT.EnrollmentProposal,consumer=self.actor_identity._id, provider=self.org._id )

        negotiation = Mock()
        negotiation._id = '456'
        negotiation.type_ = RT.Negotiation
        negotiation.proposals = [sap]

        self.mock_read.return_value = negotiation
        self.mock_create.return_value = ['456', 2]

        neg_id = negotiation_handler.create_negotiation(sap)

        sap.negotiation_id = neg_id

        consumer_accept_sap = Negotiation.create_counter_proposal(negotiation, proposal_status=ProposalStatusEnum.COUNTER,
                originator=ProposalOriginatorEnum.PROVIDER)

        self.assertEqual(consumer_accept_sap.negotiation_id, negotiation._id)
        self.assertEqual(len(negotiation.proposals),1)
        self.assertEqual(consumer_accept_sap.sequence_num, len(negotiation.proposals))
        self.assertEqual(consumer_accept_sap.proposal_status, ProposalStatusEnum.COUNTER)
        self.assertEqual(consumer_accept_sap.originator, ProposalOriginatorEnum.PROVIDER)
开发者ID:ateranishi,项目名称:pyon,代码行数:30,代码来源:test_negotiation.py


示例2: test_get_valid_resource_commitment

    def test_get_valid_resource_commitment(self):
        from pyon.util.containers import get_ion_ts_millis

        # create ION org and an actor
        ion_org = IonObject(RT.Org, name='ION')
        ion_org_id, _ = self.rr.create(ion_org)
        ion_org._id = ion_org_id
        actor = IonObject(RT.ActorIdentity, name='actor1')
        actor_id, _ = self.rr.create(actor)

        # create an expired commitment in the org
        ts = get_ion_ts_millis() - 50000
        com_obj = IonObject(RT.Commitment, provider=ion_org_id, consumer=actor_id, commitment=True, expiration=ts)
        com_id, _ = self.rr.create(com_obj)
        id = self.rr.create_association(ion_org_id, PRED.hasCommitment, com_id)
        c = get_valid_resource_commitments(ion_org_id, actor_id)
        #verify that the commitment is not returned
        self.assertIsNone(c)

        # create a commitment that has not expired yet
        ts = get_ion_ts_millis() + 50000
        com_obj = IonObject(RT.Commitment, provider=ion_org_id, consumer=actor_id, commitment=True, expiration=ts)
        com_id, _ = self.rr.create(com_obj)
        id = self.rr.create_association(ion_org_id, PRED.hasCommitment, com_id)
        c = get_valid_resource_commitments(ion_org_id, actor_id)

        #verify that the commitment is returned
        self.assertIsNotNone(c)
开发者ID:ooici,项目名称:pyon,代码行数:28,代码来源:test_governance.py


示例3: create_extended_resource_container

    def create_extended_resource_container(self, extended_resource_type, resource_id, computed_resource_type=None,
                                           ext_associations=None, ext_exclude=None):

        if not self.service_provider or not self.resource_registry:
            raise Inconsistent("This class is not initialized properly")

        if extended_resource_type not in getextends(OT.ResourceContainer):
            raise BadRequest('Requested resource %s is not extended from %s' % ( extended_resource_type, OT.ResourceContainer) )

        if computed_resource_type and computed_resource_type not in getextends(OT.ComputedAttributes):
            raise BadRequest('Requested resource %s is not extended from %s' % ( computed_resource_type, OT.ComputedAttributes) )

        resource_object = self.resource_registry.read(resource_id)
        if not resource_object:
            raise NotFound("Resource %s does not exist" % resource_id)

        res_container = IonObject(extended_resource_type)
        res_container._id = resource_object._id
        res_container.resource = resource_object

        self.set_container_field_values(res_container, ext_exclude)

        self.set_computed_attributes(res_container, computed_resource_type, ext_exclude)

        self.set_extended_associations(res_container, ext_associations, ext_exclude)

        res_container.ts_created = get_ion_ts()

        return res_container
开发者ID:swarbhanu,项目名称:pyon,代码行数:29,代码来源:resource.py


示例4: create_test_col

 def create_test_col(level=0, ot=dict, no_ion=False):
     if level == 0:
         return get_value(0, 15, uvals)
     if ot == dict:
         res_dict = {}
         num_kinds = 1 if do_ion and no_ion else (1 if do_dict else 0) + (1 if do_list else 0)
         for i in xrange(breadth / num_kinds):
             if do_ion and not no_ion:
                 key = get_key()
                 res_obj = IonObject(restype, name="TestObject %s.%s" % (level, key))
                 res_obj.addl = create_test_col(level-1, dict, no_ion=True)
                 res_dict[key] = res_obj
             else:
                 if do_dict:
                     res_dict[get_key()] = create_test_col(level-1, dict)
                 if do_list:
                     res_dict[get_key()] = create_test_col(level-1, list)
         return res_dict
     elif ot == list:
         res_list = []
         num_kinds = 1 if do_ion and no_ion else (1 if do_dict else 0) + (1 if do_list else 0)
         for i in xrange(breadth / num_kinds):
             if do_ion and not no_ion:
                 res_obj = IonObject(restype, name="TestObject %s.%s" % (level, random.randint(1000, 9999)))
                 res_obj.addl = create_test_col(level-1, dict, no_ion=True)
                 res_list.append(res_obj)
             else:
                 if do_dict:
                     res_list.append(create_test_col(level-1, dict))
                 if do_list:
                     res_list.append(create_test_col(level-1, list))
         return res_list
     elif ot == "IonObject":
         res_obj = IonObject(restype, name="TestObject %s.%s" % (level, random.randint(1000, 9999)))
         return res_obj
开发者ID:edwardhunter,项目名称:scioncc,代码行数:35,代码来源:test_objperf.py


示例5: has_valid_resource_commitments

def has_valid_resource_commitments(actor_id, resource_id):
    '''
    Returns a ResourceCommitmentStatus object indicating the commitment status between this resource/actor
    Can only have an exclusive commitment if actor already has a shared commitment.
    @param actor_id:
    @param resource_id:
    @return:
    '''
    ret_status = IonObject(OT.ResourceCommitmentStatus)
    commitments = get_valid_resource_commitments(resource_id, actor_id)
    if commitments is None:
        #No commitments were found between this resource_id and actor_id - so return default object with
        #fields set to False
        return ret_status

    ret_status.shared = True

    for com in commitments:
        if com.commitment.exclusive == True:
            #Found an exclusive commitment
            ret_status.exclusive = True
            return ret_status

    #Only a shared commitment was found
    return ret_status
开发者ID:jamie-cyber1,项目名称:pyon,代码行数:25,代码来源:__init__.py


示例6: fun

 def fun():
     #ret = Mock()
     ret = IonObject(impl.iontype)
     ret.name = "sample %s" % impl.iontype
     ret.description = "description of sample %s" % impl.iontype
     for k, v in resource_params.iteritems():
         setattr(ret, k, v)
     return ret
开发者ID:tgiguere,项目名称:coi-services,代码行数:8,代码来源:resource_impl_metatest.py


示例7: fun

 def fun():
     #ret = Mock()
     self.log.debug("Creating sample %s" % iontype)
     ret = IonObject(iontype)
     ret.name = "sample %s" % iontype
     ret.description = "description of sample %s" % iontype
     for k, v in resource_params.iteritems():
         setattr(ret, k, v)
     return ret
开发者ID:ooici-eoi,项目名称:coi-services,代码行数:9,代码来源:resource_impl_metatest.py


示例8: obtain_agent_calculation

    def obtain_agent_calculation(self, device_id, result_container):
        ret = IonObject(result_container)

        h_agent, reason = self.get_device_agent(device_id)
        if None is h_agent:
            ret.status = ComputedValueAvailability.NOTAVAILABLE
            ret.reason = reason
        else:
            ret.status = ComputedValueAvailability.PROVIDED

        return h_agent, ret
开发者ID:oldpatricka,项目名称:coi-services,代码行数:11,代码来源:status_builder.py


示例9: execute_resource

    def execute_resource(self, resource_id='', command=None):
        """
        """

        if not command:
            iex = BadRequest('Execute argument "command" not set.')
            self._on_command_error('execute_resource', None, None, None, iex)
            raise iex

        # Grab command syntax.
        id = command.command_id
        cmd = command.command
        args = command.args or []
        kwargs = command.kwargs or {}

        if not command.command:
            iex = BadRequest('Command name not set.')
            self._on_command_error('execute_resource', cmd, args, kwargs, iex)
            raise iex

        # Construct a command result object.
        cmd_result = IonObject("AgentCommandResult",
                               command_id=id,
                               command=cmd,
                               ts_execute=get_ion_ts(),
                               status=0)

        try:
            result = self._fsm.on_event(
                ResourceAgentEvent.EXECUTE_RESOURCE, cmd, *args, **kwargs)
            cmd_result.result = result
            self._on_command('execute_resource', cmd, args, kwargs, result)

        except FSMStateError as ex:
            iex = Conflict(*(ex.args))
            self._on_command_error('execute_resource', cmd, args, kwargs, iex)
            raise iex

        except FSMCommandUnknownError as ex:
            iex = BadRequest(*(ex.args))
            self._on_command_error('execute_resource', cmd, args, kwargs, iex)
            raise iex

        except IonException as iex:
            self._on_command_error('execute_resource', cmd, args, kwargs, iex)
            raise iex

        except Exception as ex:
            iex = ServerError(*(ex.args))
            self._on_command_error('execute_resource', cmd, args, kwargs, iex)
            raise iex

        return cmd_result
开发者ID:seman,项目名称:pyon,代码行数:53,代码来源:agent.py


示例10: create_extended_resource_container

    def create_extended_resource_container(self, extended_resource_type, resource_id, computed_resource_type=None,
                                           ext_associations=None, ext_exclude=None):

        overall_start_time = time.time()

        if not isinstance(resource_id, types.StringType):
            raise Inconsistent("The parameter resource_id is not a single resource id string")

        if not self.service_provider or not self._rr:
            raise Inconsistent("This class is not initialized properly")

        if extended_resource_type not in getextends(OT.ResourceContainer):
            raise BadRequest('The requested resource %s is not extended from %s' % (extended_resource_type, OT.ResourceContainer))

        if computed_resource_type and computed_resource_type not in getextends(OT.ComputedAttributes):
            raise BadRequest('The requested resource %s is not extended from %s' % (computed_resource_type, OT.ComputedAttributes))

        resource_object = self._rr.read(resource_id)

        if not resource_object:
            raise NotFound("The Resource %s does not exist" % resource_id)

        res_container = IonObject(extended_resource_type)

        # @TODO - replace with object level decorators and raise exceptions
        if not hasattr(res_container, 'origin_resource_type'):
            log.error('The requested resource %s does not contain a properly set origin_resource_type field.' , extended_resource_type)
            #raise Inconsistent('The requested resource %s does not contain a properly set origin_resource_type field.' % extended_resource_type)

        if hasattr(res_container, 'origin_resource_type') and res_container.origin_resource_type != resource_object.type_\
        and not issubtype(resource_object.type_, res_container.origin_resource_type):
            log.error('The origin_resource_type of the requested resource %s(%s) does not match the type of the specified resource id(%s).' % (
                extended_resource_type, res_container.origin_resource_type, resource_object.type_))
            #raise Inconsistent('The origin_resource_type of the requested resource %s(%s) does not match the type of the specified resource id(%s).' % (extended_resource_type, res_container.origin_resource_type, resource_object.type_))

        res_container._id = resource_object._id
        res_container.resource = resource_object

        self.set_container_lcstate_info(res_container)

        self.set_container_field_values(res_container, ext_exclude)

        self.set_computed_attributes(res_container, computed_resource_type, ext_exclude)

        self.set_extended_associations(res_container, ext_associations, ext_exclude)

        res_container.ts_created = get_ion_ts()

        overall_stop_time = time.time()

        log.debug("Time to process extended resource container %s %f secs", extended_resource_type, overall_stop_time - overall_start_time )

        return res_container
开发者ID:daf,项目名称:pyon,代码行数:53,代码来源:resource.py


示例11: obtain_agent_calculation

    def obtain_agent_calculation(self, device_id, result_container):
        ret = IonObject(result_container)
        a_client = None
        try:
            a_client = self.obtain_agent_handle(device_id)
            ret.status = ComputedValueAvailability.PROVIDED
        except NotFound:
            ret.status = ComputedValueAvailability.NOTAVAILABLE
            ret.reason = "Could not connect to instrument agent instance -- may not be running"
        except Exception as e:
            raise e

        return a_client, ret
开发者ID:jamie-cyber1,项目名称:coi-services,代码行数:13,代码来源:status_builder.py


示例12: _execute

    def _execute(self, cprefix, command):
        if not command:
            raise iex.BadRequest("execute argument 'command' not present")
        if not command.command:
            raise iex.BadRequest("command not set")

        cmd_res = IonObject("AgentCommandResult", command_id=command.command_id, command=command.command)
        cmd_func = getattr(self, cprefix + str(command.command), None)
        if cmd_func:
            cmd_res.ts_execute = get_ion_ts()
            try:
                res = cmd_func(*command.args, **command.kwargs)
                cmd_res.status = 0
                cmd_res.result = res
            except iex.IonException as ex:
                # TODO: Distinguish application vs. uncaught exception
                cmd_res.status = getattr(ex, 'status_code', -1)
                cmd_res.result = str(ex)
                log.warn("Agent command %s failed with trace=%s" % (command.command, traceback.format_exc()))
        else:
            log.info("Agent command not supported: %s" % (command.command))
            ex = iex.NotFound("Command not supported: %s" % command.command)
            cmd_res.status = iex.NotFound.status_code
            cmd_res.result = str(ex)

        sub_type = "%s.%s" % (command.command, cmd_res.status)
        post_event = self._event_publisher._create_event(event_type=self.COMMAND_EVENT_TYPE,
                                origin=self.resource_id, origin_type=self.ORIGIN_TYPE,
                                sub_type=sub_type, command=command, result=cmd_res)
        post_event = self._post_execute_event_hook(post_event)
        success = self._event_publisher._publish_event(post_event, origin=post_event.origin)

        return cmd_res
开发者ID:swarbhanu,项目名称:pyon,代码行数:33,代码来源:agent.py


示例13: _start_raw_ingestion

    def _start_raw_ingestion(self):
        dpsc_cli = DataProductManagementServiceClient()
        rrclient = ResourceRegistryServiceClient()
        RR2 = EnhancedResourceRegistryClient(rrclient)

        # Generic time-series data domain creation
        tdom, sdom = time_series_domain()

        dp_obj = IonObject(RT.DataProduct,
            name='DP1',
            description='some new dp',
            temporal_domain = tdom.dump(),
            spatial_domain = sdom.dump())

        dp_obj.geospatial_bounds.geospatial_latitude_limit_north = 10.0
        dp_obj.geospatial_bounds.geospatial_latitude_limit_south = -10.0
        dp_obj.geospatial_bounds.geospatial_longitude_limit_east = 10.0
        dp_obj.geospatial_bounds.geospatial_longitude_limit_west = -10.0
        dp_obj.ooi_product_name = "PRODNAME"

        #------------------------------------------------------------------------------------------------
        # Create a set of ParameterContext objects to define the parameters in the coverage, add each to the ParameterDictionary
        #------------------------------------------------------------------------------------------------

        log.info("Create data product... raw stream id: %s", self._raw_stream_id)
        dp_id = dpsc_cli.create_data_product_(data_product= dp_obj)
        dataset_id = self.create_dataset(self._raw_stream_pdict_id)
        RR2.assign_stream_definition_to_data_product_with_has_stream_definition(self._raw_stream_def_id, dp_id)
        RR2.assign_stream_to_data_product_with_has_stream(self._raw_stream_id, dp_id)
        RR2.assign_dataset_to_data_product_with_has_dataset(dataset_id, dp_id)
        self._raw_dataset_id = dataset_id

        log.info("Create data product...Complete")

        # Assert that the data product has an associated stream at this stage
        stream_ids, _ = rrclient.find_objects(dp_id, PRED.hasStream, RT.Stream, True)
        self.assertNotEquals(len(stream_ids), 0)

        # Assert that the data product has an associated stream def at this stage
        stream_ids, _ = rrclient.find_objects(dp_id, PRED.hasStreamDefinition, RT.StreamDefinition, True)
        self.assertNotEquals(len(stream_ids), 0)

        log.info("Activate data product persistence")
        dpsc_cli.activate_data_product_persistence(dp_id)

        log.info("Read data product")
        dp_obj = dpsc_cli.read_data_product(dp_id)
        self.assertIsNotNone(dp_obj)
        self.assertEquals(dp_obj.geospatial_point_center.lat, 0.0)
        log.debug('Created data product %s', dp_obj)
开发者ID:MatthewArrott,项目名称:coi-services,代码行数:50,代码来源:test_high_volume.py


示例14: _execute

    def _execute(self, cprefix, command):
        if not command:
            raise iex.BadRequest("execute argument 'command' not present")
        if not command.command:
            raise iex.BadRequest("command not set")

        cmd_res = IonObject("AgentCommandResult", command_id=command.command_id, command=command.command)
        cmd_func = getattr(self, cprefix + str(command.command), None)
        if cmd_func:
            cmd_res.ts_execute = get_ion_ts()
            try:
                res = cmd_func(*command.args, **command.kwargs)
                cmd_res.status = 0
                cmd_res.result = res
            except Exception as ex:
                # TODO: Distinguish application vs. uncaught exception
                cmd_res.status = getattr(ex, 'status_code', -1)
                cmd_res.result = str(ex)
                log.info("Agent function failed with ex=%s msg=%s" % (type(ex), str(ex)))
        else:
            log.info("Agent command not supported: %s" % (command.command))
            ex = iex.NotFound("Command not supported: %s" % command.command)
            cmd_res.status = iex.NotFound.status_code
            cmd_res.result = str(ex)
        return cmd_res
开发者ID:tgiguere,项目名称:pyon,代码行数:25,代码来源:agent.py


示例15: test_crud_list_obj

    def test_crud_list_obj(self):
        """ crud batch operations using lists of objects where possible """
        obj1 = IonObject(RT.InstrumentDevice, name='SBE37IMDevice', description="SBE37IMDevice", serial_number="12345" )
        obj2 = IonObject(RT.Observatory, name='mount spaghetti', description='covered with snow')
        objs = [obj1,obj2]
        tuples = self.repo.insert('sample', objs)

        for t in tuples:
            self.assertTrue(t[0])
            self.assertTrue(t[1] is not None)

        ids = [ tuples[0][1], tuples[1][1], 'howdy' ]
        tuples = self.repo.read('sample', ids)
        self.assertTrue(tuples[0][0])
        self.assertTrue(tuples[1][0])
        self.assertFalse(tuples[2][0])

        obj3 = tuples[0][2]
        obj4 = tuples[1][2]
        obj3.name = 'no longer SBE'
        obj4.description = 'no more snow'
        obj1._id = 'abc123'
        objs = [ obj3, obj4, obj1 ]
        tuples = self.repo.update('sample', objs)
        self.assertTrue(tuples[0][0])
        self.assertTrue(tuples[1][0])
        self.assertFalse(tuples[2][0])

        tuples = self.repo.read('sample', objs)
        self.assertTrue(tuples[0][0])
        self.assertTrue(tuples[1][0])
        self.assertFalse(tuples[2][0])
        obj5 = tuples[0][2]
        obj6 = tuples[1][2]
        for key in ['_id', 'name', 'description', 'serial_number']:
            self.assertEqual(obj3.__dict__[key],obj5.__dict__[key], msg='objects do not have the same '+key)

        objs = [ obj4, obj5 ]  # 4 has obsolete _rev
        tuples = self.repo.delete('sample', objs)
        self.assertFalse(tuples[0][0])
        self.assertTrue(tuples[1][0], msg='failed: '+str(tuples[1][2]) +'\nobj: ' + repr(obj5.__dict__))

        objs = [ obj5, obj6 ]  # 5 is already deleted
        tuples = self.repo.delete('sample', objs)
        self.assertFalse(tuples[0][0])
        self.assertTrue(tuples[1][0], msg='failed: '+str(tuples[1][2]) +'\nobj: ' + repr(obj5.__dict__))
开发者ID:daf,项目名称:pyon,代码行数:46,代码来源:test_repository_crud.py


示例16: create_negotiation

    def create_negotiation(self, sap=None):

        if sap is None or ( sap.type_ != OT.ServiceAgreementProposal and not issubtype(sap.type_, OT.ServiceAgreementProposal)):
            raise BadRequest('The sap parameter must be a valid Service Agreement Proposal object')

        if sap.proposal_status != ProposalStatusEnum.INITIAL or sap.sequence_num != 0:
            raise Inconsistent('The specified Service Agreement Proposal has inconsistent status fields')

        if sap.negotiation_id != '':
            raise Inconsistent('The specified Service Agreement Proposal cannot have a negotiation_id for an initial proposal')

        if self.negotiation_rules.has_key(sap.type_):
            #validate preconditions before creating
            for pc in self.negotiation_rules[sap.type_]['pre_conditions']:
                if pc.startswith('not '):
                    pre_condition_met = not eval("self.service_provider." + pc.lstrip('not ')) #Strip off the 'not ' part
                else:
                    pre_condition_met = eval("self.service_provider."+pc)

                if not pre_condition_met:
                    raise BadRequest("A precondition for this request has not been satisfied: %s" % pc)

        #Should be able to determine the negotiation type based on the intial originator
        neg_type = NegotiationTypeEnum.REQUEST
        if sap.originator == ProposalOriginatorEnum.PROVIDER:
            neg_type = NegotiationTypeEnum.INVITATION
        elif sap.originator == ProposalOriginatorEnum.BROKER:
            neg_type = NegotiationTypeEnum.BROKERED

        neg_obj = IonObject(RT.Negotiation, negotiation_type=neg_type)

        #If there is a description in the initial proposal, then set the negotiation description with it.
        if sap.description != '':
            neg_obj.description = sap.description

        neg_id,_ = self.service_provider.clients.resource_registry.create(neg_obj)

        #Create associations between the parties
        self.service_provider.clients.resource_registry.create_association(sap.consumer, PRED.hasNegotiation, neg_id)
        self.service_provider.clients.resource_registry.create_association(sap.provider, PRED.hasNegotiation, neg_id)
        if sap.broker != "":
            self.service_provider.clients.resource_registry.create_association(sap.broker, PRED.hasNegotiation, neg_id)


        return neg_id
开发者ID:ooici,项目名称:pyon,代码行数:45,代码来源:negotiation.py


示例17: has_resource_commitments

    def has_resource_commitments(self, actor_id, resource_id):

        ret_status = IonObject(OT.ResourceCommitmentStatus)
        commitments = self.get_resource_commitments(actor_id, resource_id)
        if commitments is None:
            #No commitments were found between this resource_id and actor_id
            return ret_status

        ret_status.shared = True

        for com in commitments:
            if com.commitment.exclusive == True:
                #Found an exclusive commitment
                ret_status.exclusive = True
                return ret_status

        #Only a shared commitment was found
        return ret_status
开发者ID:pkediyal,项目名称:pyon,代码行数:18,代码来源:governance_controller.py


示例18: test_expected_exceptions

    def test_expected_exceptions(self):
        """ test uses that are expected to throw exceptions (and probably need code fixes) """
        obj1 = IonObject(RT.InstrumentDevice, name='SBE37IMDevice', description="SBE37IMDevice", serial_number="12345")

        # invalid name for repository
        try:
            self.repo.insert('bad name', obj1)
            self.fail('should fail')
        except:
            pass

        # invalid argument types
        try:
            self.repo.insert('sample', None)
            self.fail('should fail')
        except:
            pass

        try:
            self.repo.insert('sample', "not ion obj")
            self.fail('should fail')
        except:
            pass

        # cannot reinsert with same id
        _,id,__ = self.repo.insert('sample', obj1)
        _,__,obj2 = self.repo.read('sample', id)
        try:
            success,_,__ = self.repo.insert('sample', obj2)
            self.fail('should not succeed')
        except:
            pass

        # cannot insert with _rev
        obj1._rev = obj2._rev
        try:
            success,_,__ = self.repo.insert('sample', obj1)
            self.fail('should not succeed')
        except:
            pass
开发者ID:daf,项目名称:pyon,代码行数:40,代码来源:test_repository_crud.py


示例19: test_create_negotiation

    def test_create_negotiation(self):

        self.preconditions.check_method1.return_value = True
        self.preconditions.check_method2.return_value = False
        self.accept_actions.accept_method.return_value = None

        negotiation_rules = {
            OT.EnrollmentProposal: {
                'pre_conditions': ['preconditions.check_method1(sap.consumer)', 'not preconditions.check_method2(sap.provider,sap.consumer)'],
                'accept_action': 'accept_actions.accept_method(sap.provider,sap.consumer)'
            }}

        negotiation_handler = Negotiation(self, negotiation_rules)

        with self.assertRaises(BadRequest) as cm:
            negotiation_handler.create_negotiation()
        self.assertIn('The sap parameter must be a valid Service Agreement Proposal object',cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal,consumer=self.actor_identity._id, provider=self.org._id )
        sap.sequence_num = 1  #Force an error
        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.create_negotiation(sap)
        self.assertIn('The specified Service Agreement Proposal has inconsistent status fields',cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal,consumer=self.actor_identity._id, provider=self.org._id )
        sap.proposal_status = ProposalStatusEnum.COUNTER  #Force an error
        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.create_negotiation(sap)
        self.assertIn('The specified Service Agreement Proposal has inconsistent status fields',cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal,consumer=self.actor_identity._id, provider=self.org._id )
        sap.negotiation_id = 'efefeff'  #Force an error
        with self.assertRaises(Inconsistent) as cm:
            negotiation_handler.create_negotiation(sap)
        self.assertIn('The specified Service Agreement Proposal cannot have a negotiation_id for an initial proposal',cm.exception.message)

        sap = IonObject(OT.EnrollmentProposal,consumer=self.actor_identity._id, provider=self.org._id )

        negotiation = Mock()
        negotiation._id = '456'
        negotiation.type_ = RT.Negotiation
        negotiation.proposals = []

        self.mock_read.return_value = negotiation
        self.mock_create.return_value = ['456', 2]

        neg_id = negotiation_handler.create_negotiation(sap)

        self.assertEqual(neg_id, negotiation._id)
        self.assertEqual(len(negotiation.proposals),0)

        self.assertEqual(self.preconditions.check_method1.called,True)
        self.assertEqual(self.preconditions.check_method2.called,True)
        self.assertEqual(self.accept_actions.accept_method.called,False)
开发者ID:ateranishi,项目名称:pyon,代码行数:54,代码来源:test_negotiation.py


示例20: create_prepare_resource_support

    def create_prepare_resource_support(self, resource_id="", prepare_resource_type=None, origin_resource_type=None):

        if not isinstance(resource_id, types.StringType):
            raise Inconsistent("The parameter resource_id is not a single resource id string")

        if not self.service_provider or not self._rr:
            raise Inconsistent("This class is not initialized properly")

        if prepare_resource_type is not None and prepare_resource_type not in getextends(OT.ResourcePrepareSupport):
            raise BadRequest('The requested resource %s is not extended from %s' % (prepare_resource_type, OT.ResourcePrepareSupport))


        resource_data = IonObject(prepare_resource_type)

        # Check to make sure the extended resource decorator raise OriginResourceType matches the type of the resource type
        origin_resource_decorator =  resource_data.get_class_decorator_value('OriginResourceType')
        if origin_resource_decorator is None and origin_resource_type is None:
            raise NotFound('OriginResourceType decorator not found in object specification %s', prepare_resource_type)

        origin_resource_type = origin_resource_type if origin_resource_type is not None else origin_resource_decorator
        if origin_resource_type is None:
            raise NotFound('OriginResourceType decorator not found in object specification %s', prepare_resource_type)


        resource_object = None
        if resource_id:
            resource_object = self._rr.read(resource_id)

            if origin_resource_type != resource_object.type_ and not issubtype(resource_object.type_, origin_resource_type):
                raise Inconsistent('The OriginResourceType decorator of the requested resource %s(%s) does not match the type of the specified resource id(%s).' % (
                    prepare_resource_type, origin_resource_type, resource_object.type_))

            resource_data._id = resource_object._id
        else:
            resource_object = IonObject(origin_resource_type)

        resource_data.resource = resource_object
        resource_data.resource_schema = get_object_schema(origin_resource_type)

        for field in resource_data._schema:

            deco_value = resource_data.get_decorator_value(field, 'AssociatedResources')
            assoc_dict = {}
            if deco_value is not None:
                if deco_value.find(',') == -1:
                    associated_resources = [deco_value]
                else:
                    associated_resources = deco_value.split(',')

                for res in associated_resources:
                    assoc = self.get_associated_resource_info(origin_resource_type, resource_id, res)
                    assoc_dict[assoc.key] = assoc

                setattr(resource_data, field, assoc_dict)
                continue


        return resource_data
开发者ID:mkl-,项目名称:scioncc,代码行数:58,代码来源:resource.py



注:本文中的pyon.core.bootstrap.IonObject类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python object.IonObjectDeserializer类代码示例发布时间:2022-05-27
下一篇:
Python bootstrap.CFG类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap