Ejemplo n.º 1
0
 def test_batch(self):
     gen_id = iter(range(100))
     batch = (
         Request('vadd.test', 5, 10, id_generator=gen_id),
         Request('vsub.test', arg1=10, arg2=9, id_generator=gen_id),
         Request('test.hello', 'WORLD', id_generator=gen_id),
         Request('nonexistent_method', id_generator=gen_id),
         Request('test.test_div', 10, 0, id_generator=gen_id),
     )
     resp = self.client.send(batch)
     self.assertEqual(len(resp.data), 5)
     for r in resp.data:
         if r.id == 0:
             self.assertEqual(r.result, 15)
         elif r.id == 1:
             self.assertEqual(r.result, 1)
         elif r.id == 2:
             self.assertEqual(r.result, 'Hello WORLD!')
         elif r.id == 3:
             self.assertFalse(r.ok)
             self.assertEqual(r.code, -32601)
         elif r.id == 4:
             self.assertFalse(r.ok)
             self.assertEqual(r.code, -32000)
             self.assertEqual(r.message, 'division by zero')
Ejemplo n.º 2
0
 def EpochTest(self, epoch: int) -> None:
     """Test epoch commands"""
     delay = 3
     self._send_json(str(Request(f"setEpoch", epoch)))
     self.ExpectOk()
     time.sleep(delay)
     self._send_json(str(Request("getEpoch")))
     self.ExpectRange("epoch", epoch + delay - 1, epoch + delay + 1)
Ejemplo n.º 3
0
    def _get_rcp_request(self, path, **kwargs):

        kwargs['data'] = kwargs.get('data', None)

        rcp_request = Request(path)
        if kwargs['data']:
            rcp_request.update(params=kwargs['data'])

        return rcp_request
Ejemplo n.º 4
0
async def main():
    response = await client.send(
        [Request("ping"),
         Notification("ping"),
         Request("ping")])
    for data in response.data:
        if data.ok:
            print("{}: {}".format(data.id, data.result))
        else:
            logging.error("%d: %s", data.id, data.message)
Ejemplo n.º 5
0
async def main():

    async with websockets.connect("ws://localhost:5000") as ws:
        requests = [Request("ping"), Notification("ping"), Request("ping")]
        response = await WebSocketsClient(ws).send(requests)

    for data in response.data:
        if data.ok:
            print("{}: {}".format(data.id, data.result))
        else:
            logging.error("%d: %s", data.id, data.message)
Ejemplo n.º 6
0
async def main(loop):

    async with aiohttp.ClientSession(loop=loop) as session:
        client = AiohttpClient(session, "http://localhost:5000")
        requests = [Request("ping"), Notification("ping"), Request("ping")]
        response = await client.send(requests)

    for data in response.data:
        if data.ok:
            print("{}: {}".format(data.id, data.result))
        else:
            logging.error("%d: %s", data.id, data.message)
Ejemplo n.º 7
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)
Ejemplo n.º 8
0
    def get_regualr_key(self, address: str, block_number: Union[int, None]):
        payload = Request("chain_getRegularKey",
                          address=address,
                          blockNumber=block_number)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 9
0
    def get_balance(self, address: str, block_number: Union[int, None]):
        payload = Request("chain_getBalance",
                          address=address,
                          blockNumber=block_number)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 10
0
def main(context: click.core.Context, method: str, request_type: str, id: Any,
         send: str) -> None:
    """
    Create a JSON-RPC request.
    """
    exit_status = 0
    # Extract the jsonrpc arguments
    positional = [a for a in context.args if "=" not in a]
    named = {
        a.split("=")[0]: a.split("=")[1]
        for a in context.args if "=" in a
    }
    # Create the request
    if request_type == "notify":
        req = Notification(method, *positional, **named)
    else:
        req = Request(method, *positional, request_id=id,
                      **named)  # type: ignore
    # Sending?
    if send:
        client = HTTPClient(send)
        try:
            response = client.send(req)
        except JsonRpcClientError as e:
            click.echo(str(e), err=True)
            exit_status = 1
        else:
            click.echo(response.text)
    # Otherwise, simply output the JSON-RPC request.
    else:
        click.echo(str(req))
    sys.exit(exit_status)
Ejemplo n.º 11
0
 def test_positional(self):
     assert Request("sqrt", 1) == {
         "jsonrpc": "2.0",
         "method": "sqrt",
         "params": [1],
         "id": 1,
     }
Ejemplo n.º 12
0
 def __check_connection(self):
     url = "%s://%s:%s/jsonrpc" % (self.config.protocol, self.config.host, self.config.port)
     self.client = HTTPClient(url)
     self.client.session.auth = (self.config.username, self.config.passwd)
     response = self.client.send(Request('Application.GetProperties', list(), id_generator=id_generators.random()))
     if not response.data.ok:
         raise KodiServerCheckException()
Ejemplo n.º 13
0
 def clean_current_playlist(self):
     response = self.client.send(
         Request('Playlist.Clear', self.playlist_id, id_generator=id_generators.random()))
     if response.data.ok:
         logger.info('Current playlist has cleaned')
     else:
         raise KodiActionException('Playlist.Clean')
Ejemplo n.º 14
0
    async def test_send_exception_check_parameters(self):
        ws = MockWebSocket()
        ws.send = AsyncMock()
        expected_method = "fake_method"
        expected_exc = RuntimeError("test")
        expected_error_code = message_code.Response.fail_subscribe_limit

        expected_request = Request(method=expected_method,
                                   error=str(expected_exc),
                                   code=expected_error_code)
        expected_called_params = dict(expected_request)

        await WSDispatcher.send_exception(ws,
                                          method=expected_method,
                                          exception=expected_exc,
                                          error_code=expected_error_code)

        actual_called_params, _ = ws.send.call_args
        actual_called_params: dict = json.loads(actual_called_params[0])

        # Remove id because jsonrpc call auto-increments request id.
        expected_called_params.pop("id")
        actual_called_params.pop("id")

        assert actual_called_params == expected_called_params
Ejemplo n.º 15
0
    def execute_transaction(self, transaction, sender: str):
        payload = Request("chain_executeTransaction",
                          transaction=transaction,
                          sender=sender)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 16
0
 def test_keyword(self):
     assert Request("find", name="Foo") == {
         "jsonrpc": "2.0",
         "method": "find",
         "params": {"name": "Foo"},
         "id": 1,
     }
Ejemplo n.º 17
0
 def __call__(self, *args, **argsn):
     if argsn:
         raise ValueError('json rpc 2 only supports array arguments')
     from jsonrpcclient.requests import Request
     request = Request(self.method, *args)
     response = self.client.send(request, timeout=self.timeout)
     return response.data.result
    def get_pending_transactions(
        self, tx_from: Union[int, None], tx_to: Union[int, None]
    ):
        payload = Request("mempool_getPendingTransactions", tx_from, tx_to)
        response = self.client.send(payload)

        return response.data.result
Ejemplo n.º 19
0
    def get_shard_users(self, shard_id: int, block_number: Union[int, None]):
        payload = Request("chain_getShardUsers",
                          shardId=shard_id,
                          blockNumber=block_number)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 20
0
    async def publish_new_block(ws, channel_name, height, peer_id):
        call_method = WSDispatcher.PUBLISH_NEW_BLOCK
        channel_stub = get_channel_stub_by_channel_name(channel_name)
        try:
            while True:
                new_block_dumped, confirm_info_bytes = await channel_stub.async_task(
                ).announce_new_block(subscriber_block_height=height,
                                     subscriber_id=peer_id)
                new_block: dict = json.loads(new_block_dumped)

                if "error" in new_block:
                    Logger.error(
                        f"announce_new_block error: {new_block}, to citizen({peer_id})"
                    )
                    break

                confirm_info = confirm_info_bytes.decode('utf-8')
                request = Request(call_method,
                                  block=new_block,
                                  confirm_info=confirm_info)
                Logger.debug(f"{call_method}: {request}")

                await ws.send(json.dumps(request))
                height += 1
        except exceptions.ConnectionClosed:
            Logger.debug(
                "Connection Closed by child.")  # TODO: Useful message needed.
        except Exception as e:
            traceback.print_exc()  # TODO: Keep this tb?
            await WSDispatcher.send_exception(
                ws,
                call_method,
                exception=e,
                error_code=message_code.Response.fail_announce_block)
Ejemplo n.º 21
0
    def run_test(self):
        # generate block with many transactions
        parent_hash = self.rpc.block_by_epoch("latest_mined")['hash']
        start_nonce = self.rpc.get_nonce(self.rpc.GENESIS_ADDR)
        txs = [self.rpc.new_tx(nonce=start_nonce + ii) for ii in range(0, 100)]
        hash = self.rpc.generate_custom_block(parent_hash=parent_hash,
                                              referee=[],
                                              txs=txs)
        epoch = self.rpc.block_by_hash(hash)["epochNumber"]

        # make sure block is executed
        self.rpc.generate_empty_blocks(5)

        # getting epoch receipts should result in error
        try:
            resp = block_on(
                self.ws.send(Request("cfx_getEpochReceipts", epoch)))
            assert False, "cfx_getEpochReceipts request should have failed"
        except ReceivedErrorResponseError as e:
            self.log.info(e.response)
            assert e.response.data.startswith("\"Oversized payload")
        except Exception as e:
            assert False, f"unexpected error: {e}"

        # this should succeed
        # resp = self.rpc.node.cfx_getEpochReceipts(epoch)

        self.log.info("Pass")
Ejemplo n.º 22
0
    def get_text(self, transaction_hash: str, block_number: Union[int, None]):
        payload = Request("chain_getText",
                          transactionHash=transaction_hash,
                          blockNumber=block_number)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 23
0
def do_rpc(method, log_error=True, **kwargs):
    req = Request(method, **kwargs)
    try:
        url = AppInstance.settings.rpc_url()
        resp = post(url, json=req, timeout=10)
        if resp.status_code != 200 and log_error:
            logging.error("RPC ==> {}".format(req))
            logging.error("RPC <== {}".format(resp.text))
        if resp.status_code != 200:
            try:  #Attempt parse response when failed
                return json.loads(resp.text)
            except:
                return None
        return json.loads(resp.text)["result"]
    except TimeoutError:
        if log_error:
            #Any RPC timeout errors are totally fatal
            logging.error("RPC Timeout")
            AppInstance.on_exit()
            show_error("RPC Timeout", "Timeout contacting RPC")
            exit(-1)
            return None
        else:
            return None
    except Exception as ex:
        logging.error(ex)
        return None
Ejemplo n.º 24
0
    def unlock(self, account, passphrase):
        payload = Request("account_unlock",
                          account=account,
                          passphrase=passphrase)
        response = self.client.send(payload)

        return response.result
    def import_raw(self, secret, passphrase):
        if isinstance(secret, bytes):
            secret = "0x" + binascii.hexlify(secret).decode("ascii")
        payload = Request("account_importRaw", secret, passphrase)
        response = self.client.send(payload)

        return response.data.result
Ejemplo n.º 26
0
    def import_raw(self, secret, passphrase):
        payload = Request("account_importRaw",
                          secret=secret,
                          passphrase=passphrase)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 27
0
def fetch_data_packet(socket, device_addr, timestamp):
    req = Request("get_data_packet",
                  timestamp=timestamp,
                  device_addr_index=device_addr)
    print(f"{device_addr} -> {req}")
    socket.send_string(str(req))
    resp = socket.recv().decode("utf-8")
    print(f"Response -> {resp}")
Ejemplo n.º 28
0
    def get_regualr_key_owner(self, public_key: str,
                              block_number: Union[int, None]):
        payload = Request("chain_getRegularKeyOwner",
                          publicKey=public_key,
                          blockNumber=block_number)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 29
0
    def sign(self, message, account, passphrase):
        payload = Request("account_sign",
                          message=message,
                          account=account,
                          passphrase=passphrase)
        response = self.client.send(payload)

        return response.result
Ejemplo n.º 30
0
 def test_send_message_conn_error(self):
     client = ZeroMQClient("tcp://localhost:5555")
     # Set timeouts
     client.socket.setsockopt(zmq.RCVTIMEO, 5)
     client.socket.setsockopt(zmq.SNDTIMEO, 5)
     client.socket.setsockopt(zmq.LINGER, 5)
     with pytest.raises(zmq.error.ZMQError):
         client.send_message(str(Request("go")), response_expected=True)