summaryrefslogtreecommitdiff
path: root/kazoo/tests/test_threading_handler.py
blob: dbdccd754bf5239c6e58a2ae44377f364bc0a091 (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
import threading
import unittest

import mock
import pytest


class TestThreadingHandler(unittest.TestCase):
    def _makeOne(self, *args):
        from kazoo.handlers.threading import SequentialThreadingHandler

        return SequentialThreadingHandler(*args)

    def _getAsync(self, *args):
        from kazoo.handlers.threading import AsyncResult

        return AsyncResult

    def test_proper_threading(self):
        h = self._makeOne()
        h.start()
        # In Python 3.3 _Event is gone, before Event is function
        event_class = getattr(threading, '_Event', threading.Event)
        assert isinstance(h.event_object(), event_class)

    def test_matching_async(self):
        h = self._makeOne()
        h.start()
        async_result = self._getAsync()
        assert isinstance(h.async_result(), async_result)

    def test_exception_raising(self):
        h = self._makeOne()

        with pytest.raises(h.timeout_exception):
            raise h.timeout_exception("This is a timeout")

    def test_double_start_stop(self):
        h = self._makeOne()
        h.start()
        assert h._running is True
        h.start()
        h.stop()
        h.stop()
        assert h._running is False

    def test_huge_file_descriptor(self):
        import resource
        import socket
        from kazoo.handlers.utils import create_tcp_socket

        try:
            resource.setrlimit(resource.RLIMIT_NOFILE, (4096, 4096))
        except (ValueError, resource.error):
            self.skipTest('couldnt raise fd limit high enough')
        fd = 0
        socks = []
        while fd < 4000:
            sock = create_tcp_socket(socket)
            fd = sock.fileno()
            socks.append(sock)
        h = self._makeOne()
        h.start()
        h.select(socks, [], [], 0)
        h.stop()
        for sock in socks:
            sock.close()


class TestThreadingAsync(unittest.TestCase):
    def _makeOne(self, *args):
        from kazoo.handlers.threading import AsyncResult

        return AsyncResult(*args)

    def _makeHandler(self):
        from kazoo.handlers.threading import SequentialThreadingHandler

        return SequentialThreadingHandler()

    def test_ready(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        assert async_result.ready() is False
        async_result.set('val')
        assert async_result.ready() is True
        assert async_result.successful() is True
        assert async_result.exception is None

    def test_callback_queued(self):
        mock_handler = mock.Mock()
        mock_handler.completion_queue = mock.Mock()
        async_result = self._makeOne(mock_handler)

        async_result.rawlink(lambda a: a)
        async_result.set('val')

        assert mock_handler.completion_queue.put.called

    def test_set_exception(self):
        mock_handler = mock.Mock()
        mock_handler.completion_queue = mock.Mock()
        async_result = self._makeOne(mock_handler)
        async_result.rawlink(lambda a: a)
        async_result.set_exception(ImportError('Error occured'))

        assert isinstance(async_result.exception, ImportError)
        assert mock_handler.completion_queue.put.called

    def test_get_wait_while_setting(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []
        bv = threading.Event()
        cv = threading.Event()

        def wait_for_val():
            bv.set()
            val = async_result.get()
            lst.append(val)
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.start()
        bv.wait()

        async_result.set('fred')
        cv.wait()
        assert lst == ['fred']
        th.join()

    def test_get_with_nowait(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)
        timeout = self._makeHandler().timeout_exception

        with pytest.raises(timeout):
            async_result.get(block=False)

        with pytest.raises(timeout):
            async_result.get_nowait()

    def test_get_with_exception(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []
        bv = threading.Event()
        cv = threading.Event()

        def wait_for_val():
            bv.set()
            try:
                val = async_result.get()
            except ImportError:
                lst.append('oops')
            else:
                lst.append(val)
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.start()
        bv.wait()

        async_result.set_exception(ImportError)
        cv.wait()
        assert lst == ['oops']
        th.join()

    def test_wait(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []
        bv = threading.Event()
        cv = threading.Event()

        def wait_for_val():
            bv.set()
            try:
                val = async_result.wait(10)
            except ImportError:
                lst.append('oops')
            else:
                lst.append(val)
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.start()
        bv.wait(10)

        async_result.set("fred")
        cv.wait(15)
        assert lst == [True]
        th.join()

    def test_wait_race(self):
        """Test that there is no race condition in `IAsyncResult.wait()`.

        Guards against the reappearance of:
            https://github.com/python-zk/kazoo/issues/485
        """
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        async_result.set("immediate")

        cv = threading.Event()

        def wait_for_val():
            # NB: should not sleep
            async_result.wait(20)
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.daemon = True
        th.start()

        # if the wait() didn't sleep (correctly), cv will be set quickly
        # if it did sleep, the cv will not be set yet and this will timeout
        cv.wait(10)
        assert cv.is_set() is True
        th.join()

    def test_set_before_wait(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []
        cv = threading.Event()
        async_result.set('fred')

        def wait_for_val():
            val = async_result.get()
            lst.append(val)
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.start()
        cv.wait()
        assert lst == ['fred']
        th.join()

    def test_set_exc_before_wait(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []
        cv = threading.Event()
        async_result.set_exception(ImportError)

        def wait_for_val():
            try:
                val = async_result.get()
            except ImportError:
                lst.append('ooops')
            else:
                lst.append(val)
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.start()
        cv.wait()
        assert lst == ['ooops']
        th.join()

    def test_linkage(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)
        cv = threading.Event()

        lst = []

        def add_on():
            lst.append(True)

        def wait_for_val():
            async_result.get()
            cv.set()

        th = threading.Thread(target=wait_for_val)
        th.start()

        async_result.rawlink(add_on)
        async_result.set(b'fred')
        assert mock_handler.completion_queue.put.called
        async_result.unlink(add_on)
        cv.wait()
        assert async_result.value == b'fred'
        th.join()

    def test_linkage_not_ready(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []

        def add_on():
            lst.append(True)

        async_result.set('fred')
        assert not mock_handler.completion_queue.called
        async_result.rawlink(add_on)
        assert mock_handler.completion_queue.put.called

    def test_link_and_unlink(self):
        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []

        def add_on():
            lst.append(True)

        async_result.rawlink(add_on)
        assert not mock_handler.completion_queue.put.called
        async_result.unlink(add_on)
        async_result.set('fred')
        assert not mock_handler.completion_queue.put.called

    def test_captured_exception(self):
        from kazoo.handlers.utils import capture_exceptions

        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        @capture_exceptions(async_result)
        def exceptional_function():
            return 1 / 0

        exceptional_function()

        with pytest.raises(ZeroDivisionError):
            async_result.get()

    def test_no_capture_exceptions(self):
        from kazoo.handlers.utils import capture_exceptions

        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []

        def add_on():
            lst.append(True)

        async_result.rawlink(add_on)

        @capture_exceptions(async_result)
        def regular_function():
            return True

        regular_function()

        assert not mock_handler.completion_queue.put.called

    def test_wraps(self):
        from kazoo.handlers.utils import wrap

        mock_handler = mock.Mock()
        async_result = self._makeOne(mock_handler)

        lst = []

        def add_on(result):
            lst.append(result.get())

        async_result.rawlink(add_on)

        @wrap(async_result)
        def regular_function():
            return 'hello'

        assert regular_function() == 'hello'
        assert mock_handler.completion_queue.put.called
        assert async_result.get() == 'hello'

    def test_multiple_callbacks(self):
        mockback1 = mock.Mock(name='mockback1')
        mockback2 = mock.Mock(name='mockback2')
        handler = self._makeHandler()
        handler.start()

        async_result = self._makeOne(handler)
        async_result.rawlink(mockback1)
        async_result.rawlink(mockback2)
        async_result.set('howdy')
        async_result.wait()
        handler.stop()

        mockback2.assert_called_once_with(async_result)
        mockback1.assert_called_once_with(async_result)