def call(self, method_name, message=None, timeout=None, is_stub_reuse=True, is_raise=False): 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, params={'channel': self.__channel_name}) else: client = HTTPClient(url) client.session.verify = conf.REST_SSL_VERIFY response = client.request( method_name, message) if message else client.request(method_name) util.logger.spam( f"RestStubManager:call complete request_url({url}), " f"method_name({method_name})") return response except Exception as e: logging.warning( f"REST call fail method_name({method_name}), caused by : {e}") raise e
def test_jsonrpc_int_negative(live_server): c = HTTPClient(live_server.url + '/all-rpc/') result = c.get_negative_int() assert type(result) == int assert result == -42
def main(context, method, request_type, id, send): """ 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, request_id=id, *positional, **named) # 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) # Otherwise, simply output the JSON-RPC request. else: click.echo(str(req)) sys.exit(exit_status)
def create_token(self, *args, **kwargs): """ create kol token Accepts: - token_name [string] token name - token_symbol [string] toke symbol - total_supply [int] token total supply - decimals [int] token precision from 1 to 18 - blockchain [string] blockchain to create token on ( QTUMTEST, ETHTEST ) - is_burnable [Bool] can burn tokens - is_mintable [Bool] can create new tokens Returns dictionary with following fields: - txid [string] - address [string] """ client = HTTPClient(self.withdraw_server_address + self.withdraw_endpoint) if check_sig: return client.request('create_token', self.signature_validator.sign(kwargs)) else: return client.request('create_token', kwargs)
def test_jsonrpc_protocol_specific_methods(live_server): c = HTTPClient(live_server.url + '/json-only/') methods_list = c.request('system.listMethods') assert 'method_x' in methods_list assert 'method_y' not in methods_list
def test_jsonrpc_user_auth(live_server, john_doe, common_pwd): c = HTTPClient(live_server.url + '/all-rpc/') c.session.auth = (john_doe.username, common_pwd) assert c.logged_user_required(5) == 5 assert c.logged_user_required_alt(5) == 5 assert raises(ReceivedErrorResponse, c.request, 'logged_superuser_required', 5).value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'logged_superuser_required_alt', 5).value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'delete_user_perm_required', 5).value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'any_permission_required', 5).value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'all_permissions_required', 5).value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'in_group_A_required', 5).value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'in_groups_A_and_B_required', 5).value.code == RPC_INTERNAL_ERROR e = raises(ReceivedErrorResponse, c.request, 'in_groups_A_and_B_required_alt', 5) assert e.value.code == RPC_INTERNAL_ERROR assert raises(ReceivedErrorResponse, c.request, 'in_group_A_or_B_required', 5).value.code == RPC_INTERNAL_ERROR
def test_custom_predicate_allowed(live_server): c = HTTPClient(live_server.url + '/all-rpc/') assert 'python-requests' in c.get_user_agent() c = xmlrpc_client.ServerProxy(live_server.url + '/all-rpc/') assert 'xmlrpc' in c.get_user_agent()
def test_body(self): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client._prepare_request(request) with self.assertRaises(requests.exceptions.RequestException): client._send_message(request) self.assertEqual(request, request.prepped.body) #pylint:disable=no-member
def test_method_level_str_std(live_server): jclient = HTTPClient(live_server.url + '/all-rpc/') assert jclient.force_unicode_input("abcde") == "<type 'unicode'>" xclient = xmlrpc_client.ServerProxy(live_server.url + '/all-rpc/') assert xclient.force_unicode_input("abcde") == "<type 'unicode'>"
def test_jsonrpc_bool_2(live_server): c = HTTPClient(live_server.url + '/all-rpc/') result = c.get_false() assert type(result) == bool assert result is False
class JSONRpcClient(object): def __init__(self, url): self.url = url self.client = HTTPClient(url) def block_number(self): resp = self.client.request("cita_blockNumber", []) return int(resp, 16) def get_nonce(self, sender, block_number): resp = self.client.request("eth_getTransactionCount", [sender, block_number]) return str(int(resp, 16)) def send_transaction(self, bytecode): return requests.post(self.url, json={ 'jsonrpc': '2.0', 'method': 'cita_sendTransaction', 'id': 1, 'params': [bytecode] }).json() # return self.client.request("cita_sendTransaction", [bytecode]) def get_receipt(self, tx_hash): return self.client.request("eth_getTransactionReceipt", [tx_hash])
def test_jsonrpc_float(live_server): c = HTTPClient(live_server.url + '/all-rpc/') result = c.get_float() assert type(result) == float assert result == 3.14
class ClientHistory(): def __init__(self, history_host=None): self.history_host = history_host if history_host else balance_server self.client = HTTPClient(self.history_host) def getbalance(self, uids=None, coin_id="QTUM"): if uids: request = self.client.request(method_name="getbalance", address=uids) return request else: return {2: "Missing name uid"} def incbalance(self, uids=None, amount=0, coin_id="QTUM"): if uids: request = self.client.request(method_name="incbalance", address=uids, amount=amount) return request else: return {2: "Missing name uid"} def decbalance(self, uids=None, amount=0, coin_id="QTUM"): if uids: request = self.client.request(method_name="decbalance", address=uids, amount=amount) return request else: return {2: "Missing name uid"} def set_balance(self, uid, amount): return self.client.set_balance(uid, amount)
def test_jsonrpc_get_signature(live_server): c = HTTPClient(live_server.url + '/all-rpc/') signature = c.request('system.methodSignature', "add") # This one doesn not have any docstring defined assert type(signature) == list assert len(signature) == 0
def test_ssl_verification(self): client = HTTPClient('https://test/') client.session.cert = '/path/to/cert' client.session.verify = 'ca-cert' request = PreparedRequest(Request('go')) client._prepare_request(request) with self.assertRaises(requests.exceptions.RequestException): client._send_message(request)
def test_success_200(): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client._prepare_request(request) responses.add( responses.POST, 'http://test/', status=200, body='{"jsonrpc": "2.0", "result": 5, "id": 1}') client._send_message(request)
def test_jsonrpc_exception_with_data(live_server): client = HTTPClient(live_server.url + '/all-rpc/') with pytest.raises(ReceivedErrorResponse) as excinfo: client.raise_custom_exception_with_data() assert ['a', 'b', 'c'] == excinfo.value.data
def update_ETH_cid(): client = HTTPClient("http://localhost:8007/api/bridge") cid = client.request(method_name="get_next_cid")["next_cid"] content = list(MongoClient().ETH.content.find())[-1] txid = content["txid"] MongoClient().ETH.content.find_one_and_update( {"txid":txid},{"$set":{"cid":int(cid)-1}}) print("Done")
def test_jsonrpc_protocol_specific_error(live_server): c = HTTPClient(live_server.url + '/xml-only/') with pytest.raises(ParseResponseError): # There is no method available via this entry point for JSON-RPC clients. # The returned error message cannot be encapsulated in a proper JSON-RPC response (since the entry # point is not configured to handle and respond via this protocol). The returned error message is RAW, # so JSON-RPC cannot parse it and generate a JSONDecodeError, or a ValueError in python 2 c.request('system.listMethods')
def download_image(cid): decode_hex = codecs.getdecoder("hex_codec") encode_hex = codecs.getencoder("hex_codec") client = HTTPClient('http://localhost:8888') data = client.request(method_name='readbycid', cid=str(cid)) print(data) with open('comando_downloaded.jpg', 'wb') as file: file.write(decode_hex(data.encode())[0])
def test_jsonrpc_date(live_server): c = HTTPClient(live_server.url + '/all-rpc/') result = c.get_date() # Unlike XML-RPC, JSON transport does not store value types. # Dates are transmitted as string in ISO 8601 format: assert '1987-06-02' in result assert '08:45:00' in result
def test_jsonrpc_string(live_server): c = HTTPClient(live_server.url + '/all-rpc/') result = c.get_string() # Unlike XML-RPC, JSON-RPC always return a unicode string. That means the type of the result value is # 'unicode' in Python 2 and 'str' in python 3. assert type(result) == str if six.PY3 else unicode assert result == 'abcde'
def test_jsonrpc_invalid_result(live_server): client = HTTPClient(live_server.url + '/all-rpc/') with pytest.raises(ReceivedErrorResponse) as excinfo: client.get_invalid_result() assert 'Unable to serialize result as' in excinfo.value.message assert excinfo.value.code == RPC_INTERNAL_ERROR
def test_jsonrpc_call_unknown_method(live_server): client = HTTPClient(live_server.url + '/all-rpc/') with pytest.raises(ReceivedErrorResponse) as excinfo: client.non_existing_method() assert 'Method not found: non_existing_method' in excinfo.value.message assert excinfo.value.code == RPC_METHOD_NOT_FOUND
def test_jsonrpc_internal_error(live_server): client = HTTPClient(live_server.url + '/all-rpc/') with pytest.raises(ReceivedErrorResponse) as excinfo: client.raise_custom_exception() assert 'This is a test error' in excinfo.value.message assert RPC_CUSTOM_ERROR_BASE <= excinfo.value.code <= RPC_CUSTOM_ERROR_MAX
def get_single_content(): client = HTTPClient("http://localhost:8003/api/bridge") cid = client.request(method_name="get_next_cid")["next_cid"] cid = int(cid) - 1 url = get_single_content_url % (cid, "QTUM") response = requests.get(url) pprint(response.json())
def test_jsonrpc_multicall_error(live_server): c = HTTPClient(live_server.url + '/all-rpc/') with pytest.raises(ReceivedErrorResponse) as excinfo: c.request('system.multicall') assert 'Method not found' in excinfo.value.message assert excinfo.value.code == RPC_METHOD_NOT_FOUND
def test_jsonrpc_input_string(live_server): c = HTTPClient(live_server.url + '/all-rpc/') # Python 2 : "<type 'str'>" # Python 3 : "<class 'str'>" # By default on Python 2, json-rpc call to this method will return 'unicode' # This test suite has been configured with settings.MODERNRPC_PY2_STR_TYPE = str, so # arguments passed to RPC methods via XML or JSON will be converted to the same type (str in that case) assert re.match(r"<(class|type) 'str'>", c.get_data_type('abcd'))
def test_call_with_named_args_errors(live_server): c = HTTPClient(live_server.url + '/all-rpc/') with pytest.raises(ReceivedErrorResponse) as excinfo: c.divide(wrong_param_1=10, wrong_param_2=20, z=25) assert 'Invalid parameters' in excinfo.value.message assert 'unexpected keyword argument' in excinfo.value.message assert excinfo.value.code == RPC_INVALID_PARAMS
def test_invalid_request(self): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client._prepare_request(request) # 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): client._send_message(request)
def test_jsonrpc_protocol_specific_methods_invalid_method(live_server): c = HTTPClient(live_server.url + '/json-only/') # method_y is available only via XML-RPC with pytest.raises(ReceivedErrorResponse) as excinfo: c.method_y() assert 'Method not found: method_y' in excinfo.value.message assert excinfo.value.code == RPC_METHOD_NOT_FOUND
def test_jsonrpc_date_3(live_server): c = HTTPClient(live_server.url + '/all-rpc/') date = datetime.datetime(2000, 6, 3, 0, 0, 0) # We have to convert date to ISO 8601, since JSON-RPC cannot serialize it result = c.add_one_month(date.isoformat()) # JSON-RPC will transmit the input argument and the result as standard string assert '2000-07-04' in result
def test_update_userprefs(): client = HTTPClient('http://*****:*****@steemit.com']}) print('request sent:') pprint.pprint(req) results = client.send(req) print('Server response:') pprint.pprint(results)
def test_jsonrpc_struct(live_server): c = HTTPClient(live_server.url + '/all-rpc/') result = c.get_struct() assert type(result) == dict assert result == { 'x': 1, 'y': 2, 'z': 3, }
def test_custom_headers(self): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client._prepare_request(request, headers={'Content-Type': 'application/json-rpc'}) with self.assertRaises(requests.exceptions.RequestException): client._send_message(request) #pylint:disable=no-member # Header set by argument self.assertEqual('application/json-rpc', request.prepped.headers['Content-Type']) # Header set by DEFAULT_HEADERS self.assertEqual('application/json', request.prepped.headers['Accept']) # Header set by Requests default_headers self.assertIn('Content-Length', request.prepped.headers)
def test_connection_error(self): client = HTTPClient('http://test/') request = PreparedRequest(Request('go')) client._prepare_request(request) with self.assertRaises(requests.exceptions.RequestException): client._send_message(request)