File: test_tornado.py

package info (click to toggle)
python-consul 0.7.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 47,052 kB
  • sloc: python: 3,081; makefile: 147
file content (381 lines) | stat: -rw-r--r-- 12,294 bytes parent folder | download | duplicates (3)
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
import struct
import time

import pytest
import six

from tornado import ioloop
from tornado import gen

import consul
import consul.tornado


Check = consul.Check


@pytest.fixture
def loop():
    loop = ioloop.IOLoop()
    loop.make_current()
    return loop


def sleep(loop, s):
    result = gen.Future()
    loop.add_timeout(
        time.time()+s, lambda: result.set_result(None))
    return result


class TestConsul(object):
    def test_kv(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            index, data = yield c.kv.get('foo')
            assert data is None
            response = yield c.kv.put('foo', 'bar')
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Value'] == six.b('bar')
            loop.stop()
        loop.run_sync(main)

    def test_kv_binary(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            yield c.kv.put('foo', struct.pack('i', 1000))
            index, data = yield c.kv.get('foo')
            assert struct.unpack('i', data['Value']) == (1000,)
            loop.stop()
        loop.run_sync(main)

    def test_kv_missing(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def main():
            yield c.kv.put('index', 'bump')
            index, data = yield c.kv.get('foo')
            assert data is None
            index, data = yield c.kv.get('foo', index=index)
            assert data['Value'] == six.b('bar')
            loop.stop()

        @gen.coroutine
        def put():
            yield c.kv.put('foo', 'bar')

        loop.add_timeout(time.time()+(2.0/100), put)
        loop.run_sync(main)

    def test_kv_put_flags(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            yield c.kv.put('foo', 'bar')
            index, data = yield c.kv.get('foo')
            assert data['Flags'] == 0

            response = yield c.kv.put('foo', 'bar', flags=50)
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Flags'] == 50
            loop.stop()
        loop.run_sync(main)

    def test_kv_delete(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            yield c.kv.put('foo1', '1')
            yield c.kv.put('foo2', '2')
            yield c.kv.put('foo3', '3')
            index, data = yield c.kv.get('foo', recurse=True)
            assert [x['Key'] for x in data] == ['foo1', 'foo2', 'foo3']

            response = yield c.kv.delete('foo2')
            assert response is True
            index, data = yield c.kv.get('foo', recurse=True)
            assert [x['Key'] for x in data] == ['foo1', 'foo3']
            response = yield c.kv.delete('foo', recurse=True)
            assert response is True
            index, data = yield c.kv.get('foo', recurse=True)
            assert data is None
            loop.stop()
        loop.run_sync(main)

    def test_kv_subscribe(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def get():
            index, data = yield c.kv.get('foo')
            assert data is None
            index, data = yield c.kv.get('foo', index=index)
            assert data['Value'] == six.b('bar')
            loop.stop()

        @gen.coroutine
        def put():
            response = yield c.kv.put('foo', 'bar')
            assert response is True

        loop.add_timeout(time.time()+(1.0/100), put)
        loop.run_sync(get)

    def test_kv_encoding(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)

            # test binary
            response = yield c.kv.put('foo', struct.pack('i', 1000))
            assert response is True
            index, data = yield c.kv.get('foo')
            assert struct.unpack('i', data['Value']) == (1000,)

            # test unicode
            response = yield c.kv.put('foo', u'bar')
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Value'] == six.b('bar')

            # test empty-string comes back as `None`
            response = yield c.kv.put('foo', '')
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Value'] is None

            # test None
            response = yield c.kv.put('foo', None)
            assert response is True
            index, data = yield c.kv.get('foo')
            assert data['Value'] is None

            # check unencoded values raises assert
            try:
                yield c.kv.put('foo', {1: 2})
            except AssertionError:
                raised = True
            assert raised

            loop.stop()
        loop.run_sync(main)

    def test_agent_services(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)
            services = yield c.agent.services()
            del services['consul']
            assert services == {}
            response = yield c.agent.service.register('foo')
            assert response is True
            services = yield c.agent.services()
            del services['consul']
            assert services == {
                'foo': {
                    'Port': 0,
                    'ID': 'foo',
                    'CreateIndex': 0,
                    'ModifyIndex': 0,
                    'EnableTagOverride': False,
                    'Service': 'foo',
                    'Tags': None,
                    'Address': ''}, }
            response = yield c.agent.service.deregister('foo')
            assert response is True
            services = yield c.agent.services()
            del services['consul']
            assert services == {}
            loop.stop()
        loop.run_sync(main)

    def test_catalog(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def nodes():
            index, nodes = yield c.catalog.nodes()
            assert len(nodes) == 1
            current = nodes[0]

            index, nodes = yield c.catalog.nodes(index=index)
            nodes.remove(current)
            assert [x['Node'] for x in nodes] == ['n1']

            index, nodes = yield c.catalog.nodes(index=index)
            nodes.remove(current)
            assert [x['Node'] for x in nodes] == []
            loop.stop()

        @gen.coroutine
        def register():
            response = yield c.catalog.register('n1', '10.1.10.11')
            assert response is True
            yield sleep(loop, 50/1000.0)
            response = yield c.catalog.deregister('n1')
            assert response is True

        loop.add_timeout(time.time()+(1.0/100), register)
        loop.run_sync(nodes)

    def test_health_service(self, loop, consul_port):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(port=consul_port)

            # check there are no nodes for the service 'foo'
            index, nodes = yield c.health.service('foo')
            assert nodes == []

            # register two nodes, one with a long ttl, the other shorter
            yield c.agent.service.register(
                'foo', service_id='foo:1', check=Check.ttl('10s'))
            yield c.agent.service.register(
                'foo', service_id='foo:2', check=Check.ttl('100ms'))

            time.sleep(30/1000.0)

            # check the nodes show for the /health/service endpoint
            index, nodes = yield c.health.service('foo')
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # but that they aren't passing their health check
            index, nodes = yield c.health.service('foo', passing=True)
            assert nodes == []

            # ping the two node's health check
            yield c.agent.check.ttl_pass('service:foo:1')
            yield c.agent.check.ttl_pass('service:foo:2')

            time.sleep(50/1000.0)

            # both nodes are now available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # wait until the short ttl node fails
            time.sleep(120/1000.0)

            # only one node available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == ['foo:1']

            # ping the failed node's health check
            yield c.agent.check.ttl_pass('service:foo:2')

            time.sleep(30/1000.0)

            # check both nodes are available
            index, nodes = yield c.health.service('foo', passing=True)
            assert [node['Service']['ID'] for node in nodes] == \
                ['foo:1', 'foo:2']

            # deregister the nodes
            yield c.agent.service.deregister('foo:1')
            yield c.agent.service.deregister('foo:2')

            time.sleep(30/1000.0)

            index, nodes = yield c.health.service('foo')
            assert nodes == []

        loop.run_sync(main)

    def test_health_service_subscribe(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        class Config(object):
            pass

        config = Config()

        @gen.coroutine
        def monitor():
            yield c.agent.service.register(
                'foo', service_id='foo:1', check=Check.ttl('40ms'))
            index = None
            while True:
                index, nodes = yield c.health.service(
                    'foo', index=index, passing=True)
                config.nodes = [node['Service']['ID'] for node in nodes]

        @gen.coroutine
        def keepalive():
            # give the monitor a chance to register the service
            yield sleep(loop, 50/1000.0)
            assert config.nodes == []

            # ping the service's health check
            yield c.agent.check.ttl_pass('service:foo:1')
            yield sleep(loop, 30/1000.0)
            assert config.nodes == ['foo:1']

            # the service should fail
            yield sleep(loop, 60/1000.0)
            assert config.nodes == []

            yield c.agent.service.deregister('foo:1')
            loop.stop()

        loop.add_callback(monitor)
        loop.run_sync(keepalive)

    def test_session(self, loop, consul_port):
        c = consul.tornado.Consul(port=consul_port)

        @gen.coroutine
        def monitor():
            index, services = yield c.session.list()
            assert services == []
            yield sleep(loop, 20/1000.0)

            index, services = yield c.session.list(index=index)
            assert len(services)

            index, services = yield c.session.list(index=index)
            assert services == []
            loop.stop()

        @gen.coroutine
        def register():
            session_id = yield c.session.create()
            yield sleep(loop, 50/1000.0)
            response = yield c.session.destroy(session_id)
            assert response is True

        loop.add_timeout(time.time()+(1.0/100), register)
        loop.run_sync(monitor)

    def test_acl(self, loop, acl_consul):
        @gen.coroutine
        def main():
            c = consul.tornado.Consul(
                port=acl_consul.port, token=acl_consul.token)

            rules = """
                key "" {
                    policy = "read"
                }
                key "private/" {
                    policy = "deny"
                }
            """
            token = yield c.acl.create(rules=rules)

            try:
                yield c.acl.list(token=token)
            except consul.ACLPermissionDenied:
                raised = True
            assert raised

            destroyed = yield c.acl.destroy(token)
            assert destroyed is True
            loop.stop()
        loop.run_sync(main)