def setUp(self): self.method_handler = TestMethodHandler() self.request_handler = JSONRequestHandler(self.method_handler)
class JSONRequestHandlerTests(TestCase): def setUp(self): self.method_handler = TestMethodHandler() self.request_handler = JSONRequestHandler(self.method_handler) def test_request_dispatching(self): """ Requests will invoke the C{gotRequest} method of the method handler with the method name and parameters. """ request = { "method": "foo", "params": {"a": 1} } self.request_handler.handle(dumps(request)) self.assertEqual(self.method_handler.requests, [("foo", {"a": 1})]) def test_success_result_sending(self): """ Results returned from the gotRequest method are serialized and put into a JSON-RPC response object. """ request = {"method": "foo", "params": {}} handler_result = self.request_handler.handle(dumps(request)) handler_result.callback({"structured": "result!"}) ultimate = self.successResultOf(handler_result) expected = { "jsonrpc": "2.0", "result": {"structured": "result!"}, "id": 1 } self.assertEqual(loads(ultimate), expected) def test_error_result_sending(self): """ Failing Deferreds returned from the gotRequest method are serialized as JSON-RPC response objects with an "error" key. """ request = {"method": "foo", "params": {}} handler_result = self.request_handler.handle(dumps(request)) handler_result.errback(Failure(ZeroDivisionError("heyo"))) ultimate = self.successResultOf(handler_result) expected = { "jsonrpc": "2.0", "error": { "code": -32000, "message": "heyo", "data": ("Traceback (most recent call last):\n" "Failure: exceptions.ZeroDivisionError: heyo\n") }, "id": 1 } self.assertEqual(loads(ultimate), expected) def test_synchronous_error_result_sending(self): """ Synchronous exceptions from the method handler's gotRequest method are handled the same way as failures. """ request = {"method": "foo", "params": {}} def gotRequest(method, **params): 1 / 0 self.method_handler.gotRequest = gotRequest handler_result = self.request_handler.handle(dumps(request)) ultimate = self.successResultOf(handler_result) self.assertEqual(loads(ultimate)["error"]["message"], "integer division or modulo by zero") def test_error_result_sending_with_custom_json_error_code(self): """ If an exception has a C{json_rpc_error_code} attribute, it will be used as the JSON-RPC error code. """ exception = ZeroDivisionError("heyo") exception.json_rpc_error_code = 55 request = {"method": "foo", "params": {}} handler_result = self.request_handler.handle(dumps(request)) handler_result.errback(exception) ultimate = self.successResultOf(handler_result) self.assertEqual(loads(ultimate)["error"]["code"], 55)