forked from aio-libs/aiohttp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_connector.py
2289 lines (1747 loc) · 65.8 KB
/
test_connector.py
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests of http client with custom Connector"""
import asyncio
import gc
import hashlib
import platform
import socket
import ssl
import sys
import uuid
from collections import deque
from unittest import mock
import pytest
from yarl import URL
import aiohttp
from aiohttp import client, web
from aiohttp.client import ClientRequest, ClientTimeout
from aiohttp.client_reqrep import ConnectionKey
from aiohttp.connector import Connection, _DNSCacheTable, TCPConnector
from aiohttp.helpers import PY_37
from aiohttp.locks import EventResultOrError
from aiohttp.test_utils import make_mocked_coro, unused_port
from aiohttp.tracing import Trace
from conftest import needs_unix
@pytest.fixture()
def key():
"""Connection key"""
return ConnectionKey('localhost', 80, False, None, None, None, None)
@pytest.fixture
def key2():
"""Connection key"""
return ConnectionKey('localhost', 80, False, None, None, None, None)
@pytest.fixture
def ssl_key():
"""Connection key"""
return ConnectionKey('localhost', 80, True, None, None, None, None)
@pytest.fixture
def unix_server(loop, unix_sockname):
runners = []
async def go(app):
runner = web.AppRunner(app)
runners.append(runner)
await runner.setup()
site = web.UnixSite(runner, unix_sockname)
await site.start()
yield go
for runner in runners:
loop.run_until_complete(runner.cleanup())
@pytest.fixture
def named_pipe_server(proactor_loop, pipe_name):
runners = []
async def go(app):
runner = web.AppRunner(app)
runners.append(runner)
await runner.setup()
site = web.NamedPipeSite(runner, pipe_name)
await site.start()
yield go
for runner in runners:
proactor_loop.run_until_complete(runner.cleanup())
def create_mocked_conn(conn_closing_result=None, **kwargs):
assert 'loop' not in kwargs
loop = asyncio.get_event_loop()
proto = mock.Mock(**kwargs)
proto.closed = loop.create_future()
proto.closed.set_result(conn_closing_result)
return proto
def test_connection_del(loop) -> None:
connector = mock.Mock()
key = mock.Mock()
protocol = mock.Mock()
loop.set_debug(0)
conn = Connection(connector, key, protocol, loop=loop)
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
with pytest.warns(ResourceWarning):
del conn
gc.collect()
connector._release.assert_called_with(
key,
protocol,
should_close=True
)
msg = {
'message': mock.ANY,
'client_connection': mock.ANY,
}
exc_handler.assert_called_with(loop, msg)
def test_connection_del_loop_debug(loop) -> None:
connector = mock.Mock()
key = mock.Mock()
protocol = mock.Mock()
loop.set_debug(1)
conn = Connection(connector, key, protocol, loop=loop)
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
with pytest.warns(ResourceWarning):
del conn
gc.collect()
msg = {
'message': mock.ANY,
'client_connection': mock.ANY,
'source_traceback': mock.ANY
}
exc_handler.assert_called_with(loop, msg)
def test_connection_del_loop_closed(loop) -> None:
connector = mock.Mock()
key = mock.Mock()
protocol = mock.Mock()
loop.set_debug(1)
conn = Connection(connector, key, protocol, loop=loop)
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
loop.close()
with pytest.warns(ResourceWarning):
del conn
gc.collect()
assert not connector._release.called
assert not exc_handler.called
async def test_del(loop) -> None:
conn = aiohttp.BaseConnector()
proto = create_mocked_conn(loop, should_close=False)
conn._release('a', proto)
conns_impl = conn._conns
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
with pytest.warns(ResourceWarning):
del conn
gc.collect()
assert not conns_impl
proto.close.assert_called_with()
msg = {'connector': mock.ANY, # conn was deleted
'connections': mock.ANY,
'message': 'Unclosed connector'}
if loop.get_debug():
msg['source_traceback'] = mock.ANY
exc_handler.assert_called_with(loop, msg)
@pytest.mark.xfail
async def test_del_with_scheduled_cleanup(loop) -> None:
loop.set_debug(True)
conn = aiohttp.BaseConnector(keepalive_timeout=0.01)
transp = create_mocked_conn(loop)
conn._conns['a'] = [(transp, 123)]
conns_impl = conn._conns
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
with pytest.warns(ResourceWarning):
# obviously doesn't deletion because loop has a strong
# reference to connector's instance method, isn't it?
del conn
await asyncio.sleep(0.01, loop=loop)
gc.collect()
assert not conns_impl
transp.close.assert_called_with()
msg = {'connector': mock.ANY, # conn was deleted
'message': 'Unclosed connector'}
if loop.get_debug():
msg['source_traceback'] = mock.ANY
exc_handler.assert_called_with(loop, msg)
@pytest.mark.skipif(sys.implementation.name != 'cpython',
reason="CPython GC is required for the test")
def test_del_with_closed_loop(loop) -> None:
async def make_conn():
return aiohttp.BaseConnector()
conn = loop.run_until_complete(make_conn())
transp = create_mocked_conn(loop)
conn._conns['a'] = [(transp, 123)]
conns_impl = conn._conns
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
loop.close()
with pytest.warns(ResourceWarning):
del conn
gc.collect()
assert not conns_impl
assert not transp.close.called
assert exc_handler.called
async def test_del_empty_connector(loop) -> None:
conn = aiohttp.BaseConnector()
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
del conn
assert not exc_handler.called
async def test_create_conn() -> None:
conn = aiohttp.BaseConnector()
with pytest.raises(NotImplementedError):
await conn._create_connection(object(), [], object())
async def test_async_context_manager(loop) -> None:
conn = aiohttp.BaseConnector()
async with conn as c:
assert conn is c
assert conn.closed
async def test_close() -> None:
proto = create_mocked_conn()
conn = aiohttp.BaseConnector()
assert not conn.closed
conn._conns[('host', 8080, False)] = [(proto, object())]
await conn.close()
assert not conn._conns
assert proto.close.called
assert conn.closed
async def test_get(loop) -> None:
conn = aiohttp.BaseConnector()
assert conn._get(1) is None
proto = create_mocked_conn(loop)
conn._conns[1] = [(proto, loop.time())]
assert conn._get(1) == proto
await conn.close()
async def test_get_expired(loop) -> None:
conn = aiohttp.BaseConnector()
key = ConnectionKey('localhost', 80, False, None, None, None, None)
assert conn._get(key) is None
proto = create_mocked_conn(loop)
conn._conns[key] = [(proto, loop.time() - 1000)]
assert conn._get(key) is None
assert not conn._conns
await conn.close()
async def test_get_expired_ssl(loop) -> None:
conn = aiohttp.BaseConnector(enable_cleanup_closed=True)
key = ConnectionKey('localhost', 80, True, None, None, None, None)
assert conn._get(key) is None
proto = create_mocked_conn(loop)
transport = proto.transport
conn._conns[key] = [(proto, loop.time() - 1000)]
assert conn._get(key) is None
assert not conn._conns
assert conn._cleanup_closed_transports == [transport]
await conn.close()
async def test_release_acquired(key) -> None:
proto = create_mocked_conn()
conn = aiohttp.BaseConnector(limit=5)
conn._release_waiter = mock.Mock()
conn._acquired.add(proto)
conn._acquired_per_host[key].add(proto)
conn._release_acquired(key, proto)
assert 0 == len(conn._acquired)
assert 0 == len(conn._acquired_per_host)
assert conn._release_waiter.called
conn._release_acquired(key, proto)
assert 0 == len(conn._acquired)
assert 0 == len(conn._acquired_per_host)
await conn.close()
async def test_release_acquired_closed(key) -> None:
proto = create_mocked_conn()
conn = aiohttp.BaseConnector(limit=5)
conn._release_waiter = mock.Mock()
conn._acquired.add(proto)
conn._acquired_per_host[key].add(proto)
conn._closed = True
conn._release_acquired(key, proto)
assert 1 == len(conn._acquired)
assert 1 == len(conn._acquired_per_host[key])
assert not conn._release_waiter.called
await conn.close()
async def test_release(loop, key) -> None:
conn = aiohttp.BaseConnector()
conn._release_waiter = mock.Mock()
proto = create_mocked_conn(loop, should_close=False)
conn._acquired.add(proto)
conn._acquired_per_host[key].add(proto)
conn._release(key, proto)
assert conn._release_waiter.called
assert conn._conns[key][0][0] == proto
assert conn._conns[key][0][1] == pytest.approx(loop.time(), abs=0.1)
assert not conn._cleanup_closed_transports
await conn.close()
async def test_release_ssl_transport(loop, ssl_key) -> None:
conn = aiohttp.BaseConnector(enable_cleanup_closed=True)
conn._release_waiter = mock.Mock()
proto = create_mocked_conn(loop)
transport = proto.transport
conn._acquired.add(proto)
conn._acquired_per_host[ssl_key].add(proto)
conn._release(ssl_key, proto, should_close=True)
assert conn._cleanup_closed_transports == [transport]
await conn.close()
async def test_release_already_closed() -> None:
conn = aiohttp.BaseConnector()
proto = create_mocked_conn()
key = 1
conn._acquired.add(proto)
await conn.close()
conn._release_waiters = mock.Mock()
conn._release_acquired = mock.Mock()
conn._release(key, proto)
assert not conn._release_waiters.called
assert not conn._release_acquired.called
async def test_release_waiter_no_limit(loop, key, key2) -> None:
# limit is 0
conn = aiohttp.BaseConnector(limit=0)
w = mock.Mock()
w.done.return_value = False
conn._waiters[key].append(w)
conn._release_waiter()
assert len(conn._waiters[key]) == 0
assert w.done.called
await conn.close()
async def test_release_waiter_first_available(loop, key, key2) -> None:
conn = aiohttp.BaseConnector()
w1, w2 = mock.Mock(), mock.Mock()
w1.done.return_value = False
w2.done.return_value = False
conn._waiters[key].append(w2)
conn._waiters[key2].append(w1)
conn._release_waiter()
assert (w1.set_result.called and not w2.set_result.called or
not w1.set_result.called and w2.set_result.called)
await conn.close()
async def test_release_waiter_release_first(loop, key, key2) -> None:
conn = aiohttp.BaseConnector(limit=1)
w1, w2 = mock.Mock(), mock.Mock()
w1.done.return_value = False
w2.done.return_value = False
conn._waiters[key] = deque([w1, w2])
conn._release_waiter()
assert w1.set_result.called
assert not w2.set_result.called
await conn.close()
async def test_release_waiter_skip_done_waiter(loop, key, key2) -> None:
conn = aiohttp.BaseConnector(limit=1)
w1, w2 = mock.Mock(), mock.Mock()
w1.done.return_value = True
w2.done.return_value = False
conn._waiters[key] = deque([w1, w2])
conn._release_waiter()
assert not w1.set_result.called
assert w2.set_result.called
await conn.close()
async def test_release_waiter_per_host(loop, key, key2) -> None:
# no limit
conn = aiohttp.BaseConnector(limit=0, limit_per_host=2)
w1, w2 = mock.Mock(), mock.Mock()
w1.done.return_value = False
w2.done.return_value = False
conn._waiters[key] = deque([w1])
conn._waiters[key2] = deque([w2])
conn._release_waiter()
assert ((w1.set_result.called and not w2.set_result.called) or
(not w1.set_result.called and w2.set_result.called))
await conn.close()
async def test_release_waiter_no_available(loop, key, key2) -> None:
# limit is 0
conn = aiohttp.BaseConnector(limit=0)
w = mock.Mock()
w.done.return_value = False
conn._waiters[key].append(w)
conn._available_connections = mock.Mock(return_value=0)
conn._release_waiter()
assert len(conn._waiters) == 1
assert not w.done.called
await conn.close()
async def test_release_close(key) -> None:
conn = aiohttp.BaseConnector()
proto = create_mocked_conn(should_close=True)
conn._acquired.add(proto)
conn._release(key, proto)
assert not conn._conns
assert proto.close.called
async def test__drop_acquire_per_host1(loop) -> None:
conn = aiohttp.BaseConnector()
conn._drop_acquired_per_host(123, 456)
assert len(conn._acquired_per_host) == 0
async def test__drop_acquire_per_host2(loop) -> None:
conn = aiohttp.BaseConnector()
conn._acquired_per_host[123].add(456)
conn._drop_acquired_per_host(123, 456)
assert len(conn._acquired_per_host) == 0
async def test__drop_acquire_per_host3(loop) -> None:
conn = aiohttp.BaseConnector()
conn._acquired_per_host[123].add(456)
conn._acquired_per_host[123].add(789)
conn._drop_acquired_per_host(123, 456)
assert len(conn._acquired_per_host) == 1
assert conn._acquired_per_host[123] == {789}
async def test_tcp_connector_certificate_error(loop) -> None:
req = ClientRequest('GET', URL('https://127.0.0.1:443'), loop=loop)
async def certificate_error(*args, **kwargs):
raise ssl.CertificateError
conn = aiohttp.TCPConnector()
conn._loop.create_connection = certificate_error
with pytest.raises(aiohttp.ClientConnectorCertificateError) as ctx:
await conn.connect(req, [], ClientTimeout())
assert isinstance(ctx.value, ssl.CertificateError)
assert isinstance(ctx.value.certificate_error, ssl.CertificateError)
assert isinstance(ctx.value, aiohttp.ClientSSLError)
async def test_tcp_connector_multiple_hosts_errors(loop) -> None:
conn = aiohttp.TCPConnector()
ip1 = '192.168.1.1'
ip2 = '192.168.1.2'
ip3 = '192.168.1.3'
ip4 = '192.168.1.4'
ip5 = '192.168.1.5'
ips = [ip1, ip2, ip3, ip4, ip5]
ips_tried = []
fingerprint = hashlib.sha256(b'foo').digest()
req = ClientRequest('GET', URL('https://mocked.host'),
ssl=aiohttp.Fingerprint(fingerprint),
loop=loop)
async def _resolve_host(host, port, traces=None):
return [{
'hostname': host,
'host': ip,
'port': port,
'family': socket.AF_INET,
'proto': 0,
'flags': socket.AI_NUMERICHOST}
for ip in ips]
conn._resolve_host = _resolve_host
os_error = certificate_error = ssl_error = fingerprint_error = False
connected = False
async def create_connection(*args, **kwargs):
nonlocal os_error, certificate_error, ssl_error, fingerprint_error
nonlocal connected
ip = args[1]
ips_tried.append(ip)
if ip == ip1:
os_error = True
raise OSError
if ip == ip2:
certificate_error = True
raise ssl.CertificateError
if ip == ip3:
ssl_error = True
raise ssl.SSLError
if ip == ip4:
fingerprint_error = True
tr = create_mocked_conn(loop)
pr = create_mocked_conn(loop)
def get_extra_info(param):
if param == 'sslcontext':
return True
if param == 'ssl_object':
s = create_mocked_conn(loop)
s.getpeercert.return_value = b'not foo'
return s
if param == 'peername':
return ('192.168.1.5', 12345)
assert False, param
tr.get_extra_info = get_extra_info
return tr, pr
if ip == ip5:
connected = True
tr = create_mocked_conn(loop)
pr = create_mocked_conn(loop)
def get_extra_info(param):
if param == 'sslcontext':
return True
if param == 'ssl_object':
s = create_mocked_conn(loop)
s.getpeercert.return_value = b'foo'
return s
assert False
tr.get_extra_info = get_extra_info
return tr, pr
assert False
conn._loop.create_connection = create_connection
await conn.connect(req, [], ClientTimeout())
assert ips == ips_tried
assert os_error
assert certificate_error
assert ssl_error
assert fingerprint_error
assert connected
async def test_tcp_connector_resolve_host(loop) -> None:
conn = aiohttp.TCPConnector(use_dns_cache=True)
res = await conn._resolve_host('localhost', 8080)
assert res
for rec in res:
if rec['family'] == socket.AF_INET:
assert rec['host'] == '127.0.0.1'
assert rec['hostname'] == 'localhost'
assert rec['port'] == 8080
elif rec['family'] == socket.AF_INET6:
assert rec['hostname'] == 'localhost'
assert rec['port'] == 8080
if platform.system() == 'Darwin':
assert rec['host'] in ('::1', 'fe80::1', 'fe80::1%lo0')
else:
assert rec['host'] == '::1'
@pytest.fixture
def dns_response(loop):
async def coro():
# simulates a network operation
await asyncio.sleep(0)
return ["127.0.0.1"]
return coro
async def test_tcp_connector_dns_cache_not_expired(loop, dns_response) -> None:
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
await conn._resolve_host('localhost', 8080)
await conn._resolve_host('localhost', 8080)
m_resolver().resolve.assert_called_once_with(
'localhost',
8080,
family=0
)
async def test_tcp_connector_dns_cache_forever(loop, dns_response) -> None:
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
await conn._resolve_host('localhost', 8080)
await conn._resolve_host('localhost', 8080)
m_resolver().resolve.assert_called_once_with(
'localhost',
8080,
family=0
)
async def test_tcp_connector_use_dns_cache_disabled(loop,
dns_response) -> None:
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(use_dns_cache=False)
m_resolver().resolve.side_effect = [dns_response(), dns_response()]
await conn._resolve_host('localhost', 8080)
await conn._resolve_host('localhost', 8080)
m_resolver().resolve.assert_has_calls([
mock.call('localhost', 8080, family=0),
mock.call('localhost', 8080, family=0)
])
async def test_tcp_connector_dns_throttle_requests(loop, dns_response) -> None:
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
loop.create_task(conn._resolve_host('localhost', 8080))
loop.create_task(conn._resolve_host('localhost', 8080))
await asyncio.sleep(0)
m_resolver().resolve.assert_called_once_with(
'localhost',
8080,
family=0
)
async def test_tcp_connector_dns_throttle_requests_exception_spread(
loop) -> None:
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
e = Exception()
m_resolver().resolve.side_effect = e
r1 = loop.create_task(conn._resolve_host('localhost', 8080))
r2 = loop.create_task(conn._resolve_host('localhost', 8080))
await asyncio.sleep(0)
assert r1.exception() == e
assert r2.exception() == e
async def test_tcp_connector_dns_throttle_requests_cancelled_when_close(
loop,
dns_response):
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
loop.create_task(conn._resolve_host('localhost', 8080))
f = loop.create_task(conn._resolve_host('localhost', 8080))
await asyncio.sleep(0)
await conn.close()
with pytest.raises(asyncio.futures.CancelledError):
await f
async def test_tcp_connector_dns_tracing(loop, dns_response) -> None:
session = mock.Mock()
trace_config_ctx = mock.Mock()
on_dns_resolvehost_start = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
on_dns_resolvehost_end = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
on_dns_cache_hit = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
on_dns_cache_miss = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
trace_config = aiohttp.TraceConfig(
trace_config_ctx_factory=mock.Mock(return_value=trace_config_ctx)
)
trace_config.on_dns_resolvehost_start.append(on_dns_resolvehost_start)
trace_config.on_dns_resolvehost_end.append(on_dns_resolvehost_end)
trace_config.on_dns_cache_hit.append(on_dns_cache_hit)
trace_config.on_dns_cache_miss.append(on_dns_cache_miss)
trace_config.freeze()
traces = [
Trace(
session,
trace_config,
trace_config.trace_config_ctx()
)
]
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
await conn._resolve_host(
'localhost',
8080,
traces=traces
)
on_dns_resolvehost_start.assert_called_once_with(
session,
trace_config_ctx,
aiohttp.TraceDnsResolveHostStartParams('localhost')
)
on_dns_resolvehost_end.assert_called_once_with(
session,
trace_config_ctx,
aiohttp.TraceDnsResolveHostEndParams('localhost')
)
on_dns_cache_miss.assert_called_once_with(
session,
trace_config_ctx,
aiohttp.TraceDnsCacheMissParams('localhost')
)
assert not on_dns_cache_hit.called
await conn._resolve_host(
'localhost',
8080,
traces=traces
)
on_dns_cache_hit.assert_called_once_with(
session,
trace_config_ctx,
aiohttp.TraceDnsCacheHitParams('localhost')
)
async def test_tcp_connector_dns_tracing_cache_disabled(loop,
dns_response) -> None:
session = mock.Mock()
trace_config_ctx = mock.Mock()
on_dns_resolvehost_start = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
on_dns_resolvehost_end = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
trace_config = aiohttp.TraceConfig(
trace_config_ctx_factory=mock.Mock(return_value=trace_config_ctx)
)
trace_config.on_dns_resolvehost_start.append(on_dns_resolvehost_start)
trace_config.on_dns_resolvehost_end.append(on_dns_resolvehost_end)
trace_config.freeze()
traces = [
Trace(
session,
trace_config,
trace_config.trace_config_ctx()
)
]
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=False
)
m_resolver().resolve.side_effect = [
dns_response(),
dns_response()
]
await conn._resolve_host(
'localhost',
8080,
traces=traces
)
await conn._resolve_host(
'localhost',
8080,
traces=traces
)
on_dns_resolvehost_start.assert_has_calls([
mock.call(
session,
trace_config_ctx,
aiohttp.TraceDnsResolveHostStartParams('localhost')
),
mock.call(
session,
trace_config_ctx,
aiohttp.TraceDnsResolveHostStartParams('localhost')
)
])
on_dns_resolvehost_end.assert_has_calls([
mock.call(
session,
trace_config_ctx,
aiohttp.TraceDnsResolveHostEndParams('localhost')
),
mock.call(
session,
trace_config_ctx,
aiohttp.TraceDnsResolveHostEndParams('localhost')
)
])
async def test_tcp_connector_dns_tracing_throttle_requests(
loop, dns_response) -> None:
session = mock.Mock()
trace_config_ctx = mock.Mock()
on_dns_cache_hit = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
on_dns_cache_miss = mock.Mock(
side_effect=asyncio.coroutine(mock.Mock())
)
trace_config = aiohttp.TraceConfig(
trace_config_ctx_factory=mock.Mock(return_value=trace_config_ctx)
)
trace_config.on_dns_cache_hit.append(on_dns_cache_hit)
trace_config.on_dns_cache_miss.append(on_dns_cache_miss)
trace_config.freeze()
traces = [
Trace(
session,
trace_config,
trace_config.trace_config_ctx()
)
]
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
loop.create_task(conn._resolve_host('localhost', 8080, traces=traces))
loop.create_task(conn._resolve_host('localhost', 8080, traces=traces))
await asyncio.sleep(0)
on_dns_cache_hit.assert_called_once_with(
session,
trace_config_ctx,
aiohttp.TraceDnsCacheHitParams('localhost')
)
on_dns_cache_miss.assert_called_once_with(
session,
trace_config_ctx,
aiohttp.TraceDnsCacheMissParams('localhost')
)
async def test_dns_error(loop) -> None:
connector = aiohttp.TCPConnector()
connector._resolve_host = make_mocked_coro(
raise_exception=OSError('dont take it serious'))
req = ClientRequest(
'GET', URL('http://www.python.org'),
loop=loop)
with pytest.raises(aiohttp.ClientConnectorError):
await connector.connect(req, [], ClientTimeout())
async def test_get_pop_empty_conns(loop) -> None:
# see issue #473
conn = aiohttp.BaseConnector()
key = ('127.0.0.1', 80, False)
conn._conns[key] = []
proto = conn._get(key)
assert proto is None
assert not conn._conns
async def test_release_close_do_not_add_to_pool(loop, key) -> None:
# see issue #473
conn = aiohttp.BaseConnector()
proto = create_mocked_conn(loop, should_close=True)
conn._acquired.add(proto)
conn._release(key, proto)
assert not conn._conns
async def test_release_close_do_not_delete_existing_connections(loop,
key) -> None:
proto1 = create_mocked_conn(loop)
conn = aiohttp.BaseConnector()
conn._conns[key] = [(proto1, 1)]
proto = create_mocked_conn(loop, should_close=True)
conn._acquired.add(proto)
conn._release(key, proto)
assert conn._conns[key] == [(proto1, 1)]
assert proto.close.called
await conn.close()
async def test_release_not_started(loop) -> None:
conn = aiohttp.BaseConnector()
proto = create_mocked_conn(should_close=False)
key = 1
conn._acquired.add(proto)
conn._release(key, proto)
# assert conn._conns == {1: [(proto, 10)]}
rec = conn._conns[1]
assert rec[0][0] == proto
assert rec[0][1] == pytest.approx(loop.time(), abs=0.05)
assert not proto.close.called
await conn.close()
async def test_release_not_opened(loop, key) -> None:
conn = aiohttp.BaseConnector()