summaryrefslogtreecommitdiff
path: root/tests.py
blob: 3ce10097367e66093dec57c5eb61a3779add9648 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
"""
The tests in this file compare the request and response objects
to the JSON-RPC 2.0 specification document, as well as testing
several internal components of the jsonrpclib library. Run this 
module without any parameters to run the tests.

Currently, this is not easily tested with a framework like 
nosetests because we spin up a daemon thread running the
the Server, and nosetests (at least in my tests) does not
ever "kill" the thread.

If you are testing jsonrpclib and the module doesn't return to
the command prompt after running the tests, you can hit 
"Ctrl-C" (or "Ctrl-Break" on Windows) and that should kill it.

TODO:
* Finish implementing JSON-RPC 2.0 Spec tests
* Implement JSON-RPC 1.0 tests
* Implement JSONClass, History, Config tests
"""

from jsonrpclib import Server, MultiCall, history, config, ProtocolError
from jsonrpclib import jsonrpc
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCRequestHandler
import socket
import tempfile
import unittest
import os
import time
try:
    import json
except ImportError:
    import simplejson as json
from threading import Thread

PORTS = range(8000, 8999)

class TestCompatibility(unittest.TestCase):
    
    client = None
    port = None
    server = None
    
    def setUp(self):
        self.port = PORTS.pop()
        self.server = server_set_up(addr=('', self.port))
        self.client = Server('http://localhost:%d' % self.port)
    
    # v1 tests forthcoming
    
    # Version 2.0 Tests
    def test_positional(self):
        """ Positional arguments in a single call """
        result = self.client.subtract(23, 42)
        self.assertTrue(result == -19)
        result = self.client.subtract(42, 23)
        self.assertTrue(result == 19)
        request = json.loads(history.request)
        response = json.loads(history.response)
        verify_request = {
            "jsonrpc": "2.0", "method": "subtract", 
            "params": [42, 23], "id": request['id']
        }
        verify_response = {
            "jsonrpc": "2.0", "result": 19, "id": request['id']
        }
        self.assertTrue(request == verify_request)
        self.assertTrue(response == verify_response)
        
    def test_named(self):
        """ Named arguments in a single call """
        result = self.client.subtract(subtrahend=23, minuend=42)
        self.assertTrue(result == 19)
        result = self.client.subtract(minuend=42, subtrahend=23)
        self.assertTrue(result == 19)
        request = json.loads(history.request)
        response = json.loads(history.response)
        verify_request = {
            "jsonrpc": "2.0", "method": "subtract", 
            "params": {"subtrahend": 23, "minuend": 42}, 
            "id": request['id']
        }
        verify_response = {
            "jsonrpc": "2.0", "result": 19, "id": request['id']
        }
        self.assertTrue(request == verify_request)
        self.assertTrue(response == verify_response)
        
    def test_notification(self):
        """ Testing a notification (response should be null) """
        result = self.client._notify.update(1, 2, 3, 4, 5)
        self.assertTrue(result == None)
        request = json.loads(history.request)
        response = history.response
        verify_request = {
            "jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]
        }
        verify_response = ''
        self.assertTrue(request == verify_request)
        self.assertTrue(response == verify_response)
        
    def test_non_existent_method(self):
        self.assertRaises(ProtocolError, self.client.foobar)
        request = json.loads(history.request)
        response = json.loads(history.response)
        verify_request = {
            "jsonrpc": "2.0", "method": "foobar", "id": request['id']
        }
        verify_response = {
            "jsonrpc": "2.0", 
            "error": 
                {"code": -32601, "message": response['error']['message']}, 
            "id": request['id']
        }
        self.assertTrue(request == verify_request)
        self.assertTrue(response == verify_response)
        
    def test_invalid_json(self):
        invalid_json = '{"jsonrpc": "2.0", "method": "foobar, '+ \
            '"params": "bar", "baz]'
        response = self.client._run_request(invalid_json)
        response = json.loads(history.response)
        verify_response = json.loads(
            '{"jsonrpc": "2.0", "error": {"code": -32700,'+
            ' "message": "Parse error."}, "id": null}'
        )
        verify_response['error']['message'] = response['error']['message']
        self.assertTrue(response == verify_response)
        
    def test_invalid_request(self):
        invalid_request = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}'
        response = self.client._run_request(invalid_request)
        response = json.loads(history.response)
        verify_response = json.loads(
            '{"jsonrpc": "2.0", "error": {"code": -32600, '+
            '"message": "Invalid Request."}, "id": null}'
        )
        verify_response['error']['message'] = response['error']['message']
        self.assertTrue(response == verify_response)
        
    def test_batch_invalid_json(self):
        invalid_request = '[ {"jsonrpc": "2.0", "method": "sum", '+ \
            '"params": [1,2,4], "id": "1"},{"jsonrpc": "2.0", "method" ]'
        response = self.client._run_request(invalid_request)
        response = json.loads(history.response)
        verify_response = json.loads(
            '{"jsonrpc": "2.0", "error": {"code": -32700,'+
            '"message": "Parse error."}, "id": null}'
        )
        verify_response['error']['message'] = response['error']['message']
        self.assertTrue(response == verify_response)
        
    def test_empty_array(self):
        invalid_request = '[]'
        response = self.client._run_request(invalid_request)
        response = json.loads(history.response)
        verify_response = json.loads(
            '{"jsonrpc": "2.0", "error": {"code": -32600, '+
            '"message": "Invalid Request."}, "id": null}'
        )
        verify_response['error']['message'] = response['error']['message']
        self.assertTrue(response == verify_response)
        
    def test_nonempty_array(self):
        invalid_request = '[1,2]'
        request_obj = json.loads(invalid_request)
        response = self.client._run_request(invalid_request)
        response = json.loads(history.response)
        self.assertTrue(len(response) == len(request_obj))
        for resp in response:
            verify_resp = json.loads(
                '{"jsonrpc": "2.0", "error": {"code": -32600, '+
                '"message": "Invalid Request."}, "id": null}'
            )
            verify_resp['error']['message'] = resp['error']['message']
            self.assertTrue(resp == verify_resp)
        
    def test_batch(self):
        multicall = MultiCall(self.client)
        multicall.sum(1,2,4)
        multicall._notify.notify_hello(7)
        multicall.subtract(42,23)
        multicall.foo.get(name='myself')
        multicall.get_data()
        job_requests = [j.request() for j in multicall._job_list]
        job_requests.insert(3, '{"foo": "boo"}')
        json_requests = '[%s]' % ','.join(job_requests)
        requests = json.loads(json_requests)
        responses = self.client._run_request(json_requests)
        
        verify_requests = json.loads("""[
            {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"},
            {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
            {"jsonrpc": "2.0", "method": "subtract", "params": [42,23], "id": "2"},
            {"foo": "boo"},
            {"jsonrpc": "2.0", "method": "foo.get", "params": {"name": "myself"}, "id": "5"},
            {"jsonrpc": "2.0", "method": "get_data", "id": "9"} 
        ]""")
            
        # Thankfully, these are in order so testing is pretty simple.
        verify_responses = json.loads("""[
            {"jsonrpc": "2.0", "result": 7, "id": "1"},
            {"jsonrpc": "2.0", "result": 19, "id": "2"},
            {"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request."}, "id": null},
            {"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found."}, "id": "5"},
            {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"}
        ]""")
        
        self.assertTrue(len(requests) == len(verify_requests))
        self.assertTrue(len(responses) == len(verify_responses))
        
        responses_by_id = {}
        response_i = 0
        
        for i in range(len(requests)):
            verify_request = verify_requests[i]
            request = requests[i]
            response = None
            if request.get('method') != 'notify_hello':
                req_id = request.get('id')
                if verify_request.has_key('id'):
                    verify_request['id'] = req_id
                verify_response = verify_responses[response_i]
                verify_response['id'] = req_id
                responses_by_id[req_id] = verify_response
                response_i += 1
                response = verify_response
            self.assertTrue(request == verify_request)
            
        for response in responses:
            verify_response = responses_by_id.get(response.get('id'))
            if verify_response.has_key('error'):
                verify_response['error']['message'] = \
                    response['error']['message']
            self.assertTrue(response == verify_response)
        
    def test_batch_notifications(self):    
        multicall = MultiCall(self.client)
        multicall._notify.notify_sum(1, 2, 4)
        multicall._notify.notify_hello(7)
        result = multicall()
        self.assertTrue(len(result) == 0)
        valid_request = json.loads(
            '[{"jsonrpc": "2.0", "method": "notify_sum", '+
            '"params": [1,2,4]},{"jsonrpc": "2.0", '+
            '"method": "notify_hello", "params": [7]}]'
        )
        request = json.loads(history.request)
        self.assertTrue(len(request) == len(valid_request))
        for i in range(len(request)):
            req = request[i]
            valid_req = valid_request[i]
            self.assertTrue(req == valid_req)
        self.assertTrue(history.response == '')
        
class InternalTests(unittest.TestCase):
    """ 
    These tests verify that the client and server portions of 
    jsonrpclib talk to each other properly.
    """    
    client = None
    server = None
    port = None
    
    def setUp(self):
        self.port = PORTS.pop()
        self.server = server_set_up(addr=('', self.port))
    
    def get_client(self):
        return Server('http://localhost:%d' % self.port)
        
    def get_multicall_client(self):
        server = self.get_client()
        return MultiCall(server)

    def test_connect(self):
        client = self.get_client()
        result = client.ping()
        self.assertTrue(result)
        
    def test_single_args(self):
        client = self.get_client()
        result = client.add(5, 10)
        self.assertTrue(result == 15)
        
    def test_single_kwargs(self):
        client = self.get_client()
        result = client.add(x=5, y=10)
        self.assertTrue(result == 15)
        
    def test_single_kwargs_and_args(self):
        client = self.get_client()
        self.assertRaises(ProtocolError, client.add, (5,), {'y':10})
        
    def test_single_notify(self):
        client = self.get_client()
        result = client._notify.add(5, 10)
        self.assertTrue(result == None)
    
    def test_single_namespace(self):
        client = self.get_client()
        response = client.namespace.sum(1,2,4)
        request = json.loads(history.request)
        response = json.loads(history.response)
        verify_request = {
            "jsonrpc": "2.0", "params": [1, 2, 4], 
            "id": "5", "method": "namespace.sum"
        }
        verify_response = {
            "jsonrpc": "2.0", "result": 7, "id": "5"
        }
        verify_request['id'] = request['id']
        verify_response['id'] = request['id']
        self.assertTrue(verify_request == request)
        self.assertTrue(verify_response == response)
        
    def test_multicall_success(self):
        multicall = self.get_multicall_client()
        multicall.ping()
        multicall.add(5, 10)
        multicall.namespace.sum([5, 10, 15])
        correct = [True, 15, 30]
        i = 0
        for result in multicall():
            self.assertTrue(result == correct[i])
            i += 1
            
    def test_multicall_success(self):
        multicall = self.get_multicall_client()
        for i in range(3):
            multicall.add(5, i)
        result = multicall()
        self.assertTrue(result[2] == 7)
    
    def test_multicall_failure(self):
        multicall = self.get_multicall_client()
        multicall.ping()
        multicall.add(x=5, y=10, z=10)
        raises = [None, ProtocolError]
        result = multicall()
        for i in range(2):
            if not raises[i]:
                result[i]
            else:
                def func():
                    return result[i]
                self.assertRaises(raises[i], func)
        
        
if jsonrpc.USE_UNIX_SOCKETS:
    # We won't do these tests unless Unix Sockets are supported
    
    class UnixSocketInternalTests(InternalTests):
        """
        These tests run the same internal communication tests, 
        but over a Unix socket instead of a TCP socket.
        """
        def setUp(self):
            suffix = "%d.sock" % PORTS.pop()
            
            # Open to safer, alternative processes 
            # for getting a temp file name...
            temp = tempfile.NamedTemporaryFile(
                suffix=suffix
            )
            self.port = temp.name
            temp.close()
            
            self.server = server_set_up(
                addr=self.port, 
                address_family=socket.AF_UNIX
            )

        def get_client(self):
            return Server('unix:/%s' % self.port)
            
        def tearDown(self):
            """ Removes the tempory socket file """
            os.unlink(self.port)
            
class UnixSocketErrorTests(unittest.TestCase):
    """ 
    Simply tests that the proper exceptions fire if 
    Unix sockets are attempted to be used on a platform
    that doesn't support them.
    """
    
    def setUp(self):
        self.original_value = jsonrpc.USE_UNIX_SOCKETS
        if (jsonrpc.USE_UNIX_SOCKETS):
            jsonrpc.USE_UNIX_SOCKETS = False
        
    def test_client(self):
        address = "unix://shouldnt/work.sock"
        self.assertRaises(
            jsonrpc.UnixSocketMissing,
            Server,
            address
        )
        
    def tearDown(self):
        jsonrpc.USE_UNIX_SOCKETS = self.original_value
        

""" Test Methods """
def subtract(minuend, subtrahend):
    """ Using the keywords from the JSON-RPC v2 doc """
    return minuend-subtrahend
    
def add(x, y):
    return x + y
    
def update(*args):
    return args
    
def summation(*args):
    return sum(args)
    
def notify_hello(*args):
    return args
    
def get_data():
    return ['hello', 5]
        
def ping():
    return True
        
def server_set_up(addr, address_family=socket.AF_INET):
    # Not sure this is a good idea to spin up a new server thread
    # for each test... but it seems to work fine.
    def log_request(self, *args, **kwargs):
        """ Making the server output 'quiet' """
        pass
    SimpleJSONRPCRequestHandler.log_request = log_request
    server = SimpleJSONRPCServer(addr, address_family=address_family)
    server.register_function(summation, 'sum')
    server.register_function(summation, 'notify_sum')
    server.register_function(notify_hello)
    server.register_function(subtract)
    server.register_function(update)
    server.register_function(get_data)
    server.register_function(add)
    server.register_function(ping)
    server.register_function(summation, 'namespace.sum')
    server_proc = Thread(target=server.serve_forever)
    server_proc.daemon = True
    server_proc.start()
    return server_proc

if __name__ == '__main__':
    print "==============================================================="
    print "  NOTE: There may be threading exceptions after tests finish.  "
    print "==============================================================="
    time.sleep(2)
    unittest.main()