예제 #1
0
    def _create_jsonrpc_params(self, method: RestMethod, params: Optional[NamedTuple]):
        # 'vars(namedtuple)' does not working in Python 3.7.4
        # noinspection PyProtectedMember
        params = params._asdict() if params else None
        if params:
            params = { k: v for k, v in params.items() if v is not None}
            if "from_" in params:
                params["from"] = params.pop("from_")

        return Request(method.value.name, params) if params else Request(method.value.name)
예제 #2
0
def rpc_call(method_name, **kwargs):
    bind_address = Config.getParam('pacing', 'bindaddrclient')
    request_timeout = int(Config.getParam('pacing', 'requesttimeout'))
    context = zmq.Context(1)
    client = context.socket(zmq.REQ)
    logger.debug('bind adress is %s' % bind_address)
    client.connect(bind_address)

    poll = zmq.Poller()
    poll.register(client, zmq.POLLIN)

    request = Request(method_name, **kwargs)
    client.send_json(request)

    socks = dict(poll.poll(request_timeout))
    try:
        if socks.get(client) == zmq.POLLIN:
            reply = client.recv_json()
            logger.debug('reply from client {0}'.format(reply))
            return reply['result']

        else:
            return False
            #print("E: No response from server, closing...")
    finally:
        client.setsockopt(zmq.LINGER, 0)
        client.close()
        poll.unregister(client)
        context.term()
예제 #3
0
 def test_send_message_with_success_200():
     s = HTTPServer('http://test/')
     responses.add(responses.POST,
                   'http://test/',
                   status=200,
                   body='{"jsonrpc": "2.0", "result": 5, "id": 1}')
     s._send_message(Request('go'))
예제 #4
0
 def test_ssl_verification(self):
     s = HTTPServer('https://test/')
     s.session.cert = '/path/to/cert'
     s.session.verify = 'ca-cert'
     req = Request('go')
     with self.assertRaises(requests.exceptions.RequestException):
         s._send_message(req)
 def test_send_message_conn_error(self):
     client = ZMQClient('tcp://localhost:5555')
     # Set timeouts
     client.socket.setsockopt(zmq.RCVTIMEO, 5)
     client.socket.setsockopt(zmq.SNDTIMEO, 5)
     client.socket.setsockopt(zmq.LINGER, 5)
     with self.assertRaises(zmq.error.ZMQError):
         client._send_message(str(Request('go')))
예제 #6
0
 def test_send_message_with_connection_error(self):
     server = ZMQServer('tcp://localhost:5555')
     # Set timeouts
     server.socket.setsockopt(zmq.RCVTIMEO, 5)
     server.socket.setsockopt(zmq.SNDTIMEO, 5)
     server.socket.setsockopt(zmq.LINGER, 5)
     with self.assertRaises(zmq.error.ZMQError):
         server._send_message(str(Request('go')))
예제 #7
0
 def test_send_message_with_invalid_request(self):
     s = HTTPServer('http://test/')
     # Impossible to pass an invalid dict, so just assume the exception was raised
     responses.add(responses.POST,
                   'http://test/',
                   status=400,
                   body=requests.exceptions.InvalidSchema())
     with self.assertRaises(requests.exceptions.InvalidSchema):
         s._send_message(Request('go'))
예제 #8
0
 def test_custom_headers(self):
     testee = TornadoClient(self.get_url('/echo'))
     response = yield testee.send(Request('some_method', 1, [2], {
         '3': 4,
         '5': True,
         '6': None
     }),
                                  headers={'foo': 'bar'})
     self.assertEqual([1, [2], {'3': 4, '6': None, '5': True}], response)
예제 #9
0
    def call(self,
             method_name,
             message=None,
             timeout=None,
             is_stub_reuse=True,
             is_raise=False) -> dict:
        try:
            version = self._method_versions[method_name]
            url = self._version_urls[version]
            method_name = self._method_names[method_name]

            if version == conf.ApiVersion.v1:
                url += method_name
                response = requests.get(url=url,
                                        params={'channel': self._channel_name},
                                        timeout=conf.REST_ADDITIONAL_TIMEOUT)
                if response.status_code != 200:
                    raise ConnectionError
                response = response.json()
            else:
                # using jsonRPC client request.
                if message:
                    request = Request(method_name, message)
                else:
                    request = Request(method_name)

                try:
                    response = self._http_clients[url].send(
                        request, timeout=conf.REST_ADDITIONAL_TIMEOUT)
                except Exception as e:
                    raise ConnectionError(e)
            util.logger.spam(
                f"REST call complete request_url({url}), method_name({method_name})"
            )
            return response

        except Exception as e:
            logging.warning(
                f"REST call fail method_name({method_name}), caused by : {type(e)}, {e}"
            )
            raise e
예제 #10
0
 def test_send_message_custom_headers(self):
     s = HTTPServer('http://test/')
     req = Request('go')
     with self.assertRaises(requests.exceptions.RequestException):
         s._send_message(req,
                         headers={'Content-Type': 'application/json-rpc'})
     # Header set by argument
     self.assertEqual('application/json-rpc',
                      s.last_request.headers['Content-Type'])
     # Header set by DEFAULT_HEADERS
     self.assertEqual('application/json', s.last_request.headers['Accept'])
     # Header set by Requests default_headers
     self.assertIn('Content-Length', s.last_request.headers)
예제 #11
0
 def test_send_message(self):
     client = ZMQClient('tcp://localhost:5555')
     client._send_message(str(Request('go')))
예제 #12
0
 def test_send_message(self):  # pylint: disable=no-self-use
     server = ZMQServer('tcp://localhost:5555')
     server._send_message(str(Request('go')))
예제 #13
0
 def test_send_message_with_connection_error(self):
     s = HTTPServer('http://test/')
     with self.assertRaises(requests.exceptions.RequestException):
         s._send_message(Request('go'))
예제 #14
0
 def test_send_message_body(self):
     s = HTTPServer('http://test/')
     req = Request('go')
     with self.assertRaises(requests.exceptions.RequestException):
         s._send_message(req)
     self.assertEqual(urlencode(req), s.last_request.body)