def translate_result(self, id_, rslt, err, trace): if err is not None: error = {} if hasattr(err, 'jsonrpc_error_msg'): error['message'] = err.jsonrpc_error_msg else: error['message'] = unicode(err) if hasattr(err, 'jsonrpc_error_code'): error['code'] = err.jsonrpc_error_code else: error['code'] = -32603 if trace: error['data'] = trace return dumps({'id': id_, 'error': error}) try: return dumps({'jsonrpc': '2.0', 'id': id_, 'result': rslt}) except JSONEncodeException: error = { 'message': 'Internal JSON-RPC error', 'code': -32603, } if trace: error['data'] = trace return dumps({'id': id_, 'error': error})
def test_Float(self): json = jsonrpc.dumps(1.2345) self.assertJSON(json, u'1.2345') json = jsonrpc.dumps(1.2345e67) self.assertJSON(json, u'1.2345e+67') json = jsonrpc.dumps(1.2345e-67) self.assertJSON(json, u'1.2345e-67')
def test_Float(self): json = jsonrpc.dumps(1.2345) self.assertJSON(json, u'1.2345') json =jsonrpc.dumps(1.2345e67) self.assertJSON(json, u'1.2345e+67') json =jsonrpc.dumps(1.2345e-67) self.assertJSON(json, u'1.2345e-67')
def translateResult(self, rslt, err, id_): if err != None: err = {"name": err.__class__.__name__, "message":err} rslt = None try: data = dumps({"result":rslt,"id":id_,"error":err}) except JSONEncodeException, e: err = {"name": "JSONEncodeException", "message":"Result Object Not Serializable"} data = dumps({"result":None, "id":id_,"error":err})
def translateResult(self, rslt, err, id_): if err != None: err = {"name": err.__class__.__name__, "message":err.message} rslt = None try: data = dumps({"result":rslt,"id":id_,"error":err}) except JSONEncodeException, e: err = {"name": "JSONEncodeException", "message":"Result Object Not Serializable"} data = dumps({"result":None, "id":id_,"error":err})
def test_datetime_objects(self): """Test that we serialize datetime objects without raising""" now = datetime.datetime.now() obj = {'time': now} value = jsonrpc.dumps(obj) self.assertTrue(value)
def test_translateRequest(self): handler = Handler(self.service) json=jsonrpc.dumps({"method":"echo", 'params':['foobar'], 'id':''}) req = handler.translateRequest(json) self.assertEquals(req['method'], "echo") self.assertEquals(req['params'],['foobar']) self.assertEquals(req['id'],'')
def test_translate_request(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'echo', 'params': ['foobar'], 'id': ''}) req = handler.translate_request(json) self.assertEqual(req['method'], 'echo') self.assertEqual(req['params'], ['foobar']) self.assertEqual(req['id'], '')
def test_NestedDictAllTypes(self): json = jsonrpc.dumps({ 's': 'foobar', 'int': 1234, 'float': 1234.567, 'exp': 1234.56e78, 'negInt': -1234, 'None': None, 'True': True, 'False': False, 'list': [1, 2, 4, {}], 'dict': { 'a': 'b' } }) obj = jsonrpc.loads(json) self.assertEquals( obj, { 's': 'foobar', 'int': 1234, 'float': 1234.567, 'exp': 1234.56e78, 'negInt': -1234, 'None': None, 'True': True, 'False': False, 'list': [1, 2, 4, {}], 'dict': { 'a': 'b' } })
def test_NestedDictAllTypes(self): json = jsonrpc.dumps({'s':'foobar', 'int':1234, 'float':1234.567, 'exp':1234.56e78, 'negInt':-1234, 'None':None,'True':True, 'False':False, 'list':[1,2,4,{}], 'dict':{'a':'b'}}) obj = jsonrpc.loads(json) self.assertEquals(obj, {'s':'foobar', 'int':1234, 'float':1234.567, 'exp':1234.56e78, 'negInt':-1234, 'None':None,'True':True, 'False':False, 'list':[1,2,4,{}], 'dict':{'a':'b'}})
def test_handle_request_MethodRaiseError(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'raise_error', 'params': [], 'id': ''}) result = handler.handle_request(json) self.assertEqual( jsonrpc.loads(result), {'error': {'code': -32603, 'message': 'foobar'}, 'id': ''}, )
def test_handle_request_echo(self): handler = Handler(self.service) json = jsonrpc.dumps({'method':'echo', 'params':['foobar'], 'id':''}) expected = '{"result":"foobar", "id":"", "jsonrpc":"2.0"}' result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), jsonrpc.loads(expected))
def test_request_processing(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'echo', 'params': ['foobar'], 'id': ''}) handler.handle_request(json) self.assertTrue(handler._request_translated) self.assertTrue(handler._found_service_method) self.assertTrue(handler._service_method_called) self.assertTrue(handler._result_translated)
def test_RequestProcessing(self): handler = Handler(self.service) json=jsonrpc.dumps({"method":"echo", 'params':['foobar'], 'id':''}) result = handler.handleRequest(json) self.assert_(handler._requestTranslated) self.assert_(handler._foundServiceEndpoint) self.assert_(handler._invokedEndpoint) self.assert_(handler._resultTranslated)
def test_handle_request_echo(self): handler = Handler(self.service) json = jsonrpc.dumps({ 'method': 'echo', 'params': ['foobar'], 'id': '' }) expected = '{"result":"foobar", "id":"", "jsonrpc":"2.0"}' result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), jsonrpc.loads(expected))
def test_handle_request_MethodNotFound(self): handler=Handler(self.service) json=jsonrpc.dumps({'method': 'not_found', 'params': ['foobar'], 'id':''}) result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), {'error': { 'message':'Method not found: not_found', 'code': -32601}, 'id':''})
def test_handle_request_MethodRaiseError(self): handler=Handler(self.service) json=jsonrpc.dumps({'method': 'raise_error', 'params': [], 'id': ''}) result = handler.handle_request(json) self.assertEquals(jsonrpc.loads(result), {'error': {'code': -32603, 'message': 'foobar'}, 'id':''})
def test_request_processing_kwargs(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'echo_kwargs', 'params': {'foobar': True}, 'id':''}) handler.handle_request(json) self.assertTrue(handler._request_translated) self.assertTrue(handler._found_service_method) self.assertTrue(handler._service_method_called) self.assertTrue(handler._result_translated)
def test_handle_request_MethodNotFound(self): handler = Handler(self.service) json = jsonrpc.dumps({'method': 'not_found', 'params': ['foobar'], 'id': ''}) result = handler.handle_request(json) self.assertEqual( jsonrpc.loads(result), { 'error': {'message': 'Method not found: not_found', 'code': -32601}, 'id': '', }, )
def test_MethodCallCallsService(self): s = jsonrpc.ServiceProxy("http://localhost/") self.respdata='{"result":"foobar","error":null,"id":""}' echo = s.echo("foobar") self.assertEquals(self.postdata, jsonrpc.dumps({"method":"echo", 'params':['foobar'], 'id':'jsonrpc'})) self.assertEquals(echo, 'foobar') self.respdata='{"result":null,"error":"MethodNotFound","id":""}' try: s.echo("foobar") except jsonrpc.JSONRPCException,e: self.assertEquals(e.error, "MethodNotFound")
def test_method_call_with_kwargs(self): s = jsonrpc.ServiceProxy("http://localhost/") http = MockHTTPConnection.current http.respdata = '{"result": {"foobar": true},"error":null,"id": 1}' echo = s.echo_kwargs(foobar=True) self.assertEquals(MockHTTPConnection.current.postdata, jsonrpc.dumps({ 'id': 1, 'jsonrpc': '2.0', 'method':'echo_kwargs', 'params': {'foobar': True}, })) self.assertEquals(echo, {'foobar': True})
def test_datetime_objects_roundtrip(self): """Test that we can serialize and un-serialize datetimes datetime objects are converted to strings when serializing, but we do not convert back to datetime. """ now = datetime.datetime.now() obj = {'time': now} value = jsonrpc.dumps(obj) unserialized = jsonrpc.loads(value) self.assertTrue(isinstance(unserialized['time'], basestring)) self.assertEqual(unserialized['time'], now.isoformat())
def test_datetime_objects_roundtrip(self): """Test that we can serialize and un-serialize datetimes datetime objects are converted to strings when serializing, but we do not convert back to datetime. """ now = datetime.datetime.now() obj = {'time': now} value = jsonrpc.dumps(obj) unserialized = jsonrpc.loads(value) self.assertTrue(isinstance(unserialized['time'], ustr)) self.assertEqual(unserialized['time'], now.isoformat())
def test_method_call_with_kwargs(self, mock_httplib): setup_mock_httplib(mock_httplib) s = jsonrpc.ServiceProxy("http://localhost/") http = MockHTTPConnection.current http.respdata = b'{"result": {"foobar": true},"error": null, "id": 1}' echo = s.echo_kwargs(foobar=True) expect = jsonrpc.dumps({ 'id': 1, 'jsonrpc': '2.0', 'method': 'echo_kwargs', 'params': { 'foobar': True }, }) assert expect == MockHTTPConnection.current.postdata assert echo == {'foobar': True}
def test_service_echoes_unicode(self): echo_data = {'hello': unichr(0x1234)} json = jsonrpc.dumps({ 'id': '', 'params': [echo_data], 'method': 'echo', }) fin=StringIO(json) fout=StringIO() req = ApacheRequestMockup(__file__, fin, fout) result = jsonrpc.handler(req) self.assertEquals(result, 'OK') data = fout.getvalue() expect = echo_data actual = jsonrpc.loads(data)['result'] self.assertEqual(expect, actual)
def test_MethodCallCallsService(self): s = jsonrpc.ServiceProxy("http://localhost/") self.respdata = '{"result":"foobar","error":null,"id":""}' echo = s.echo("foobar") self.assertEquals( self.postdata, jsonrpc.dumps({ "method": "echo", 'params': ['foobar'], 'id': 'jsonrpc' })) self.assertEquals(echo, 'foobar') self.respdata = '{"result":null,"error":"MethodNotFound","id":""}' try: s.echo("foobar") except jsonrpc.JSONRPCException, e: self.assertEquals(e.error, "MethodNotFound")
def test_service_echoes_unicode(self): echo_data = {'hello': uchr(0x1234)} json = jsonrpc.dumps({ 'id': '', 'params': [echo_data], 'method': 'echo' }) fin = BytesIO(encode(json)) fout = BytesIO() req = ApacheRequestMockup(__file__, fin, fout) result = jsonrpc.handler(req) self.assertEqual(result, 'OK') data = fout.getvalue() expect = echo_data actual = jsonrpc.loads(data)['result'] self.assertEqual(expect, actual)
def test_method_call(self): s = jsonrpc.ServiceProxy("http://localhost/") http = MockHTTPConnection.current http.respdata = '{"result":"foobar","error":null,"id": 1}' echo = s.echo('foobar') self.assertEquals(MockHTTPConnection.current.postdata, jsonrpc.dumps({ 'id': 1, 'jsonrpc': '2.0', 'method':'echo', 'params': ['foobar'], })) self.assertEquals(echo, 'foobar') http.respdata='{"result":null,"error":"MethodNotFound","id":""}' try: s.echo('foobar') except jsonrpc.JSONRPCException,e: self.assertEquals(e.error, 'MethodNotFound')
def test_method_call(self, mock_httplib): setup_mock_httplib(mock_httplib) s = jsonrpc.ServiceProxy("http://localhost/") http = MockHTTPConnection.current http.respdata = b'{"result":"foobar","error":null,"id": 1}' echo = s.echo('foobar') expect = jsonrpc.dumps({ 'id': 1, 'jsonrpc': '2.0', 'method': 'echo', 'params': ['foobar'] }) assert expect == MockHTTPConnection.current.postdata assert echo == 'foobar' http.respdata = b'{"result":null,"error":"MethodNotFound","id":""}' try: s.echo('foobar') except jsonrpc.JSONRPCException as e: assert e.error == 'MethodNotFound'
def test_StringEscapedUnicodeChars(self): json = jsonrpc.dumps(u'\0 \x19 \x20\u0130') self.assertJSON(json, u'"\\u0000 \\u0019 \u0130"')
def test_Dictionary(self): json = jsonrpc.dumps({'foobar': 'spam', 'a': [1, 2, 3]}) self.assertJSON(json, u'{"a":[1,2,3],"foobar":"spam"}')
def test_Array(self): json = jsonrpc.dumps([1, 2.3e45, 'foobar']) self.assertJSON(json, u'[1,2.3e+45,"foobar"]')
def test_FailOther(self): self.failUnlessRaises(jsonrpc.JSONEncodeException, lambda: jsonrpc.dumps(self))
nsrprice = max(nbttotal,0) / max(nsrtotal-1.1,1) print 'Auction Closing Price:',price,'NBT/NSR' #Payout and Sendback for i in usersnbt.iterkeys(): usersnbt[i]=usersnbt[i]*nbtprice for i in usersnsr.iterkeys(): usersnsr[i]=usersnsr[i]/nsrprice for i in usersnbtstore.iterkeys(): usersnbt[i]=usersnbtstore[i] for i in usersnsrstore.iterkeys(): usersnsr[i]=usersnsrstore[i] #Manysend Output sumnbt=0 sumnsr=0 outnbt = {} for addr in usersnbt: if usersnbt[addr] < 0.01: del(usersnbt[addr]) outnbt[addr] = float("%.8f" % usersnbt[addr]) sumnbt = sumnbt + usersnbt[addr] print jsonrpc.dumps(outnbt).replace(' ', '') outnsr = {} for addr in usersnsr: if usersnsr[addr] < 1: del(usersnsr[addr]) outnsr[addr] = float("%.8f" % usersnsr[addr]) sumnsr = sumnsr + usersnsr[addr] print jsonrpc.dumps(outnsr).replace(' ', '') print "Sum NBT to send:",sumnbt print "Sum NSR to send:",sumnsr
def test_handleRequestMethodRaiseError(self): handler=Handler(self.service) json=jsonrpc.dumps({"method":"raiseError", 'params':[], 'id':''}) result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), {"result":None, "error":{"name":"Exception", "message":"foobar"}, "id":""})
def test_String(self): json = jsonrpc.dumps("foobar") obj = jsonrpc.loads(json) self.assertEquals(obj, u"foobar")
def test_Boolean(self): json = jsonrpc.dumps(False) self.assertJSON(json, u'false') json = jsonrpc.dumps(True) self.assertJSON(json, u'true')
def test_String(self): json = jsonrpc.dumps('foobar') self.assertJSON(json, u'"foobar"') json = jsonrpc.dumps('foobar') self.assertJSON(json, u'"foobar"')
def test_StringEscapedChars(self): json = jsonrpc.dumps('\n \f \t \b \r \\ " /') self.assertJSON(json, u'"\\n \\f \\t \\b \\r \\\\ \\" \\/"')
def serializeValue(self, value): """ Serialize the given value to JSON. """ objects=self.makeObject(value) return dumps(objects)
sys.path.append("../") from common import * from jsonrpc import ServiceProxy from jsonrpc import JSONRPCException from jsonrpc import ServiceHandler import jsonrpc handler = ServiceHandler("") print "ready" mm = ModuleManager() print mm.getModuleInstance("TTS") print handler.listMethods() json = jsonrpc.dumps({ "method": "system.listMethods", "params": [''], 'id': '' }) print handler.handleRequest(json) json = jsonrpc.dumps({ "method": "modules.TTS.text_to_wave", "params": ["hello"], 'id': '' }) print handler.handleRequest(json) json = jsonrpc.dumps({ "method": "modules.Fortune.fortune_ml", "params": [u"ആന"], 'id': '' }) print handler.handleRequest(json)
def test_FailOther(self): self.failUnlessRaises(jsonrpc.JSONEncodeException, lambda:jsonrpc.dumps(self))
def test_Dictionary(self): json = jsonrpc.dumps({'foobar':'spam', 'a':[1,2,3]}) self.assertJSON(json, u'{"a":[1,2,3],"foobar":"spam"}')
def test_None(self): json = jsonrpc.dumps(None) self.assertJSON(json, u'null')
def test_handleRequestMethodNotAllowed(self): handler=Handler(self.service) json=jsonrpc.dumps({"method":"not_a_ServiceMethod", 'params':['foobar'], 'id':''}) result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), {"result":None, "error":{"name":"ServiceMethodNotFound", "message":""}, "id":""})
def test_handleRequestEcho(self): handler=Handler(self.service) json=jsonrpc.dumps({"method":"echo", 'params':['foobar'], 'id':''}) result = handler.handleRequest(json) self.assertEquals(jsonrpc.loads(result), jsonrpc.loads('{"result":"foobar", "error":null, "id":""}'))
def test_Number(self): json = jsonrpc.dumps(1) self.assertJSON(json, u'1') json = jsonrpc.dumps(0xffffffffffffffffffffffff) self.assertJSON(json, u'79228162514264337593543950335')