summaryrefslogtreecommitdiffhomepage
path: root/tests/unit/lib/test_rpc.py
blob: 2df123eeaa929e41177322ae303baea68d0643cb (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
# Copyright (C) 2013-2015 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013-2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import numbers
import socket
import struct
import unittest

from nose.tools import raises
import six

from ryu.lib import hub
from ryu.lib import rpc


class MyException(BaseException):
    pass


class Test_rpc(unittest.TestCase):
    """ Test case for ryu.lib.rpc
    """

    def _handle_request(self, m):
        e = self._server_endpoint
        msgid, method, params = m
        if method == 'resp':
            e.send_response(msgid, result=params[0])
        elif method == 'err':
            e.send_response(msgid, error=params[0])
        elif method == 'callback':
            n, cb, v = params
            assert n > 0
            self._requests.add(e.send_request(cb, [msgid, n, cb, v]))
        elif method == 'notify1':
            e.send_notification(params[1], params[2])
            e.send_response(msgid, result=params[0])
        elif method == 'shutdown':
            how = getattr(socket, params[0])
            self._server_sock.shutdown(how)
            e.send_response(msgid, result=method)
        else:
            raise Exception("unknown method %s" % method)

    def _handle_notification(self, m):
        e = self._server_endpoint
        method, params = m
        if method == 'notify2':
            e.send_notification(params[0], params[1])

    def _handle_response(self, m):
        e = self._server_endpoint
        msgid, error, result = m
        assert error is None
        self._requests.remove(msgid)
        omsgid, n, cb, v = result
        assert n >= 0
        if n == 0:
            e.send_response(omsgid, result=v)
        else:
            self._requests.add(e.send_request(cb, [omsgid, n, cb, v]))

    def setUp(self):
        self._server_sock, self._client_sock = socket.socketpair()
        table = {
            rpc.MessageType.REQUEST: self._handle_request,
            rpc.MessageType.RESPONSE: self._handle_response,
            rpc.MessageType.NOTIFY: self._handle_notification
        }
        self._requests = set()
        self._server_sock.setblocking(0)
        self._server_endpoint = rpc.EndPoint(self._server_sock,
                                             disp_table=table)
        self._server_thread = hub.spawn(self._server_endpoint.serve)

    def tearDown(self):
        hub.kill(self._server_thread)
        hub.joinall([self._server_thread])

    def test_0_call_str(self):
        c = rpc.Client(self._client_sock)
        obj = 'hoge'
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, str)

    def test_0_call_int(self):
        c = rpc.Client(self._client_sock)
        obj = 12345
        assert isinstance(obj, int)
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, numbers.Integral)

    def test_0_call_int2(self):
        c = rpc.Client(self._client_sock)
        obj = six.MAXSIZE
        assert isinstance(obj, int)
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, numbers.Integral)

    def test_0_call_int3(self):
        c = rpc.Client(self._client_sock)
        obj = - six.MAXSIZE - 1
        assert isinstance(obj, int)
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, numbers.Integral)

    def test_0_call_long(self):
        c = rpc.Client(self._client_sock)
        obj = 0xffffffffffffffff  # max value for msgpack
        assert isinstance(obj, numbers.Integral)
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, numbers.Integral)

    def test_0_call_long2(self):
        c = rpc.Client(self._client_sock)
        # Note: the python type of this value is int for 64-bit arch
        obj = -0x8000000000000000  # min value for msgpack
        assert isinstance(obj, numbers.Integral)
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, numbers.Integral)

    @raises(TypeError)
    def test_0_call_bytearray(self):
        c = rpc.Client(self._client_sock)
        obj = bytearray(b'foo')
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, str)

    def test_1_shutdown_wr(self):
        # test if the server shutdown on disconnect
        self._client_sock.shutdown(socket.SHUT_WR)
        hub.joinall([self._server_thread])

    @raises(EOFError)
    def test_1_client_shutdown_wr(self):
        c = rpc.Client(self._client_sock)
        c.call('shutdown', ['SHUT_WR'])

    def test_1_call_True(self):
        c = rpc.Client(self._client_sock)
        obj = True
        assert c.call('resp', [obj]) == obj

    def test_2_call_None(self):
        c = rpc.Client(self._client_sock)
        obj = None
        assert c.call('resp', [obj]) is None

    def test_2_call_False(self):
        c = rpc.Client(self._client_sock)
        obj = False
        assert c.call('resp', [obj]) == obj

    def test_2_call_dict(self):
        c = rpc.Client(self._client_sock)
        obj = {'hoge': 1, 'fuga': 2}
        assert c.call('resp', [obj]) == obj

    def test_2_call_empty_dict(self):
        c = rpc.Client(self._client_sock)
        obj = {}
        assert c.call('resp', [obj]) == obj

    def test_2_call_array(self):
        c = rpc.Client(self._client_sock)
        obj = [1, 2, 3, 4]
        assert c.call('resp', [obj]) == obj

    def test_2_call_empty_array(self):
        c = rpc.Client(self._client_sock)
        obj = []
        assert c.call('resp', [obj]) == obj

    def test_2_call_tuple(self):
        c = rpc.Client(self._client_sock)
        # Note: msgpack library implicitly convert a tuple into a list
        obj = (1, 2, 3)
        assert c.call('resp', [obj]) == list(obj)

    def test_2_call_unicode(self):
        c = rpc.Client(self._client_sock)
        # Note: We use encoding='utf-8' option in msgpack.Packer/Unpacker
        # in order to support Python 3.
        # With this option, utf-8 encoded bytes will be decoded into unicode
        # type in Python 2 and str type in Python 3.
        obj = u"hoge"
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, six.text_type)

    def test_2_call_small_binary(self):
        c = rpc.Client(self._client_sock)
        obj = struct.pack("100x")
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, six.binary_type)

    def test_3_call_complex(self):
        c = rpc.Client(self._client_sock)
        obj = [1, 'hoge', {'foo': 1, 3: 'bar'}]
        assert c.call('resp', [obj]) == obj

    @unittest.skip("doesn't work with eventlet 0.18 and later")
    def test_4_call_large_binary(self):
        c = rpc.Client(self._client_sock)
        obj = struct.pack("10000000x")
        result = c.call('resp', [obj])
        assert result == obj
        assert isinstance(result, six.binary_type)

    def test_0_notification1(self):
        l = []

        def callback(n):
            l.append(n)
        c = rpc.Client(self._client_sock, notification_callback=callback)
        obj = 'hogehoge'
        robj = 'fugafuga'
        assert c.call('notify1', [robj, 'notify_hoge', [obj]]) == robj
        c.receive_notification()
        assert len(l) == 1
        n = l.pop(0)
        assert n is not None
        method, params = n
        assert method == 'notify_hoge'
        assert params[0] == obj

    def test_0_notification2(self):
        l = []

        def callback(n):
            l.append(n)
        c = rpc.Client(self._client_sock, notification_callback=callback)
        obj = 'hogehogehoge'
        c.send_notification('notify2', ['notify_hoge', [obj]])
        c.receive_notification()
        assert len(l) == 1
        n = l.pop(0)
        assert n is not None
        method, params = n
        assert method == 'notify_hoge'
        assert params[0] == obj

    def test_0_call_error(self):
        c = rpc.Client(self._client_sock)
        obj = 'hoge'
        try:
            c.call('err', [obj])
            raise Exception("unexpected")
        except rpc.RPCError as e:
            assert e.get_value() == obj

    def test_0_call_error_notification(self):
        l = []

        def callback(n):
            l.append(n)
        c = rpc.Client(self._client_sock, notification_callback=callback)
        c.send_notification('notify2', ['notify_foo', []])
        hub.sleep(0.5)  # give the peer a chance to run
        obj = 'hoge'
        try:
            c.call('err', [obj])
            raise Exception("unexpected")
        except rpc.RPCError as e:
            assert e.get_value() == obj
        assert len(l) == 1
        n = l.pop(0)
        method, params = n
        assert method == 'notify_foo'
        assert params == []

    def test_4_async_call(self):
        """send a bunch of requests and then wait for responses
        """
        num_calls = 9999
        old_blocking = self._client_sock.setblocking(0)
        try:
            e = rpc.EndPoint(self._client_sock)
            s = set()
            for i in range(1, num_calls + 1):
                s.add(e.send_request('resp', [i]))
            sum = 0
            while s:
                e.block()
                e.process()
                done = set()
                for x in s:
                    r = e.get_response(x)
                    if r is None:
                        continue
                    res, error = r
                    assert error is None
                    sum += res
                    done.add(x)
                assert done.issubset(s)
                s -= done
            assert sum == (1 + num_calls) * num_calls / 2
        finally:
            self._client_sock.setblocking(old_blocking)

    def test_4_async_call2(self):
        """both sides act as rpc client and server
        """
        assert not self._requests
        num_calls = 100
        old_blocking = self._client_sock.setblocking(0)
        try:
            e = rpc.EndPoint(self._client_sock)
            s = set()
            for i in range(1, num_calls + 1):
                s.add(e.send_request('callback', [i, 'ourcallback', 0]))
            sum = 0
            while s:
                e.block()
                e.process()
                done = set()
                for x in s:
                    r = e.get_response(x)
                    if r is None:
                        continue
                    res, error = r
                    assert error is None
                    sum += res
                    done.add(x)
                assert done.issubset(s)
                s -= done
                r = e.get_request()
                if r is not None:
                    msgid, method, params = r
                    assert method == 'ourcallback'
                    omsgid, n, cb, v = params
                    assert omsgid in s
                    assert cb == 'ourcallback'
                    assert n > 0
                    e.send_response(msgid, result=[omsgid, n - 1, cb, v + 1])
            assert sum == (1 + num_calls) * num_calls / 2
        finally:
            self._client_sock.setblocking(old_blocking)
        assert not self._requests