def __init__(self, *args): unittest.TestCase.__init__(self, *args) self.s = jsonrpclib.ServerProxy("http://127.0.0.9/services/wanted/", verbose=0) self.f = jsonrpclib.ServerProxy("http://127.0.0.9/services/forms/", verbose=0)
def createRpc (self): """ Returns a freshly created JSON-RPC connection for this node. This can be used if multiple threads need to send RPCs in parallel. """ return jsonrpclib.ServerProxy (self.rpcurl)
def start(self, xayarpc, gsprpc, bcrpc, extraArgs=[]): if self.proc is not None: self.log.error( "Channel process is already running, not starting again") return self.log.info("Starting channel daemon for %s" % self.playerName) args = [self.binary] args.append("--xaya_rpc_url=%s" % xayarpc) args.append("--gsp_rpc_url=%s" % gsprpc) args.append("--broadcast_rpc_url=%s" % bcrpc) args.append("--rpc_port=%d" % self.port) args.append("--channelid=%s" % self.channelId) args.append("--playername=%s" % self.playerName) args.extend(extraArgs) envVars = dict(os.environ) envVars["GLOG_log_dir"] = self.datadir self.proc = subprocess.Popen(args, env=envVars) self.rpc = self.createRpc() self.xayaRpc = jsonrpclib.ServerProxy(xayarpc) self.log.info("Waiting for the JSON-RPC server to be up...") while True: try: data = self.rpc.getcurrentstate() self.log.info("Channel daemon is up for %s" % self.playerName) break except: time.sleep(0.1)
def test_should_allow_to_nest_additional_header_blocks(self): """ Check nested additional headers """ # given client = jsonrpclib.ServerProxy("http://localhost:{0}".format( self.port), verbose=1) # when with client._additional_headers({"X-Level-1": "1"}) as cl_level1: with self.captured_headers() as headers1: response = cl_level1.ping() self.assertTrue(response) with cl_level1._additional_headers({"X-Level-2": "2"}) as cl: with self.captured_headers() as headers2: response = cl.ping() self.assertTrue(response) # then self.assertTrue("x-level-1" in headers1) self.assertEqual(headers1["x-level-1"], "1") self.assertTrue("x-level-1" in headers2) self.assertEqual(headers1["x-level-1"], "1") self.assertTrue("x-level-2" in headers2) self.assertEqual(headers2["x-level-2"], "2")
def createRpc(self): """ Returns a freshly created JSON-RPC connection for this daemon. This can be used if multiple threads need to send RPCs in parallel. """ return jsonrpclib.ServerProxy("http://localhost:%d" % self.port)
def test_should_allow_to_nest_additional_header_blocks(self): # given client = jsonrpclib.ServerProxy('http://localhost:{0}'.format( self.port), verbose=1) # when with client._additional_headers({'X-Level-1': '1'}) as cl_level1: with self.captured_headers() as headers1: response = cl_level1.ping() self.assertTrue(response) with cl_level1._additional_headers({'X-Level-2': '2'}) as cl: with self.captured_headers() as headers2: response = cl.ping() self.assertTrue(response) # then self.assertTrue('x-level-1' in headers1) self.assertEqual(headers1['x-level-1'], '1') self.assertTrue('x-level-1' in headers2) self.assertEqual(headers1['x-level-1'], '1') self.assertTrue('x-level-2' in headers2) self.assertEqual(headers2['x-level-2'], '2')
def test_should_restore_global_headers(self): """ Check custom headers context clean up """ # given client = jsonrpclib.ServerProxy( "http://localhost:{0}".format(self.port), verbose=1, headers={"X-Test": "Global"}, ) # when with self.captured_headers() as headers: with client._additional_headers({"X-Test": "Method"}) as cl: response = cl.ping() self.assertTrue(response) self.assertTrue("x-test" in headers) self.assertEqual(headers["x-test"], "Method") with self.captured_headers() as headers: response = cl.ping() self.assertTrue(response) # then self.assertTrue("x-test" in headers) self.assertEqual(headers["x-test"], "Global")
def test_url_query_string(self): """ Tests if the query string arguments are kept """ # Prepare a simple server class ReqHandler(BaseHTTPRequestHandler): """ Basic request handler that returns parameters """ def do_POST(self): parsed = urlparse(self.path) result = { "id": 0, "error": None, "result": { "path": parsed.path, "qs": parsed.query, }, } result_str = json.dumps(result).encode("utf8") self.send_response(200) self.send_header("content-type", "application/json") self.send_header("content-length", str(len(result_str))) self.end_headers() self.wfile.write(result_str) # Start it httpd = HTTPServer(("", 0), ReqHandler) # Run it in a thread thread = threading.Thread(target=httpd.serve_forever) thread.daemon = True thread.start() # Prepare a random value arg = str(random.randint(0, 1024)) # Prepare the client client = jsonrpclib.ServerProxy( "http://localhost:{port}/test?q={arg}".format( port=httpd.server_port, arg=arg ) ) # Run a query result = client.test() # Stop the server httpd.shutdown() httpd.server_close() # Check the result self.assertEqual(result["path"], "/test", "Invalid path") self.assertEqual( result["qs"], "q={}".format(arg), "Invalid query string" ) # Wait the server to stop (5 sec max) thread.join(5)
def get_client(self): """ Utility method to get a proxy to the test server """ return jsonrpclib.ServerProxy( "http://localhost:{0}".format(self.port), history=self.history )
def getWalletRpc(self, wallet): """ Returns the RPC URL to use for a particular wallet as well as a ServerProxy instance. """ url = "%s/wallet/%s" % (self.baseRpcUrl, wallet) return url, jsonrpclib.ServerProxy(url)
def system_emit(): rpc = jsonrpclib.ServerProxy(_url, api_key=_api_key) def _emit(_id, _res): rpc.ann.emit_async(ssekey, eventname, _id) rpc("close")() return _emit
def ui(request, server): """Fixture of environment for unittests JSONRPC UI wrappers. """ ui = ui_onpss_jsonrpc.UiOnpssJsonrpc(MagicMock(**CONFIG)) url = urllib.parse.urlunsplit( ('http', '{0}:{1}'.format(CONFIG["ip_host"], CONFIG["json_port"]), '', '', '')) ui.jsonrpc = jsonrpclib.ServerProxy(url) return ui
def test_tranport_error(self): """ test http error handling """ badserver = jsonrpclib.ServerProxy( "http://localhost:{0}/pathdoesnotexist".format(self.port), history=self.history, ) self.assertRaises(jsonrpclib.TransportError, badserver.foo)
def __init__(self, url, user, password): self.url = url self._server = jsonrpclib.ServerProxy(self.url) self.__session = None self.__user = user self.__password = password self.__timeout = timedelta(seconds=1) self.__expires = None self.__lastcalled = datetime.now() self.__lastused = datetime(year=1970, month=1, day=1) self.logger = logging.getLogger('jsonubus')
def test(): service_process = Process(target=service.start) service_process.start() time.sleep(1) server = jsonrpclib.ServerProxy('http://localhost:4040') assert server.add(5, 6) == 11 print('test passed!') service_process.terminate()
def run(self): port = self.gamenode.port rpc = jsonrpclib.ServerProxy("http://127.0.0.1:%d" % port) alternateRpc = jsonrpclib.ServerProxy("http://127.0.0.2:%d" % port) # By default, the normal RPC connection to 127.0.0.1 should work. But the # connection to the alternate IP 127.0.0.2 should fail. assert rpc.getcurrentstate()["chain"] == "regtest" try: alternateRpc.getcurrentstate() raise AssertionError("Expected connection failure, got none") except socket.error as exc: assert exc.errno == errno.ECONNREFUSED # Restart and listen on all interfaces. self.stopGameDaemon() self.startGameDaemon(extraArgs=["--game_rpc_listen_locally=false"]) # Now both connections should work. assert rpc.getcurrentstate()["chain"] == "regtest" assert alternateRpc.getcurrentstate()["chain"] == "regtest"
def setUp(self): """ Pre-test set up """ # Set up the server self.server = UtilityServer().start('', 0) self.port = self.server.get_port() # Set up the client self.history = jsonrpclib.history.History() self.client = jsonrpclib.ServerProxy( 'http://localhost:{0}'.format(self.port), history=self.history)
def test2(): service_process = Process(target=service.start) service_process.start() time.sleep(1) server = jsonrpclib.ServerProxy('http://localhost:4040') my_test = server.maze_creation(2, 2) print(my_test) print('test passed!') service_process.terminate()
def test_should_add_additional_headers_to_notifications(self): # given client = jsonrpclib.ServerProxy('http://localhost:{0}'.format( self.port), verbose=1, headers={'X-My-Header': 'Test'}) # when with self.captured_headers() as headers: client._notify.ping() # then self.assertTrue('x-my-header' in headers) self.assertEqual(headers['x-my-header'], 'Test')
def getWalletRpc(self, wallet): """ Returns the RPC URL to use for a particular wallet as well as a ServerProxy instance. """ url = "%s/wallet/%s" % (self.baseRpcUrl, wallet) rpc = jsonrpclib.ServerProxy(url) # Record all RPC handles created, so we can close them when # shutting down. self.rpcHandles.append(rpc) return url, rpc
def __init__(self, binary, basedir, rpcport): self.log = logging.getLogger("charonclient") self.binary = binary self.rpcport = rpcport self.datadir = os.path.join(basedir, "charonclient") self.log.info("Creating data directory for charon client in %s" % self.datadir) shutil.rmtree(self.datadir, ignore_errors=True) os.mkdir(self.datadir) self.rpc = jsonrpclib.ServerProxy("http://localhost:%d" % self.rpcport) self.proc = None
def test_should_extract_headers(self): # given client = jsonrpclib.ServerProxy('http://localhost:{0}'.format( self.port), verbose=1) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue(len(headers) > 0) self.assertTrue('content-type' in headers) self.assertEqual(headers['content-type'], 'application/json-rpc')
def test_should_convert_header_values_to_basestring(self): # given client = jsonrpclib.ServerProxy('http://localhost:{0}'.format( self.port), verbose=1, headers={'X-Test': 123}) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue('x-test' in headers) self.assertEqual(headers['x-test'], '123')
def test_should_not_override_content_length(self): # given client = jsonrpclib.ServerProxy( 'http://localhost:{0}'.format(self.port), verbose=1, headers={'Content-Length': 'invalid value'}) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue('content-length' in headers) self.assertNotEqual(headers['content-length'], 'invalid value')
def test_should_add_additional_headers_to_notifications(self): """ Check custom headers on notifications """ # given client = jsonrpclib.ServerProxy( "http://localhost:{0}".format(self.port), verbose=1, headers={"X-My-Header": "Test"}, ) # when with self.captured_headers() as headers: client._notify.ping() # then self.assertTrue("x-my-header" in headers) self.assertEqual(headers["x-my-header"], "Test")
def test_should_override_global_headers(self): # given client = jsonrpclib.ServerProxy('http://localhost:{0}'.format( self.port), verbose=1, headers={'X-Test': 'Global'}) # when with self.captured_headers() as headers: with client._additional_headers({'X-Test': 'Method'}) as cl: response = cl.ping() self.assertTrue(response) # then self.assertTrue('x-test' in headers) self.assertEqual(headers['x-test'], 'Method')
def test_should_add_custom_headers_to_methods(self): # given client = jsonrpclib.ServerProxy('http://localhost:{0}'.format( self.port), verbose=1) # when with self.captured_headers() as headers: with client._additional_headers({'X-Method': 'Method'}) as cl: response = cl.ping() self.assertTrue(response) # then self.assertTrue('x-method' in headers) self.assertEqual(headers['x-method'], 'Method')
def test_should_extract_headers(self): """ Check client headers capture """ # given client = jsonrpclib.ServerProxy("http://localhost:{0}".format( self.port), verbose=1) # when with self.captured_headers() as headers: response = client.ping() self.assertTrue(response) # then self.assertTrue(len(headers) > 0) self.assertTrue("content-type" in headers) self.assertEqual(headers["content-type"], "application/json-rpc")
def connectRegtestRpc(url, logger): """ Opens an RPC client connection to the given JSON-RPC url, and verifies that it is good and on regtest. """ rpc = jsonrpclib.ServerProxy(url) netinfo = rpc.getnetworkinfo() logger.info("Connected to Xaya Core version %d" % netinfo["version"]) chaininfo = rpc.getblockchaininfo() if chaininfo["chain"] != "regtest": logger.fatal("Connected to chain %s instead of regtest" % chaininfo["chain"]) sys.exit(1) return rpc
def test_should_add_custom_headers_to_methods(self): """ Check method-based custom headers """ # given client = jsonrpclib.ServerProxy("http://localhost:{0}".format( self.port), verbose=1) # when with self.captured_headers() as headers: with client._additional_headers({"X-Method": "Method"}) as cl: response = cl.ping() self.assertTrue(response) # then self.assertTrue("x-method" in headers) self.assertEqual(headers["x-method"], "Method")