summaryrefslogtreecommitdiff
path: root/src/etcd/tests/unit/test_old_request.py
blob: 9367ebd525d1516827d5aebf9b3e377cc4ca92df (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
import etcd
import unittest
try:
    import mock
except ImportError:
    from unittest import mock

from etcd import EtcdException


class FakeHTTPResponse(object):

    def __init__(self, status, data=''):
        self.status = status
        self.data = data.encode('utf-8')

    def getheaders(self):
        return {}

class TestClientRequest(unittest.TestCase):

    def test_machines(self):
        """ Can request machines """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200, data=
                                          "http://127.0.0.1:4002,"
                                          " http://127.0.0.1:4001,"
                                          " http://127.0.0.1:4003,"
                                          " http://127.0.0.1:4001")
        )

        assert client.machines == [
            'http://127.0.0.1:4002',
            'http://127.0.0.1:4001',
            'http://127.0.0.1:4003',
            'http://127.0.0.1:4001'
        ]

    def test_leader(self):
        """ Can request the leader """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200, "http://127.0.0.1:7002"))
        result = client.leader
        self.assertEquals('http://127.0.0.1:7002', result)

    def test_set(self):
        """ Can set a value """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(201,
                                          '{"action":"SET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"value":"test",'
                                          '"newKey":true,'
                                          '"expiration":"2013-09-14T00:56:59.316195568+02:00",'
                                          '"ttl":19,"modifiedIndex":183}}')
        )

        result = client.set('/testkey', 'test', ttl=19)

        self.assertEquals(
            etcd.EtcdResult(
                **{u'action': u'SET',
                   'node': {
                       u'expiration': u'2013-09-14T00:56:59.316195568+02:00',
                       u'modifiedIndex': 183,
                       u'key': u'/testkey',
                       u'newKey': True,
                       u'ttl': 19,
                       u'value': u'test'}}), result)

    def test_test_and_set(self):
        """ Can test and set a value """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"SET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"prevValue":"test",'
                                          '"value":"newvalue",'
                                          '"expiration":"2013-09-14T02:09:44.24390976+02:00",'
                                          '"ttl":49,"modifiedIndex":203}}')
        )
        result = client.test_and_set('/testkey', 'newvalue', 'test', ttl=19)
        self.assertEquals(
            etcd.EtcdResult(
                **{u'action': u'SET',
                   u'node': {
                       u'expiration': u'2013-09-14T02:09:44.24390976+02:00',
                       u'modifiedIndex': 203,
                       u'key': u'/testkey',
                       u'prevValue': u'test',
                       u'ttl': 49,
                       u'value': u'newvalue'}
                   }), result)

    def test_test_and_test_failure(self):
        """ Exception will be raised if prevValue != value in test_set """

        client = etcd.Client()
        client.api_execute = mock.Mock(
            side_effect=ValueError(
                'The given PrevValue is not equal'
                ' to the value of the key : TestAndSet: 1!=3'))
        try:
            result = client.test_and_set(
                '/testkey',
                'newvalue',
                'test', ttl=19)
        except ValueError as e:
            #from ipdb import set_trace; set_trace()
            self.assertEquals(
                'The given PrevValue is not equal'
                ' to the value of the key : TestAndSet: 1!=3', str(e))

    def test_delete(self):
        """ Can delete a value """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"DELETE",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"prevValue":"test",'
                                          '"expiration":"2013-09-14T01:06:35.5242587+02:00",'
                                          '"modifiedIndex":189}}')
        )
        result = client.delete('/testkey')
        self.assertEquals(etcd.EtcdResult(
            **{u'action': u'DELETE',
               u'node': {
                   u'expiration': u'2013-09-14T01:06:35.5242587+02:00',
                   u'modifiedIndex': 189,
                   u'key': u'/testkey',
                   u'prevValue': u'test'}
               }), result)

    def test_get(self):
        """ Can get a value """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"GET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"value":"test",'
                                          '"modifiedIndex":190}}')
        )

        result = client.get('/testkey')
        self.assertEquals(etcd.EtcdResult(
            **{u'action': u'GET',
               u'node': {
                   u'modifiedIndex': 190,
                   u'key': u'/testkey',
                   u'value': u'test'}
               }), result)

    def test_get_multi(self):
        """Can get multiple values"""
        pass

    def test_get_subdirs(self):
        """ Can understand dirs in results """
        pass

    def test_not_in(self):
        """ Can check if key is not in client """
        client = etcd.Client()
        client.get = mock.Mock(side_effect=etcd.EtcdKeyNotFound())
        result = '/testkey' not in client
        self.assertEquals(True, result)

    def test_in(self):
        """ Can check if key is in client """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"GET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"value":"test",'
                                          '"modifiedIndex":190}}')
        )
        result = '/testkey' in client

        self.assertEquals(True, result)

    def test_simple_watch(self):
        """ Can watch values """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"SET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"value":"test",'
                                          '"newKey":true,'
                                          '"expiration":"2013-09-14T01:35:07.623681365+02:00",'
                                          '"ttl":19,'
                                          '"modifiedIndex":192}}')
        )
        result = client.watch('/testkey')
        self.assertEquals(
            etcd.EtcdResult(
                **{u'action': u'SET',
                   u'node': {
                       u'expiration': u'2013-09-14T01:35:07.623681365+02:00',
                       u'modifiedIndex': 192,
                       u'key': u'/testkey',
                       u'newKey': True,
                       u'ttl': 19,
                       u'value': u'test'}
                   }), result)

    def test_index_watch(self):
        """ Can watch values from index """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"SET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"value":"test",'
                                          '"newKey":true,'
                                          '"expiration":"2013-09-14T01:35:07.623681365+02:00",'
                                          '"ttl":19,'
                                          '"modifiedIndex":180}}')
        )
        result = client.watch('/testkey', index=180)
        self.assertEquals(
            etcd.EtcdResult(
                **{u'action': u'SET',
                   u'node': {
                       u'expiration': u'2013-09-14T01:35:07.623681365+02:00',
                       u'modifiedIndex': 180,
                       u'key': u'/testkey',
                       u'newKey': True,
                       u'ttl': 19,
                       u'value': u'test'}
                   }), result)


class TestEventGenerator(object):

    def check_watch(self, result):
        assert etcd.EtcdResult(
            **{u'action': u'SET',
               u'node': {
                   u'expiration': u'2013-09-14T01:35:07.623681365+02:00',
                   u'modifiedIndex': 180,
                   u'key': u'/testkey',
                   u'newKey': True,
                   u'ttl': 19,
                   u'value': u'test'}
               }) == result

    def test_eternal_watch(self):
        """ Can watch values from generator """
        client = etcd.Client()
        client.api_execute = mock.Mock(
            return_value=FakeHTTPResponse(200,
                                          '{"action":"SET",'
                                          '"node": {'
                                          '"key":"/testkey",'
                                          '"value":"test",'
                                          '"newKey":true,'
                                          '"expiration":"2013-09-14T01:35:07.623681365+02:00",'
                                          '"ttl":19,'
                                          '"modifiedIndex":180}}')
        )
        for result in range(1, 5):
            result = next(client.eternal_watch('/testkey', index=180))
            yield self.check_watch, result


class TestClientApiExecutor(unittest.TestCase):

    def test_get(self):
        """ http get request """
        client = etcd.Client()
        response = FakeHTTPResponse(status=200, data='arbitrary json data')
        client.http.request = mock.Mock(return_value=response)
        result = client.api_execute('/v1/keys/testkey', client._MGET)
        self.assertEquals('arbitrary json data'.encode('utf-8'), result.data)

    def test_delete(self):
        """ http delete request """
        client = etcd.Client()
        response = FakeHTTPResponse(status=200, data='arbitrary json data')
        client.http.request = mock.Mock(return_value=response)
        result = client.api_execute('/v1/keys/testkey', client._MDELETE)
        self.assertEquals('arbitrary json data'.encode('utf-8'), result.data)

    def test_get_error(self):
        """ http get error request 101"""
        client = etcd.Client()
        response = FakeHTTPResponse(status=400,
                                    data='{"message": "message",'
                                    ' "cause": "cause",'
                                    ' "errorCode": 100}')
        client.http.request = mock.Mock(return_value=response)
        try:
            client.api_execute('/v2/keys/testkey', client._MGET)
            assert False
        except etcd.EtcdKeyNotFound as e:
            self.assertEquals(str(e), 'message : cause')

    def test_put(self):
        """ http put request """
        client = etcd.Client()
        response = FakeHTTPResponse(status=200, data='arbitrary json data')
        client.http.request_encode_body = mock.Mock(return_value=response)
        result = client.api_execute('/v2/keys/testkey', client._MPUT)
        self.assertEquals('arbitrary json data'.encode('utf-8'), result.data)

    def test_test_and_set_error(self):
        """ http post error request 101 """
        client = etcd.Client()
        response = FakeHTTPResponse(
            status=400,
            data='{"message": "message", "cause": "cause", "errorCode": 101}')
        client.http.request_encode_body = mock.Mock(return_value=response)
        payload = {'value': 'value', 'prevValue': 'oldValue', 'ttl': '60'}
        try:
            client.api_execute('/v2/keys/testkey', client._MPUT, payload)
            self.fail()
        except ValueError as e:
            self.assertEquals('message : cause', str(e))

    def test_set_error(self):
        """ http post error request 102 """
        client = etcd.Client()
        response = FakeHTTPResponse(
            status=400,
            data='{"message": "message", "cause": "cause", "errorCode": 102}')
        client.http.request_encode_body = mock.Mock(return_value=response)
        payload = {'value': 'value', 'prevValue': 'oldValue', 'ttl': '60'}
        try:
            client.api_execute('/v2/keys/testkey', client._MPUT, payload)
            self.fail()
        except KeyError as e:
            self.assertEquals('message : cause', str(e))

    def test_set_error(self):
        """ http post error request 102 """
        client = etcd.Client()
        response = FakeHTTPResponse(
            status=400,
            data='{"message": "message", "cause": "cause", "errorCode": 102}')
        client.http.request_encode_body = mock.Mock(return_value=response)
        payload = {'value': 'value', 'prevValue': 'oldValue', 'ttl': '60'}
        try:
            client.api_execute('/v2/keys/testkey', client._MPUT, payload)
            self.fail()
        except etcd.EtcdNotFile as e:
            self.assertEquals('message : cause', str(e))

    def test_get_error_unknown(self):
        """ http get error request unknown """
        client = etcd.Client()
        response = FakeHTTPResponse(status=400,
                                    data='{"message": "message",'
                                    ' "cause": "cause",'
                                    ' "errorCode": 42}')
        client.http.request = mock.Mock(return_value=response)
        try:
            client.api_execute('/v2/keys/testkey', client._MGET)
            self.fail()
        except etcd.EtcdException as e:
            self.assertTrue(
                str(e).startswith("Unable to decode server response"))

    def test_get_error_request_invalid(self):
        """ http get error request invalid """
        client = etcd.Client()
        response = FakeHTTPResponse(status=200,
                                    data='{){){)*garbage*')
        client.http.request = mock.Mock(return_value=response)
        self.assertRaises(etcd.EtcdException, client.get, '/testkey')

    def test_get_error_invalid(self):
        """ http get error request invalid """
        client = etcd.Client()
        response = FakeHTTPResponse(status=400,
                                    data='{){){)*garbage*')
        client.http.request = mock.Mock(return_value=response)
        self.assertRaises(etcd.EtcdException, client.api_execute,
                          '/v2/keys/testkey', client._MGET)