def action(self, request):
        path_match = False

        for rule in self.__rules:
            matched = re.search(rule[self.PATTERN], request.path)
            if not matched:
                continue

            path_match = True
            if request.method != rule[self.METHOD]:
                continue

            if rule[self.PARAMS] == 0:
                return rule[self.FUNC]()
            elif rule[self.PARAMS] == 1:
                if request.body is None:
                    return rule[self.FUNC](*matched.groups())
                else:
                    return rule[self.FUNC](request.body)
            else:
                if request.body is None:
                    return rule[self.FUNC](*matched.groups())
                else:
                    return rule[self.FUNC](request.body, *matched.groups())

        if path_match:
            return Response(Response.StatusCode.METHOD_NOT_ALLOWED, None)

        return Response(Response.StatusCode.NOT_FOUND, None)
    def test__del_object_to_remote_object_StatusCode_NotOK(self):
        Path = RemoteObjectInterface.PROPETY_PATH
        method = Request.Method.DELETE
        _object_id = self.object_id
        status_code = Response.StatusCode.NOT_FOUND
        debug_log = "Error Response DELETE DestID:" + _object_id\
                    + " Path:" + Path\
                    + " StatusCode:" + str(status_code)
        value = "propertyBody"

        with nested(
                patch(
                    'org.o3project.odenos.core.util.remote_object_interface.'
                    'RemoteObjectInterface.'
                    '_RemoteObjectInterface__send_request',
                    return_value=Response(status_code, value)),
                patch('logging.debug')) as (m_send_request, m_log_debug):

            self.result = self.target._del_object_to_remote_object(Path, value)
            self.assertEqual(m_send_request.call_count, 1)
            m_send_request.assert_any_call(_object_id,
                                           method,
                                           Path,
                                           body=value)
            self.assertEqual(m_log_debug.call_count, 1)
            m_log_debug.assert_any_call(debug_log)
            self.assertNotEqual(self.result, None)
Beispiel #3
0
    def test_get_connection_arg_ComponentConnectio_success(self):
        ComponentConnectioTmp = ComponentConnection("slicer1network",
                                                    "original",
                                                    "running")
        body = ComponentConnectioTmp.packed_object()
        with nested(
                patch('org.o3project.odenos.core.util.remote_object_interface.'
                      'RemoteObjectInterface._get_object_to_remote_object',
                      return_value=Response(Response.StatusCode.OK,
                                            body)),
                patch('org.o3project.odenos.remoteobject.manager.system.'
                      'component_connection.ComponentConnection.'
                      'create_from_packed',
                      return_value=ComponentConnection.create_from_packed(
                          body)),
                patch('org.o3project.odenos.remoteobject.manager.system.'
                      'component_connection_logic_and_network.'
                      'ComponentConnectionLogicAndNetwork.create_from_packed'),
                patch('logging.error'
                      )) as (m_get_object,
                             m_Connection,
                             m_LogicAndNetwork,
                             m_log_error):

                self.result = self.target.get_connection("slicer1network")
                self.assertEqual(m_get_object.call_count, 1)
                m_get_object.assert_any_call(SystemManagerInterface.
                                             CONNECTION_PATH %
                                             "slicer1network")
                self.assertEqual(m_Connection.call_count, 1)
                m_Connection.assert_any_call(body)
                self.assertEqual(m_LogicAndNetwork.call_count, 0)
                self.assertNotEqual(self.result, None)
                self.assertEqual(self.result.packed_object(), body)
                self.assertEqual(m_log_error.call_count, 0)
    def _do_get_component_types(self):
        comp_types = {}
        tmp = None
        try:
            for type_name, clazz in self.remote_object_classes.items():
                comp_id = "%s_%s" % (self.object_id, type_name)
                component = clazz(comp_id, None)
                obj_prop = component.object_property
                component = None

                type = obj_prop.get_property(ObjectProperty.OBJECT_TYPE)
                super_type = obj_prop.get_property(
                    ObjectProperty.OBJECT_SUPER_TYPE)

                connection_types = {}
                connection_types_str = obj_prop.get_property(
                    ObjectProperty.CONNECTION_TYPES)
                conn_type_list = connection_types_str.split(",")
                for type_elem in conn_type_list:
                    type_elem_list = type_elem.split(":")
                    if len(type_elem_list) == 2:
                        connection_types[type_elem_list[0]] = type_elem_list[1]

                description = obj_prop.get_property(ObjectProperty.DESCRIPTION)

                target = ComponentType(type, super_type, connection_types,
                                       description)
                comp_types[type_name] = target.packed_object()

        except Exception, e:
            return Response(Response.StatusCode.INTERNAL_SERVER_ERROR, str(e))
Beispiel #5
0
 def test_get_connection_arg_is_error_NG(self):
     with nested(
             patch('org.o3project.odenos.core.util.remote_object_interface.'
                   'RemoteObjectInterface._get_object_to_remote_object',
                   return_value=Response(Response.StatusCode.NOT_FOUND,
                                         None)),
             patch('org.o3project.odenos.remoteobject.manager.system.'
                   'component_connection.ComponentConnection.'
                   'create_from_packed'),
             patch('org.o3project.odenos.remoteobject.manager.system.'
                   'component_connection_logic_and_network.'
                   'ComponentConnectionLogicAndNetwork.create_from_packed'),
             patch('logging.error'
                   )) as (m_get_object,
                          m_Connection,
                          m_LogicAndNetwork,
                          m_log_error):
             self.result = self.target.get_connection("slicer1network")
             self.assertEqual(m_get_object.call_count, 1)
             m_get_object.assert_any_call(SystemManagerInterface.
                                          CONNECTION_PATH %
                                          "slicer1network")
             self.assertEqual(m_Connection.call_count, 0)
             self.assertEqual(m_LogicAndNetwork.call_count, 0)
             self.assertEqual(self.result, None)
             self.assertEqual(m_log_error.call_count, 0)
    def test_register_to_system_manager_success(self):
        self.target._request = MagicMock()
        self.target._ComponentManager__register_component_managers =\
            MagicMock()
        register_component_managers =\
            self.target._ComponentManager__register_component_managers
        self.target._ComponentManager__register_event_manager =\
            MagicMock()
        register_event_manager =\
            self.target._ComponentManager__register_event_manager
        self.target._ComponentManager__subscribe_event =\
            MagicMock()
        subscribe_event =\
            self.target._ComponentManager__subscribe_event
        self.value = {
            "id": "123456",
            "super_type": "Network",
            "type": "Network",
            "base_uri": "http://example.com:123456",
            "state": "running",
            "description": "NetworkComponent"
        }
        self.target._request.return_value = Response(Response.StatusCode.OK,
                                                     self.value)

        with patch('logging.debug') as m_logging_debug:
            self.target.register_to_system_manager()
            self.assertEqual(m_logging_debug.call_count, 1)
            self.assertEqual(register_component_managers.call_count, 1)
            self.assertEqual(register_event_manager.call_count, 1)
            self.assertEqual(subscribe_event.call_count, 1)

            self.target._ComponentManager__register_component_managers.close()
            self.target._ComponentManager__register_event_manager.close()
            self.target._ComponentManager__subscribe_event.close()
 def send_request_message(self, request):
     # for deep copy of Request object
     obj = msgpack.unpackb(msgpack.packb(request.packed_object()))
     rcv_request = Request.create_from_packed(obj)
     response = self.dispatcher.dispatch_request(rcv_request)
     # for deep copy of Response object
     obj = msgpack.unpackb(msgpack.packb(response.packed_object()))
     return Response.create_from_packed(obj)
Beispiel #8
0
    def test_Future_set(self):
        self.target = self.target.Future()
        response = Response(200, "body")

        self.target.set(response)

        self.assertEqual(self.target._Future__response, response)
        self.assertEqual(self.target._Future__response_obtained, True)
Beispiel #9
0
    def _request(self, object_id, method, path, body=None):
        resp = Response(Response.StatusCode.INTERNAL_SERVER_ERROR, None)
        try:
            resp = self._request_sync(object_id, method, path, body)
        except:
            logging.error("Exception: Request to " + object_id + " Method:" +
                          method + " Path:" + path)
            logging.error(traceback.format_exc())

        return resp
    def _do_delete_remote_object(self, object_id):
        if object_id in self.remote_objects:
            remote_object = self.remote_objects[object_id]
            prev = copy.deepcopy(
                remote_object._object_property).packed_object()
            remote_object.on_finalize()
            del self.remote_objects[object_id]
            logging.debug("Deleted RemoteObject ID:%s", object_id)

        return Response(Response.StatusCode.OK, None)
    def test_do_event_componentmanagerchanged_keyerror(self):
        self.value = {
            "type": "ComponentManager",
            "id": "456",
            "base_uri": "789"
        }
        self.result = Response("add", self.value)

        with patch('logging.error') as m_logging_error:
            self.target._do_event_componentmanagerchanged(self.result)
            self.assertEqual(m_logging_error.call_count, 1)
Beispiel #12
0
    def _do_delete_component(self, object_id):
        if object_id in self.components:
            component = self.components[object_id]
            prev = copy.deepcopy(component._object_property).packed_object()
            component.on_finalize()
            del self.components[object_id]
            self._do_component_changed(ComponentChanged.Action.DELETE, prev,
                                       None)
            logging.info("Deleted Component ID:%s", object_id)

        return Response(Response.StatusCode.OK, None)
    def del_flow(self, flow_id):
        logging.debug("DELETE Flow NetworkID:" + self.network_id + " FlowID:" +
                      flow_id)

        flow = self.get_flow(flow_id)
        if flow is None:
            return Response(Response.StatusCode.OK, None)

        flow.enabled = False
        path = self.FLOW_PATH % flow_id
        return self._del_object_to_remote_object(path, body=flow)
    def test_send_request_message(self):
        request = Request("object_id", "method", "path")
        response = Response(200, "body")

        self.target.dispatcher.dispatch_request =\
            MagicMock(return_value=response)

        result = self.target.send_request_message(request)

        self.assertEqual(result.status_code, 200)
        self.assertEqual(result.body, "body")
Beispiel #15
0
 def test_get_component_managers_error(self):
     with patch('org.o3project.odenos.core.util.remote_object_interface.'
                'RemoteObjectInterface._get_object_to_remote_object',
                return_value=Response(Response.StatusCode.NOT_FOUND,
                                      None)
                ) as m_get_object:
         self.result = self.target.get_component_managers()
         self.assertEqual(m_get_object.call_count, 1)
         m_get_object.assert_any_call(SystemManagerInterface.
                                      COMP_MNGS_PATH)
         self.assertEqual(self.result, None)
Beispiel #16
0
    def dispatch_request(self, request):
        try:
            resp = self.__parser.action(request)
            if resp.status_code == Response.StatusCode.NOT_FOUND:
                resp = self._on_request(request)
        except:
            logging.error("Exception: Receive Request" + " Method:" +
                          request.method + " Path:" + request.path)
            logging.error(traceback.format_exc())
            resp = Response(Response.StatusCode.INTERNAL_SERVER_ERROR, None)

        return resp
Beispiel #17
0
    def test_get_connections_success(self):
        ComponentConnectioTmp = ComponentConnection("slicer1_network1",
                                                    "original",
                                                    "running")
        LogicAndNetworkTmp =\
            ComponentConnectionLogicAndNetwork("slicer1_network2",
                                               "original",
                                               "running",
                                               "LogicId",
                                               "NetworkId")
        ComponentConnectioTmp_packed_object =\
            ComponentConnectioTmp.packed_object()
        LogicAndNetworkTmp_packed_object =\
            LogicAndNetworkTmp.packed_object()
        body = {"slicer1network": ComponentConnectioTmp_packed_object,
                "slicer2network": LogicAndNetworkTmp_packed_object}
        with nested(
                patch('org.o3project.odenos.core.util.remote_object_interface.'
                      'RemoteObjectInterface._get_object_to_remote_object',
                      return_value=Response(Response.StatusCode.OK, body)),
                patch('org.o3project.odenos.remoteobject.manager.system.'
                      'component_connection.ComponentConnection.'
                      'create_from_packed',
                      return_value=ComponentConnection.create_from_packed(
                          ComponentConnectioTmp_packed_object)),
                patch('org.o3project.odenos.remoteobject.manager.system.'
                      'component_connection_logic_and_network.'
                      'ComponentConnectionLogicAndNetwork.create_from_packed',
                      return_value=ComponentConnectionLogicAndNetwork.
                      create_from_packed(LogicAndNetworkTmp_packed_object)),
                patch('logging.error'
                      )) as (m_get_object,
                             m_Connection,
                             m_LogicAndNetwork,
                             m_log_error):

                self.result = self.target.get_connections()
                self.assertEqual(m_get_object.call_count, 1)
                m_get_object.assert_any_call(SystemManagerInterface.
                                             CONNECTIONS_PATH)
                self.assertEqual(m_Connection.call_count, 1)
                m_Connection.assert_any_call(
                    ComponentConnectioTmp_packed_object)
                self.assertEqual(m_LogicAndNetwork.call_count, 1)
                m_LogicAndNetwork.assert_any_call(
                    LogicAndNetworkTmp_packed_object)
                self.assertNotEqual(self.result, None)
                self.assertEqual(len(self.result), 2)
                self.assertEqual(self.result["slicer1network"].packed_object(),
                                 ComponentConnectioTmp_packed_object)
                self.assertEqual(self.result["slicer2network"].packed_object(),
                                 LogicAndNetworkTmp_packed_object)
                self.assertEqual(m_log_error.call_count, 0)
Beispiel #18
0
 def test_get_component_type_arg_comp_type_error(self):
     value = "ComponentTypeBody"
     with patch('org.o3project.odenos.core.util.remote_object_interface.'
                'RemoteObjectInterface._get_object_to_remote_object',
                return_value=Response(Response.StatusCode.NOT_FOUND,
                                      value)
                ) as m_get_object:
         self.result = self.target.get_component_type("CompTypeId1")
         self.assertEqual(m_get_object.call_count, 1)
         m_get_object.assert_any_call(SystemManagerInterface.
                                      COMP_TYPE_PATH % "CompTypeId1")
         self.assertEqual(self.result, None)
Beispiel #19
0
    def test_add_component_managers_success(self):
        value = ComponentManager("cmp_id", self.Dispatcher)

        with nested(patch('org.o3project.odenos.core.util.remote_object_interface.'
                   'RemoteObjectInterface._put_object_to_remote_object', \
                   return_value=Response(Response.StatusCode.OK, value.object_property)
                   ), patch("logging.error")) as (m_put_object, logging_error):
            self.result = self.target.add_component_manager(value)
            self.assertEqual(m_put_object.call_count, 1)
            m_put_object.assert_any_call(SystemManagerInterface.
                                         COMP_MNG_PATH % value.object_id,
                                          value.object_property)
Beispiel #20
0
 def test_get_event_manager_success(self):
     value = "EventManager_Body"
     with patch('org.o3project.odenos.core.util.remote_object_interface.'
                'RemoteObjectInterface._get_object_to_remote_object',
                return_value=Response(Response.StatusCode.OK, value)
                ) as m_get_object:
         self.result = self.target.get_event_manager()
         self.assertEqual(m_get_object.call_count, 1)
         m_get_object.assert_any_call(SystemManagerInterface.
                                      EVENT_MNG_PATH)
         self.assertNotEqual(self.result, None)
         self.assertEqual(self.result, value)
    def test_redisSubscriberRunnable_TYPE_RESPONSE(self):
        clients = self.target._MessageDispatcher__clients
        remote_msg_trans = RemoteMessageTransport("publisher_id:event_type",
                                                  self.target)
        clients["publisher_id:event_type"] = remote_msg_trans

        response = Response(200, "remote_msg_trans")

        pk = msgpack.Packer()
        resb = bytearray()
        resb.extend(pk.pack(1))
        resb.extend(pk.pack(0))
        resb.extend(pk.pack("publisher_id:event_type"))
        resb.extend(pk.pack(response.packed_object()))
        self.value = {"type": "message",
                      "data": resb}

        self.target._MessageDispatcher__redisSubscriber = redis.StrictRedis(
            host=self.target._MessageDispatcher__redisServer,
            port=self.target._MessageDispatcher__redisPort)
        self.target._MessageDispatcher__redisSubscriber =\
            self.target._MessageDispatcher__redisSubscriber.pubsub()

        with nested(
            patch("redis.client.PubSub.subscribe"),
                patch("redis.client.PubSub.unsubscribe"),
                patch("redis.client.PubSub.listen"),
                patch(self.RESPONSE_PATH + ".create_from_packed")) as (
                mock_subscribe,
                mock_unsubscribe,
                mock_listen,
                mock_response):
            mock_subscribe.return_value = None
            mock_unsubscribe.return_value = None
            mock_listen.return_value = [self.value]

            self.target._MessageDispatcher__redisSubscriberRunnable()

            mock_response.assert_called_once_with(
                [200, "remote_msg_trans"])
    def delete_all_flow(self):
        logging.debug("DELETE AllFlow NetworkID:" + self.network_id)
        resp_list = []

        flow_set = self.get_flow_set()
        if flow_set is None:
            resp_list.append(Response(Response.StatusCode.OK, None))
            return resp_list

        for flow_id in flow_set.flows:
            resp_list.append(self.del_flow(flow_id))

        return resp_list
Beispiel #23
0
 def test_get_component_arg_comp_id_success(self):
     value = "ComponentBody"
     with patch('org.o3project.odenos.core.util.remote_object_interface.'
                'RemoteObjectInterface._get_object_to_remote_object',
                return_value=Response(Response.StatusCode.OK,
                                      value)
                ) as m_get_object:
         self.result = self.target.get_component("CompId1")
         self.assertEqual(m_get_object.call_count, 1)
         m_get_object.assert_any_call(SystemManagerInterface.
                                      COMP_PATH % "CompId1")
         self.assertNotEqual(self.result, None)
         self.assertEqual(self.result, value)
Beispiel #24
0
    def _do_put_property(self, body):
        logging.debug("Receive PUT Property ObjectID:" + self.object_id)
        # check State Change to Finalizing
        for k, v in body.items():
            if k == ObjectProperty.OBJECT_STATE:
                oldValue = self._object_property.get_property(k)
                self.on_state_changed(oldValue, v)

        # update Property
        if not (self._object_property.equals(body)):
            self._object_property.put_property(body)

        return Response(Response.StatusCode.OK, self._object_property)
    def test_get_property_success(self):
        value = "propertyBody"
        with patch(
                'org.o3project.odenos.core.util.remote_object_interface.'
                'RemoteObjectInterface._get_object_to_remote_object',
                return_value=Response(Response.StatusCode.OK,
                                      value)) as m_get_object:

            self.result = self.target.get_property()

            self.assertEqual(m_get_object.call_count, 1)
            self.assertEqual(m_get_object.call_args[0][0],
                             RemoteObjectInterface.PROPETY_PATH)
            self.assertNotEqual(self.result, None)
 def __redisPublisherRunnable(self):
     while (True):
         pubs = self.__pubsqueue.get()
         if pubs is None:
             break
         try:
             self.__redisPubliser.publish(pubs.channel, pubs.data)
         except:
             if pubs.type == self.TYPE_REQUEST:
                 if pubs.trans is not None:
                     pubs.trans.signalResponse(
                         pubs.sno,
                         Response(Response.StatusCode.NOT_FOUND, None))
             pass
    def test_get_settings_StatusCode_NotOK(self):
        value = "settingsBody"
        with patch(
                'org.o3project.odenos.core.util.remote_object_interface.'
                'RemoteObjectInterface._get_object_to_remote_object',
                return_value=Response(Response.StatusCode.NOT_FOUND,
                                      value)) as m_get_object:

            self.result = self.target.get_settings()

            self.assertEqual(m_get_object.call_count, 1)
            self.assertEqual(m_get_object.call_args[0][0],
                             RemoteObjectInterface.SETTINGS_PATH)
            self.assertEqual(self.result, None)
    def _do_put_remote_object(self, obj_prop, object_id):
        remote_object_type = obj_prop[ObjectProperty.OBJECT_TYPE]

        if remote_object_type not in self.remote_object_classes:
            return Response(Response.StatusCode.BAD_REQUEST, None)
        elif object_id in self.remote_objects:
            return Response(Response.StatusCode.CONFLICT, None)

        remote_object_class = self.remote_object_classes[remote_object_type]
        self.remote_objects[object_id] = remote_object_class(
            object_id, self.dispatcher)

        if self.remote_objects[object_id].on_initialize(obj_prop):
            self.remote_objects[object_id].set_state(
                ObjectProperty.State.RUNNING)
        else:
            self.remote_objects[object_id].set_state(
                ObjectProperty.State.ERROR)

        logging.debug("Created RemoteObject Type:%s ID:%s", remote_object_type,
                      object_id)
        return Response(Response.StatusCode.CREATED,
                        self.remote_objects[object_id].object_property)
    def test_redisSubscriberRunnable_TYPE_RESPONSE(self):
        clients = self.target._MessageDispatcher__clients
        remote_msg_trans = RemoteMessageTransport("publisher_id:event_type",
                                                  self.target)
        clients["publisher_id:event_type"] = remote_msg_trans

        response = Response(200, "remote_msg_trans")

        pk = msgpack.Packer()
        resb = bytearray()
        resb.extend(pk.pack(1))
        resb.extend(pk.pack(0))
        resb.extend(pk.pack("publisher_id:event_type"))
        resb.extend(pk.pack(response.packed_object()))
        self.value = {"type": "message", "data": resb}

        self.target._MessageDispatcher__redisSubscriber = redis.StrictRedis(
            host=self.target._MessageDispatcher__redisServer,
            port=self.target._MessageDispatcher__redisPort)
        self.target._MessageDispatcher__redisSubscriber =\
            self.target._MessageDispatcher__redisSubscriber.pubsub()

        with nested(patch("redis.client.PubSub.subscribe"),
                    patch("redis.client.PubSub.unsubscribe"),
                    patch("redis.client.PubSub.listen"),
                    patch(self.RESPONSE_PATH +
                          ".create_from_packed")) as (mock_subscribe,
                                                      mock_unsubscribe,
                                                      mock_listen,
                                                      mock_response):
            mock_subscribe.return_value = None
            mock_unsubscribe.return_value = None
            mock_listen.return_value = [self.value]

            self.target._MessageDispatcher__redisSubscriberRunnable()

            mock_response.assert_called_once_with([200, "remote_msg_trans"])
Beispiel #30
0
    def _do_put_component(self, obj_prop, object_id):
        component_type = obj_prop[ObjectProperty.OBJECT_TYPE]

        if component_type not in self.component_classes:
            return Response(Response.StatusCode.BAD_REQUEST, None)
        elif object_id in self.components:
            return Response(Response.StatusCode.CONFLICT, None)

        component_class = self.component_classes[component_type]
        self.components[object_id] = component_class(object_id,
                                                     self.dispatcher)
        if self.components[object_id].on_initialize(obj_prop):
            self.components[object_id].\
                _object_property.set_state(ObjectProperty.State.RUNNING)
        else:
            self.components[object_id].\
                _object_property.set_state(ObjectProperty.State.ERROR)
        curr = self.components[object_id].object_property.packed_object()
        self._do_component_changed(ComponentChanged.Action.ADD, None, curr)

        logging.info("Created Component Type:%s ID:%s", component_type,
                     object_id)
        return Response(Response.StatusCode.CREATED,
                        self.components[object_id].object_property)
    def delete_topology(self):
        logging.debug("DELETE Topology NetworkID:" + self.network_id)
        resp_list = []

        topology = self.get_topology()
        if topology is None:
            resp_list.append(Response(Response.StatusCode.OK, None))
            return resp_list

        for link_id in topology.links:
            # delete Link
            resp_list.append(self.del_link(link_id))

        for node_id, node in topology.nodes.items():
            for port_id in node.ports:
                # delete port
                resp_list.append(self.del_port(node_id, port_id))
            # delete node
            resp_list.append(self.del_node(node_id))

        if len(resp_list) == 0:
            resp_list.append(Response(Response.StatusCode.OK, None))

        return resp_list
    def __redisSubscriberRunnable(self):
        for mesg in self.__redisSubscriber.listen():
            if mesg['type'] != 'message':
                continue
            try:
                bio = BytesIO()
                bio.write(mesg['data'])
                bio.seek(0)
                upk = msgpack.Unpacker(bio)
                tp = upk.unpack()
                sno = upk.unpack()
                srcid = upk.unpack()
                if tp == self.TYPE_REQUEST:
                    request = Request.create_from_packed(upk.unpack())

                    def request_runnable(request, sno, srcid):
                        response = self.dispatch_request(request)
                        pk = msgpack.Packer()
                        resb = bytearray()
                        resb.extend(pk.pack(self.TYPE_RESPONSE))
                        resb.extend(pk.pack(sno))
                        resb.extend(pk.pack(request.object_id))
                        resb.extend(pk.pack(response.packed_object()))
                        self.__pubsqueue.put(
                            MessageDispatcher.PublishData(None,
                                                          self.TYPE_RESPONSE,
                                                          sno,
                                                          srcid,
                                                          resb))
                    self.thread_pool.submit(request_runnable,
                                            request,
                                            sno,
                                            srcid)
                elif tp == self.TYPE_RESPONSE:
                    trans = self.__clients[srcid]
                    response = Response.create_from_packed(upk.unpack())
                    trans.signalResponse(sno, response)
                elif tp == self.TYPE_EVENT:
                    event = Event.create_from_packed(upk.unpack())

                    def event_runnable(event):
                        self.dispatch_event(event)
                    self.thread_pool.submit(event_runnable, event)
            except:
                logging.error(traceback.format_exc())
                pass
    def test_do_event_componentmanagerchanged_delete_action(self):
        self.value = ComponentManager("456", self.MessageDispatcher)
        self.target.register_component_type(self.value.__class__)
        self.value = {
            "type": "ComponentManager",
            "id": "456",
            "base_uri": "789"
        }
        self.result = self.target._do_put_component(self.value, "456")
        prev = self.target.components["456"].object_property.packed_object()

        self.target.dispatcher.remove_remote_client = Mock()
        self.value = {"action": "delete", "prev": prev, "curr": None}
        self.result = Response("add", self.value)
        self.target._do_event_componentmanagerchanged(self.result)
        self.assertEqual(
            self.target.dispatcher.remove_remote_client.call_count, 1)
Beispiel #34
0
class ResponseTest(unittest.TestCase):

    Type = "BasicFlow"
    Version = "v01"
    Flow_id = "Id01"
    Owner = "Owner"
    Enabled = True
    Priority = "65535"
    Status = "none"
    Attributes = {"bandwidth": "10Mbps", "req_bandwidth": "11Mbps",
                  "latency": "10msec", "req_latency": "11msec"}
    Publisher_id = 'Id1'
    Event_type = 'flow'
    value = {"type": Type, "version": Version,
             "flow_id": Flow_id, "owner": Owner,
             "enabled": Enabled, "priority": Priority,
             "status": Status, "attributes": Attributes}
    Packed = [Response.StatusCode.OK, value]

    flow_target = Flow(Type, Version, Flow_id, Owner,
                       Enabled, Priority, Status,
                       Attributes)

    flow_target_packed_object = flow_target.packed_object()

    def setUp(self):
        self.target = Response(Response.StatusCode.OK, self.flow_target)

    def tearDown(self):
        self.target = None

    def test_constructor_hasattr_True(self):
        self.assertEqual(self.target.status_code,
                         Response.StatusCode.OK)
        self.assertEqual(self.target.body,
                         self.value)

    def test_constructor_hasattr_Falseself(self):
        self.target2 = Response(Response.StatusCode.CREATED,
                                self.value)
        self.assertEqual(self.target2.status_code,
                         Response.StatusCode.CREATED)
        self.assertEqual(self.target2.body,
                         self.value)

    def test_is_error_method_GET_status_code_OK(self):
        self.result = Response(Response.StatusCode.OK, self.flow_target)
        self.assertEqual(self.result.is_error("GET"),
                         False)

    def test_is_error_method_GET_status_code_NotOK(self):
        self.result = Response(Response.StatusCode.CREATED,
                               self.flow_target)
        self.assertEqual(self.result.is_error("GET"),
                         True)

    def test_is_error_method_DELETE_status_code_OK(self):
        self.result = Response(Response.StatusCode.OK, self.flow_target)
        self.assertEqual(self.result.is_error("DELETE"),
                         False)

    def test_is_error_method_DELETE_status_code_NotOK(self):
        self.result = Response(Response.StatusCode.CREATED,
                               self.flow_target)
        self.assertEqual(self.result.is_error("DELETE"),
                         True)

    def test_is_error_method_PUT_status_code_OK(self):
        self.result = Response(Response.StatusCode.OK, self.flow_target)
        self.assertEqual(self.result.is_error("PUT"),
                         False)

    def test_is_error_method_PUT_status_code_CREATED(self):
        self.result = Response(Response.StatusCode.CREATED,
                               self.flow_target)
        self.assertEqual(self.result.is_error("PUT"),
                         False)

    def test_is_error_method_PUT_status_code_NotOKandCREATED(self):
        self.result = Response(Response.StatusCode.ACCEPTED,
                               self.flow_target)
        self.assertEqual(self.result.is_error("PUT"),
                         True)

    def test_is_error_method_other_status_code_OK(self):
        self.result = Response(Response.StatusCode.OK, self.flow_target)
        self.assertEqual(self.result.is_error("POST"),
                         False)

    def test_is_error_method_other_status_code_CREATED(self):
        self.result = Response(Response.StatusCode.CREATED,
                               self.flow_target)
        self.assertEqual(self.result.is_error("POST"),
                         False)

    def test_is_error_method_other_status_code_NotOKandCREATED(self):
        self.result = Response(Response.StatusCode.ACCEPTED,
                               self.flow_target)
        self.assertEqual(self.result.is_error("POST"),
                         True)

    def test_create_from_packed(self):
        self.result = self.target.create_from_packed(self.Packed)
        self.assertEqual(self.result.status_code,
                         Response.StatusCode.OK)
        self.assertEqual(self.result.body,
                         self.value)

    def test_packed_object(self):
        self.result = self.target.packed_object()
        self.assertEqual(self.result, (Response.StatusCode.OK,
                                       self.value))
        self.assertEqual(len(self.result), 2)
Beispiel #35
0
 def test_is_error_method_DELETE_status_code_OK(self):
     self.result = Response(Response.StatusCode.OK, self.flow_target)
     self.assertEqual(self.result.is_error("DELETE"),
                      False)
Beispiel #36
0
 def test_is_error_method_DELETE_status_code_NotOK(self):
     self.result = Response(Response.StatusCode.CREATED,
                            self.flow_target)
     self.assertEqual(self.result.is_error("DELETE"),
                      True)
Beispiel #37
0
 def test_is_error_method_PUT_status_code_CREATED(self):
     self.result = Response(Response.StatusCode.CREATED,
                            self.flow_target)
     self.assertEqual(self.result.is_error("PUT"),
                      False)
Beispiel #38
0
 def test_is_error_method_PUT_status_code_NotOKandCREATED(self):
     self.result = Response(Response.StatusCode.ACCEPTED,
                            self.flow_target)
     self.assertEqual(self.result.is_error("PUT"),
                      True)
Beispiel #39
0
 def setUp(self):
     self.target = Response(Response.StatusCode.OK, self.flow_target)
    def test_redisSubscriberRunnable_TYPE_REQUEST(self):
        request = Request("object_id", "method", "path", None)
        request_packed = request.packed_object()
        response = Response(200, "body")
        response_packed = response.packed_object()

        pk = msgpack.Packer()
        resb = bytearray()
        resb.extend(pk.pack(0))
        resb.extend(pk.pack(0))
        resb.extend(pk.pack("object_id"))
        resb.extend(pk.pack(request_packed))
        self.value = {"type": "message",
                      "data": resb}
        self.value02 = {"type": "ERROR",
                        "data": resb}

        resb_check = bytearray()
        resb_check.extend(pk.pack(1))
        resb_check.extend(pk.pack(0))
        resb_check.extend(pk.pack("object_id"))
        resb_check.extend(pk.pack(response_packed))

        self.target.thread_pool = futures.ThreadPoolExecutor(max_workers=8)
        self.target._MessageDispatcher__redisSubscriber = redis.StrictRedis(
            host=self.target._MessageDispatcher__redisServer,
            port=self.target._MessageDispatcher__redisPort)
        self.target._MessageDispatcher__redisSubscriber =\
            self.target._MessageDispatcher__redisSubscriber.pubsub()

        def dummy_request_runnable(arg, request, sno, srcid):
            arg(request, sno, srcid)

        with nested(
            patch("redis.client.PubSub.subscribe"),
                patch("redis.client.PubSub.unsubscribe"),
                patch("redis.client.PubSub.listen"),
                patch("concurrent.futures.ThreadPoolExecutor.submit"),
                patch(self.REQUEST_PATH + ".create_from_packed"),
                patch(self.DISPATCHER_PATH + ".dispatch_request")) as (
                mock_subscribe,
                mock_unsubscribe,
                mock_listen,
                mock_submit,
                mock_request,
                mock_dispatch_request):
            mock_subscribe.return_value = None
            mock_unsubscribe.return_value = None
            mock_listen.return_value = [self.value, self.value02]
            mock_request.return_value = request
            mock_dispatch_request.return_value = response
            mock_submit.side_effect = dummy_request_runnable

            self.target._MessageDispatcher__redisSubscriberRunnable()
            self.result = self.target._MessageDispatcher__pubsqueue.get()

            mock_request.assert_called_once_with(
                ["object_id", "method", "path", None])
            self.assertEqual(mock_submit.call_count, 1)

            self.assertEqual(
                self.result.trans, None)
            self.assertEqual(
                self.result.type, 1)
            self.assertEqual(
                self.result.sno, 0)
            self.assertEqual(
                self.result.channel, "object_id")
            self.assertEqual(
                self.result.data, resb_check)