summaryrefslogtreecommitdiff
path: root/t/unit/async/aws/test_connection.py
blob: 5de76aa5c0c4fc3722d2944158c7574b78cd4145 (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
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals

import pytest

from contextlib import contextmanager

from case import Mock, patch
from vine.abstract import Thenable

from kombu.exceptions import HttpError
from kombu.five import WhateverIO

from kombu.async import http
from kombu.async.aws.connection import (
    AsyncHTTPConnection,
    AsyncHTTPSConnection,
    AsyncHTTPResponse,
    AsyncConnection,
    AsyncAWSAuthConnection,
    AsyncAWSQueryConnection,
)

from .case import AWSCase

from t.mocks import PromiseMock

# Not currently working
VALIDATES_CERT = False


def passthrough(*args, **kwargs):
    m = Mock(*args, **kwargs)

    def side_effect(ret):
        return ret
    m.side_effect = side_effect
    return m


class test_AsyncHTTPConnection(AWSCase):

    def test_AsyncHTTPSConnection(self):
        x = AsyncHTTPSConnection('aws.vandelay.com')
        assert x.scheme == 'https'

    def test_http_client(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        assert x.http_client is http.get_client()
        client = Mock(name='http_client')
        y = AsyncHTTPConnection('aws.vandelay.com', http_client=client)
        assert y.http_client is client

    def test_args(self):
        x = AsyncHTTPConnection(
            'aws.vandelay.com', 8083, strict=True, timeout=33.3,
        )
        assert x.host == 'aws.vandelay.com'
        assert x.port == 8083
        assert x.strict
        assert x.timeout == 33.3
        assert x.scheme == 'http'

    def test_request(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        x.request('PUT', '/importer-exporter')
        assert x.path == '/importer-exporter'
        assert x.method == 'PUT'

    def test_request_with_body_buffer(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        body = Mock(name='body')
        body.read.return_value = 'Vandelay Industries'
        x.request('PUT', '/importer-exporter', body)
        assert x.method == 'PUT'
        assert x.path == '/importer-exporter'
        assert x.body == 'Vandelay Industries'
        body.read.assert_called_with()

    def test_request_with_body_text(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        x.request('PUT', '/importer-exporter', 'Vandelay Industries')
        assert x.method == 'PUT'
        assert x.path == '/importer-exporter'
        assert x.body == 'Vandelay Industries'

    def test_request_with_headers(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        headers = {'Proxy': 'proxy.vandelay.com'}
        x.request('PUT', '/importer-exporter', None, headers)
        assert 'Proxy' in dict(x.headers)
        assert dict(x.headers)['Proxy'] == 'proxy.vandelay.com'

    def assert_request_created_with(self, url, conn):
        conn.Request.assert_called_with(
            url, method=conn.method,
            headers=http.Headers(conn.headers), body=conn.body,
            connect_timeout=conn.timeout, request_timeout=conn.timeout,
            validate_cert=VALIDATES_CERT,
        )

    def test_getrequest_AsyncHTTPSConnection(self):
        x = AsyncHTTPSConnection('aws.vandelay.com')
        x.Request = Mock(name='Request')
        x.getrequest()
        self.assert_request_created_with('https://aws.vandelay.com/', x)

    def test_getrequest_nondefault_port(self):
        x = AsyncHTTPConnection('aws.vandelay.com', port=8080)
        x.Request = Mock(name='Request')
        x.getrequest()
        self.assert_request_created_with('http://aws.vandelay.com:8080/', x)

        y = AsyncHTTPSConnection('aws.vandelay.com', port=8443)
        y.Request = Mock(name='Request')
        y.getrequest()
        self.assert_request_created_with('https://aws.vandelay.com:8443/', y)

    def test_getresponse(self):
        client = Mock(name='client')
        client.add_request = passthrough(name='client.add_request')
        x = AsyncHTTPConnection('aws.vandelay.com', http_client=client)
        x.Response = Mock(name='x.Response')
        request = x.getresponse()
        x.http_client.add_request.assert_called_with(request)
        assert isinstance(request, Thenable)
        assert isinstance(request.on_ready, Thenable)

        response = Mock(name='Response')
        request.on_ready(response)
        x.Response.assert_called_with(response)

    def test_getresponse__real_response(self):
        client = Mock(name='client')
        client.add_request = passthrough(name='client.add_request')
        callback = PromiseMock(name='callback')
        x = AsyncHTTPConnection('aws.vandelay.com', http_client=client)
        request = x.getresponse(callback)
        x.http_client.add_request.assert_called_with(request)

        buf = WhateverIO()
        buf.write('The quick brown fox jumps')

        headers = http.Headers({'X-Foo': 'Hello', 'X-Bar': 'World'})

        response = http.Response(request, 200, headers, buf)
        request.on_ready(response)
        callback.assert_called()
        wresponse = callback.call_args[0][0]

        assert wresponse.read() == 'The quick brown fox jumps'
        assert wresponse.status == 200
        assert wresponse.getheader('X-Foo') == 'Hello'
        assert dict(wresponse.getheaders()) == headers
        assert wresponse.msg
        assert wresponse.msg
        assert repr(wresponse)

    def test_repr(self):
        assert repr(AsyncHTTPConnection('aws.vandelay.com'))

    def test_putrequest(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        x.putrequest('UPLOAD', '/new')
        assert x.method == 'UPLOAD'
        assert x.path == '/new'

    def test_putheader(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        x.putheader('X-Foo', 'bar')
        assert x.headers == [('X-Foo', 'bar')]
        x.putheader('X-Bar', 'baz')
        assert x.headers == [
            ('X-Foo', 'bar'),
            ('X-Bar', 'baz'),
        ]

    def test_send(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        x.send('foo')
        assert x.body == 'foo'
        x.send('bar')
        assert x.body == 'foobar'

    def test_interface(self):
        x = AsyncHTTPConnection('aws.vandelay.com')
        assert x.set_debuglevel(3) is None
        assert x.connect() is None
        assert x.close() is None
        assert x.endheaders() is None


class test_AsyncHTTPResponse(AWSCase):

    def test_with_error(self):
        r = Mock(name='response')
        r.error = HttpError(404, 'NotFound')
        x = AsyncHTTPResponse(r)
        assert x.reason == 'NotFound'

        r.error = None
        assert not x.reason


class test_AsyncConnection(AWSCase):

    def test_when_boto_missing(self, patching):
        patching('kombu.async.aws.connection.boto', None)
        with pytest.raises(ImportError):
            AsyncConnection(Mock(name='client'))

    def test_client(self):
        x = AsyncConnection()
        assert x._httpclient is http.get_client()
        client = Mock(name='client')
        y = AsyncConnection(http_client=client)
        assert y._httpclient is client

    def test_get_http_connection(self):
        x = AsyncConnection(client=Mock(name='client'))
        assert isinstance(
            x.get_http_connection('aws.vandelay.com', 80, False),
            AsyncHTTPConnection,
        )
        assert isinstance(
            x.get_http_connection('aws.vandelay.com', 443, True),
            AsyncHTTPSConnection,
        )

        conn = x.get_http_connection('aws.vandelay.com', 80, False)
        assert conn.http_client is x._httpclient
        assert conn.host == 'aws.vandelay.com'
        assert conn.port == 80


class test_AsyncAWSAuthConnection(AWSCase):

    @patch('boto.log', create=True)
    def test_make_request(self, _):
        x = AsyncAWSAuthConnection('aws.vandelay.com',
                                   http_client=Mock(name='client'))
        Conn = x.get_http_connection = Mock(name='get_http_connection')
        callback = PromiseMock(name='callback')
        ret = x.make_request('GET', '/foo', callback=callback)
        assert ret is callback
        Conn.return_value.request.assert_called()
        Conn.return_value.getresponse.assert_called_with(
            callback=callback,
        )

    @patch('boto.log', create=True)
    def test_mexe(self, _):
        x = AsyncAWSAuthConnection('aws.vandelay.com',
                                   http_client=Mock(name='client'))
        Conn = x.get_http_connection = Mock(name='get_http_connection')
        request = x.build_base_http_request('GET', 'foo', '/auth')
        callback = PromiseMock(name='callback')
        x._mexe(request, callback=callback)
        Conn.return_value.request.assert_called_with(
            request.method, request.path, request.body, request.headers,
        )
        Conn.return_value.getresponse.assert_called_with(
            callback=callback,
        )

        no_callback_ret = x._mexe(request)
        # _mexe always returns promise
        assert isinstance(no_callback_ret, Thenable)

    @patch('boto.log', create=True)
    def test_mexe__with_sender(self, _):
        x = AsyncAWSAuthConnection('aws.vandelay.com',
                                   http_client=Mock(name='client'))
        Conn = x.get_http_connection = Mock(name='get_http_connection')
        request = x.build_base_http_request('GET', 'foo', '/auth')
        sender = Mock(name='sender')
        callback = PromiseMock(name='callback')
        x._mexe(request, sender=sender, callback=callback)
        sender.assert_called_with(
            Conn.return_value, request.method, request.path,
            request.body, request.headers, callback,
        )


class test_AsyncAWSQueryConnection(AWSCase):

    def setup(self):
        self.x = AsyncAWSQueryConnection('aws.vandelay.com',
                                         http_client=Mock(name='client'))

    @patch('boto.log', create=True)
    def test_make_request(self, _):
        _mexe, self.x._mexe = self.x._mexe, Mock(name='_mexe')
        Conn = self.x.get_http_connection = Mock(name='get_http_connection')
        callback = PromiseMock(name='callback')
        self.x.make_request(
            'action', {'foo': 1}, '/', 'GET', callback=callback,
        )
        self.x._mexe.assert_called()
        request = self.x._mexe.call_args[0][0]
        assert request.params['Action'] == 'action'
        assert request.params['Version'] == self.x.APIVersion

        ret = _mexe(request, callback=callback)
        assert ret is callback
        Conn.return_value.request.assert_called()
        Conn.return_value.getresponse.assert_called_with(
            callback=callback,
        )

    @patch('boto.log', create=True)
    def test_make_request__no_action(self, _):
        self.x._mexe = Mock(name='_mexe')
        self.x.get_http_connection = Mock(name='get_http_connection')
        callback = PromiseMock(name='callback')
        self.x.make_request(
            None, {'foo': 1}, '/', 'GET', callback=callback,
        )
        self.x._mexe.assert_called()
        request = self.x._mexe.call_args[0][0]
        assert 'Action' not in request.params
        assert request.params['Version'] == self.x.APIVersion

    @contextmanager
    def mock_sax_parse(self, parser):
        with patch('kombu.async.aws.connection.sax_parse') as sax_parse:
            with patch('kombu.async.aws.connection.XmlHandler') as xh:

                def effect(body, h):
                    return parser(xh.call_args[0][0], body, h)
                sax_parse.side_effect = effect
                yield (sax_parse, xh)
                sax_parse.assert_called()

    def Response(self, status, body):
        r = Mock(name='response')
        r.status = status
        r.read.return_value = body
        return r

    @contextmanager
    def mock_make_request(self):
        self.x.make_request = Mock(name='make_request')
        callback = PromiseMock(name='callback')
        yield callback

    def assert_make_request_called(self):
        self.x.make_request.assert_called()
        return self.x.make_request.call_args[1]['callback']

    def test_get_list(self):
        with self.mock_make_request() as callback:
            self.x.get_list('action', {'p': 3.3}, ['m'], callback=callback)
            on_ready = self.assert_make_request_called()

            def parser(dest, body, h):
                dest.append('hi')
                dest.append('there')

            with self.mock_sax_parse(parser):
                on_ready(self.Response(200, 'hello'))
            callback.assert_called_with(['hi', 'there'])

    def test_get_list_error(self):
        with self.mock_make_request() as callback:
            self.x.get_list('action', {'p': 3.3}, ['m'], callback=callback)
            on_ready = self.assert_make_request_called()

            with pytest.raises(self.x.ResponseError):
                on_ready(self.Response(404, 'Not found'))

    def test_get_object(self):
        with self.mock_make_request() as callback:

            class Result(object):
                parent = None
                value = None

                def __init__(self, parent):
                    self.parent = parent

            self.x.get_object('action', {'p': 3.3}, Result, callback=callback)
            on_ready = self.assert_make_request_called()

            def parser(dest, body, h):
                dest.value = 42

            with self.mock_sax_parse(parser):
                on_ready(self.Response(200, 'hello'))

            callback.assert_called()
            result = callback.call_args[0][0]
            assert result.value == 42
            assert result.parent

    def test_get_object_error(self):
        with self.mock_make_request() as callback:
            self.x.get_object('action', {'p': 3.3}, object, callback=callback)
            on_ready = self.assert_make_request_called()

            with pytest.raises(self.x.ResponseError):
                on_ready(self.Response(404, 'Not found'))

    def test_get_status(self):
        with self.mock_make_request() as callback:
            self.x.get_status('action', {'p': 3.3}, callback=callback)
            on_ready = self.assert_make_request_called()
            set_status_to = [True]

            def parser(dest, body, b):
                dest.status = set_status_to[0]

            with self.mock_sax_parse(parser):
                on_ready(self.Response(200, 'hello'))
            callback.assert_called_with(True)

            set_status_to[0] = False
            with self.mock_sax_parse(parser):
                on_ready(self.Response(200, 'hello'))
            callback.assert_called_with(False)

    def test_get_status_error(self):
        with self.mock_make_request() as callback:
            self.x.get_status('action', {'p': 3.3}, callback=callback)
            on_ready = self.assert_make_request_called()

            with pytest.raises(self.x.ResponseError):
                on_ready(self.Response(404, 'Not found'))

    def test_get_status_error_empty_body(self):
        with self.mock_make_request() as callback:
            self.x.get_status('action', {'p': 3.3}, callback=callback)
            on_ready = self.assert_make_request_called()

            with pytest.raises(self.x.ResponseError):
                on_ready(self.Response(200, ''))