File: test_proxy_functional.py

package info (click to toggle)
python-aiohttp 1.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,288 kB
  • ctags: 4,380
  • sloc: python: 27,221; makefile: 236
file content (500 lines) | stat: -rw-r--r-- 15,087 bytes parent folder | download
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
import asyncio
from functools import partial
from unittest import mock

import pytest
from yarl import URL

import aiohttp
import aiohttp.helpers
import aiohttp.web


@pytest.fixture
def proxy_test_server(raw_test_server, loop, monkeypatch):
    """Handle all proxy requests and imitate remote server response."""

    _patch_ssl_transport(monkeypatch)

    default_response = dict(
        status=200,
        headers=None,
        body=None)

    @asyncio.coroutine
    def proxy_handler(request, proxy_mock):
        proxy_mock.request = request
        proxy_mock.requests_list.append(request)

        response = default_response.copy()
        if isinstance(proxy_mock.return_value, dict):
            response.update(proxy_mock.return_value)

        if request.method == 'CONNECT':
            response['body'] = None

        return aiohttp.web.Response(**response)

    @asyncio.coroutine
    def proxy_server():
        proxy_mock = mock.Mock()
        proxy_mock.request = None
        proxy_mock.requests_list = []

        handler = partial(proxy_handler, proxy_mock=proxy_mock)
        server = yield from raw_test_server(handler)

        proxy_mock.server = server
        proxy_mock.url = server.make_url('/')

        return proxy_mock

    return proxy_server


@asyncio.coroutine
def _request(method, url, loop=None, **kwargs):
    with aiohttp.ClientSession(loop=loop) as client:
        resp = yield from client.request(method, url, **kwargs)
        yield from resp.release()
        return resp


@pytest.fixture()
def get_request(loop):
    return partial(_request, method='GET', loop=loop)


@asyncio.coroutine
def test_proxy_http_absolute_path(proxy_test_server, get_request):
    url = 'http://aiohttp.io/path?query=yes'
    proxy = yield from proxy_test_server()

    yield from get_request(url=url, proxy=proxy.url)

    assert len(proxy.requests_list) == 1
    assert proxy.request.method == 'GET'
    assert proxy.request.host == 'aiohttp.io'
    assert proxy.request.path_qs == 'http://aiohttp.io/path?query=yes'


@asyncio.coroutine
def test_proxy_http_raw_path(proxy_test_server, get_request):
    url = 'http://aiohttp.io:2561/space sheep?q=can:fly'
    raw_url = 'http://aiohttp.io:2561/space%20sheep?q=can:fly'
    proxy = yield from proxy_test_server()

    yield from get_request(url=url, proxy=proxy.url)

    assert proxy.request.host == 'aiohttp.io:2561'
    assert proxy.request.path_qs == raw_url


@asyncio.coroutine
def test_proxy_http_idna_support(proxy_test_server, get_request):
    url = 'http://éé.com/'
    raw_url = 'http://xn--9caa.com/'
    proxy = yield from proxy_test_server()

    yield from get_request(url=url, proxy=proxy.url)

    assert proxy.request.host == 'xn--9caa.com'
    assert proxy.request.path_qs == raw_url


@asyncio.coroutine
def test_proxy_http_connection_error(get_request):
    url = 'http://aiohttp.io/path'
    proxy_url = 'http://localhost:2242/'

    with pytest.raises(aiohttp.ProxyConnectionError):
        yield from get_request(url=url, proxy=proxy_url)


@asyncio.coroutine
def test_proxy_http_bad_response(proxy_test_server, get_request):
    url = 'http://aiohttp.io/path'
    proxy = yield from proxy_test_server()
    proxy.return_value = dict(
        status=502,
        headers={'Proxy-Agent': 'TestProxy'})

    resp = yield from get_request(url=url, proxy=proxy.url)

    assert resp.status == 502
    assert resp.headers['Proxy-Agent'] == 'TestProxy'


@asyncio.coroutine
def test_proxy_http_auth(proxy_test_server, get_request):
    url = 'http://aiohttp.io/path'
    proxy = yield from proxy_test_server()

    yield from get_request(url=url, proxy=proxy.url)

    assert 'Authorization' not in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers

    auth = aiohttp.helpers.BasicAuth('user', 'pass')
    yield from get_request(url=url, auth=auth, proxy=proxy.url)

    assert 'Authorization' in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers

    yield from get_request(url=url, proxy_auth=auth, proxy=proxy.url)

    assert 'Authorization' not in proxy.request.headers
    assert 'Proxy-Authorization' in proxy.request.headers

    yield from get_request(url=url, auth=auth,
                           proxy_auth=auth, proxy=proxy.url)

    assert 'Authorization' in proxy.request.headers
    assert 'Proxy-Authorization' in proxy.request.headers


@asyncio.coroutine
def test_proxy_http_auth_utf8(proxy_test_server, get_request):
    url = 'http://aiohttp.io/path'
    auth = aiohttp.helpers.BasicAuth('юзер', 'пасс', 'utf-8')
    proxy = yield from proxy_test_server()

    yield from get_request(url=url, auth=auth, proxy=proxy.url)

    assert 'Authorization' in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers


@asyncio.coroutine
def test_proxy_http_auth_from_url(proxy_test_server, get_request):
    url = 'http://aiohttp.io/path'
    proxy = yield from proxy_test_server()

    auth_url = URL(url).with_user('user').with_password('pass')
    yield from get_request(url=auth_url, proxy=proxy.url)

    assert 'Authorization' in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers

    proxy_url = URL(proxy.url).with_user('user').with_password('pass')
    yield from get_request(url=url, proxy=proxy_url)

    assert 'Authorization' not in proxy.request.headers
    assert 'Proxy-Authorization' in proxy.request.headers


@asyncio.coroutine
def test_proxy_http_acquired_cleanup(proxy_test_server, loop):
    url = 'http://aiohttp.io/path'
    key = ('aiohttp.io', 80, False)

    conn = aiohttp.TCPConnector(loop=loop)
    sess = aiohttp.ClientSession(connector=conn, loop=loop)
    proxy = yield from proxy_test_server()

    assert 0 == len(conn._acquired.keys())

    @asyncio.coroutine
    def request():
        resp = yield from sess.get(url, proxy=proxy.url)

        assert 1 == len(conn._acquired.keys())
        assert 1 == len(conn._acquired[key])

        yield from resp.release()

    yield from request()

    assert 0 == len(conn._acquired[key])

    yield from sess.close()


@asyncio.coroutine
def test_proxy_http_acquired_cleanup_force(proxy_test_server, loop):
    url = 'http://aiohttp.io/path'
    key = ('aiohttp.io', 80, False)

    conn = aiohttp.TCPConnector(force_close=True, loop=loop)
    sess = aiohttp.ClientSession(connector=conn, loop=loop)
    proxy = yield from proxy_test_server()

    assert 0 == len(conn._acquired.keys())

    @asyncio.coroutine
    def request():
        resp = yield from sess.get(url, proxy=proxy.url)

        assert 1 == len(conn._acquired.keys())
        assert 1 == len(conn._acquired[key])

        yield from resp.release()

    yield from request()

    assert 0 == len(conn._acquired[key])

    yield from sess.close()


@asyncio.coroutine
def test_proxy_http_multi_conn_limit(proxy_test_server, loop):
    url = 'http://aiohttp.io/path'
    limit, multi_conn_num = 1, 5

    conn = aiohttp.TCPConnector(limit=limit, loop=loop)
    sess = aiohttp.ClientSession(connector=conn, loop=loop)
    proxy = yield from proxy_test_server()

    current_pid = None

    @asyncio.coroutine
    def request(pid):
        # process requests only one by one
        nonlocal current_pid

        resp = yield from sess.get(url, proxy=proxy.url)

        current_pid = pid
        yield from asyncio.sleep(0.2, loop=loop)
        assert current_pid == pid

        yield from resp.release()
        return resp

    requests = [request(pid) for pid in range(multi_conn_num)]
    responses = yield from asyncio.gather(*requests, loop=loop)

    assert len(responses) == multi_conn_num
    assert set(resp.status for resp in responses) == {200}

    yield from sess.close()


@asyncio.coroutine
def test_proxy_https_connect(proxy_test_server, get_request):
    proxy = yield from proxy_test_server()
    url = 'https://www.google.com.ua/search?q=aiohttp proxy'

    yield from get_request(url=url, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert connect.method == 'CONNECT'
    assert connect.path == 'www.google.com.ua:443'
    assert connect.host == 'www.google.com.ua'

    assert proxy.request.host == 'www.google.com.ua'
    assert proxy.request.path_qs == '/search?q=aiohttp+proxy'


@asyncio.coroutine
def test_proxy_https_connect_with_port(proxy_test_server, get_request):
    proxy = yield from proxy_test_server()
    url = 'https://secure.aiohttp.io:2242/path'

    yield from get_request(url=url, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert connect.method == 'CONNECT'
    assert connect.path == 'secure.aiohttp.io:2242'
    assert connect.host == 'secure.aiohttp.io:2242'

    assert proxy.request.host == 'secure.aiohttp.io:2242'
    assert proxy.request.path_qs == '/path'


@asyncio.coroutine
def test_proxy_https_send_body(proxy_test_server, loop):
    sess = aiohttp.ClientSession(loop=loop)
    proxy = yield from proxy_test_server()
    proxy.return_value = {'status': 200, 'body': b'1'*(2**20)}
    url = 'https://www.google.com.ua/search?q=aiohttp proxy'

    resp = yield from sess.get(url, proxy=proxy.url)
    body = yield from resp.read()
    yield from resp.release()
    yield from sess.close()

    assert body == b'1'*(2**20)


@asyncio.coroutine
def test_proxy_https_idna_support(proxy_test_server, get_request):
    url = 'https://éé.com/'
    proxy = yield from proxy_test_server()

    yield from get_request(url=url, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert connect.method == 'CONNECT'
    assert connect.path == 'xn--9caa.com:443'
    assert connect.host == 'xn--9caa.com'


@asyncio.coroutine
def test_proxy_https_connection_error(get_request):
    url = 'https://secure.aiohttp.io/path'
    proxy_url = 'http://localhost:2242/'

    with pytest.raises(aiohttp.ProxyConnectionError):
        yield from get_request(url=url, proxy=proxy_url)


@asyncio.coroutine
def test_proxy_https_bad_response(proxy_test_server, get_request):
    url = 'https://secure.aiohttp.io/path'
    proxy = yield from proxy_test_server()
    proxy.return_value = dict(
        status=502,
        headers={'Proxy-Agent': 'TestProxy'})

    with pytest.raises(aiohttp.HttpProxyError):
        yield from get_request(url=url, proxy=proxy.url)

    assert len(proxy.requests_list) == 1
    assert proxy.request.method == 'CONNECT'
    assert proxy.request.path == 'secure.aiohttp.io:443'


@asyncio.coroutine
def test_proxy_https_auth(proxy_test_server, get_request):
    url = 'https://secure.aiohttp.io/path'
    auth = aiohttp.helpers.BasicAuth('user', 'pass')

    proxy = yield from proxy_test_server()
    yield from get_request(url=url, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert 'Authorization' not in connect.headers
    assert 'Proxy-Authorization' not in connect.headers
    assert 'Authorization' not in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers

    proxy = yield from proxy_test_server()
    yield from get_request(url=url, auth=auth, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert 'Authorization' not in connect.headers
    assert 'Proxy-Authorization' not in connect.headers
    assert 'Authorization' in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers

    proxy = yield from proxy_test_server()
    yield from get_request(url=url, proxy_auth=auth, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert 'Authorization' not in connect.headers
    assert 'Proxy-Authorization' in connect.headers
    assert 'Authorization' not in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers

    proxy = yield from proxy_test_server()
    yield from get_request(url=url, auth=auth,
                           proxy_auth=auth, proxy=proxy.url)

    connect = proxy.requests_list[0]
    assert 'Authorization' not in connect.headers
    assert 'Proxy-Authorization' in connect.headers
    assert 'Authorization' in proxy.request.headers
    assert 'Proxy-Authorization' not in proxy.request.headers


@asyncio.coroutine
def test_proxy_https_acquired_cleanup(proxy_test_server, loop):
    url = 'https://secure.aiohttp.io/path'
    key = ('secure.aiohttp.io', 443, True)

    conn = aiohttp.TCPConnector(loop=loop)
    sess = aiohttp.ClientSession(connector=conn, loop=loop)
    proxy = yield from proxy_test_server()

    assert 0 == len(conn._acquired.keys())

    @asyncio.coroutine
    def request():
        resp = yield from sess.get(url, proxy=proxy.url)

        assert 1 == len(conn._acquired.keys())
        assert 1 == len(conn._acquired[key])

        yield from resp.release()

    yield from request()

    assert 0 == len(conn._acquired[key])

    yield from sess.close()


@asyncio.coroutine
def test_proxy_https_acquired_cleanup_force(proxy_test_server, loop):
    url = 'https://secure.aiohttp.io/path'
    key = ('secure.aiohttp.io', 443, True)

    conn = aiohttp.TCPConnector(force_close=True, loop=loop)
    sess = aiohttp.ClientSession(connector=conn, loop=loop)
    proxy = yield from proxy_test_server()

    assert 0 == len(conn._acquired.keys())

    @asyncio.coroutine
    def request():
        resp = yield from sess.get(url, proxy=proxy.url)

        assert 1 == len(conn._acquired.keys())
        assert 1 == len(conn._acquired[key])

        yield from resp.release()

    yield from request()

    assert 0 == len(conn._acquired[key])

    yield from sess.close()


@asyncio.coroutine
def test_proxy_https_multi_conn_limit(proxy_test_server, loop):
    url = 'https://secure.aiohttp.io/path'
    limit, multi_conn_num = 1, 5

    conn = aiohttp.TCPConnector(limit=limit, loop=loop)
    sess = aiohttp.ClientSession(connector=conn, loop=loop)
    proxy = yield from proxy_test_server()

    current_pid = None

    @asyncio.coroutine
    def request(pid):
        # process requests only one by one
        nonlocal current_pid

        resp = yield from sess.get(url, proxy=proxy.url)

        current_pid = pid
        yield from asyncio.sleep(0.2, loop=loop)
        assert current_pid == pid

        yield from resp.release()
        return resp

    requests = [request(pid) for pid in range(multi_conn_num)]
    responses = yield from asyncio.gather(*requests, loop=loop)

    assert len(responses) == multi_conn_num
    assert set(resp.status for resp in responses) == {200}

    yield from sess.close()


def _patch_ssl_transport(monkeypatch):
    """Make ssl transport substitution to prevent ssl handshake."""
    def _make_ssl_transport_dummy(self, rawsock, protocol, sslcontext,
                                  waiter=None, **kwargs):
        return self._make_socket_transport(rawsock, protocol, waiter,
                                           extra=kwargs.get('extra'),
                                           server=kwargs.get('server'))

    monkeypatch.setattr(
        "asyncio.selector_events.BaseSelectorEventLoop._make_ssl_transport",
        _make_ssl_transport_dummy)