Exemplo n.º 1
0
 def setUp(self):
     self.reqclient = RequestClient()
     self.jsonclient = JSONRPCClient(self.reqclient)
Exemplo n.º 2
0
class JSONRPCClientTests(TestCase):

    def setUp(self):
        self.reqclient = RequestClient()
        self.jsonclient = JSONRPCClient(self.reqclient)

    def test_request_generation(self):
        """
        Requests meet the JSON-RPC 2.0 specification requirements.
        """
        self.jsonclient.request("foo")
        expected = {
            "jsonrpc": "2.0",
            "method": "foo",
            "params": {},
            "id": 1
        }

        [request] = self.reqclient.requests
        self.assertEqual(loads(request.data), expected)

    def test_request_with_paramethers(self):
        """
        Parameters are encoded as attributes of a JSON object (in the parlance of the spec,
        "by-name").
        """
        self.jsonclient.request("foo", bar=1, baz="quux", obj={"hey": "there"}, arr=[1,2])
        expected = {
            "jsonrpc": "2.0",
            "method": "foo",
            "params": {"bar": 1, "baz": "quux", "obj": {"hey": "there"}, "arr": [1, 2]},
            "id": 1
        }

        [request] = self.reqclient.requests
        self.assertEqual(loads(request.data), expected)

    def test_success_response_handling(self):
        """
        The L{JSONRPCClient.request} method returns a Deferred which will fire with the "result"
        member of the JSON in the response.
        """
        request_result = self.jsonclient.request("foo")
        [request] = self.reqclient.requests
        request.response_deferred.callback(dumps({"result": "hey"}))
        self.assertEqual(self.successResultOf(request_result), "hey")

    def test_error_response_handling(self):
        """
        The L{JSONRPCClient.request} method returns a Deferred which will error out with a Failure
        derived from the "error" member of the JSON in the response.
        """
        request_result = self.jsonclient.request("foo")
        [request] = self.reqclient.requests
        request.response_deferred.callback(
            dumps({"error": {"code": 50, "message": "got an error!", "data": [1, 2, 3]}}))

        failure = self.failureResultOf(request_result)
        failure.trap(ServiceAPIError)
        self.assertEqual(failure.value.method, "foo")
        self.assertEqual(failure.value.code, 50)
        self.assertEqual(failure.value.message, "got an error!")
        self.assertEqual(failure.value.data, [1, 2, 3])