-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
test_connector.py
1351 lines (1031 loc) · 38.7 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 os.path
import platform
import shutil
import socket
import ssl
import tempfile
import unittest
from unittest import mock
import pytest
from yarl import URL
import aiohttp
from aiohttp import client, helpers, web
from aiohttp.client import ClientRequest
from aiohttp.connector import Connection, _DNSCacheTable
from aiohttp.test_utils import unused_port
@pytest.fixture()
def key():
"""Connection key"""
return ('localhost1', 80, False)
@pytest.fixture
def key2():
"""Connection key"""
return ('localhost2', 80, False)
@pytest.fixture
def ssl_key():
"""Connection key"""
return ('localhost', 80, True)
def test_del(loop):
conn = aiohttp.BaseConnector(loop=loop)
proto = mock.Mock(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
@asyncio.coroutine
def test_del_with_scheduled_cleanup(loop):
loop.set_debug(True)
conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=0.01)
transp = mock.Mock()
conn._conns['a'] = [(transp, 'proto', 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
yield from 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)
def test_del_with_closed_loop(loop):
conn = aiohttp.BaseConnector(loop=loop)
transp = mock.Mock()
conn._conns['a'] = [(transp, 'proto', 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
def test_del_empty_conector(loop):
conn = aiohttp.BaseConnector(loop=loop)
exc_handler = mock.Mock()
loop.set_exception_handler(exc_handler)
del conn
assert not exc_handler.called
@asyncio.coroutine
def test_create_conn(loop):
conn = aiohttp.BaseConnector(loop=loop)
with pytest.raises(NotImplementedError):
yield from conn._create_connection(object())
def test_context_manager(loop):
conn = aiohttp.BaseConnector(loop=loop)
conn.close = mock.Mock()
with conn as c:
assert conn is c
assert conn.close.called
def test_ctor_loop():
with mock.patch('aiohttp.connector.asyncio') as m_asyncio:
session = aiohttp.BaseConnector()
assert session._loop is m_asyncio.get_event_loop.return_value
def test_close(loop):
proto = mock.Mock()
conn = aiohttp.BaseConnector(loop=loop)
assert not conn.closed
conn._conns[('host', 8080, False)] = [(proto, object())]
conn.close()
assert not conn._conns
assert proto.close.called
assert conn.closed
def test_get(loop):
conn = aiohttp.BaseConnector(loop=loop)
assert conn._get(1) is None
proto = mock.Mock()
conn._conns[1] = [(proto, loop.time())]
assert conn._get(1) == proto
conn.close()
def test_get_expired(loop):
conn = aiohttp.BaseConnector(loop=loop)
assert conn._get(('localhost', 80, False)) is None
proto = mock.Mock()
conn._conns[('localhost', 80, False)] = [(proto, loop.time() - 1000)]
assert conn._get(('localhost', 80, False)) is None
assert not conn._conns
conn.close()
def test_get_expired_ssl(loop):
conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True)
assert conn._get(('localhost', 80, True)) is None
proto = mock.Mock()
conn._conns[('localhost', 80, True)] = [(proto, loop.time() - 1000)]
assert conn._get(('localhost', 80, True)) is None
assert not conn._conns
assert conn._cleanup_closed_transports == [proto.close.return_value]
conn.close()
def test_release_acquired(loop, key):
proto = mock.Mock()
conn = aiohttp.BaseConnector(loop=loop, 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)
conn.close()
def test_release_acquired_closed(loop, key):
proto = mock.Mock()
conn = aiohttp.BaseConnector(loop=loop, 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
conn.close()
def test_release(loop, key):
conn = aiohttp.BaseConnector(loop=loop)
conn._release_waiter = mock.Mock()
proto = mock.Mock(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
conn.close()
def test_release_ssl_transport(loop, ssl_key):
conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True)
conn._release_waiter = mock.Mock()
proto = mock.Mock()
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 == [proto.close.return_value]
conn.close()
def test_release_already_closed(loop):
conn = aiohttp.BaseConnector(loop=loop)
proto = mock.Mock()
key = 1
conn._acquired.add(proto)
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
def test_release_waiter(loop, key, key2):
# limit is 0
conn = aiohttp.BaseConnector(limit=0, loop=loop)
w = mock.Mock()
w.done.return_value = False
conn._waiters[key].append(w)
conn._release_waiter()
assert len(conn._waiters) == 1
assert not w.done.called
conn.close()
# release first available
conn = aiohttp.BaseConnector(loop=loop)
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)
conn.close()
# limited available
conn = aiohttp.BaseConnector(loop=loop, limit=1)
w1, w2 = mock.Mock(), mock.Mock()
w1.done.return_value = False
w2.done.return_value = False
conn._waiters[key] = [w1, w2]
conn._release_waiter()
assert w1.set_result.called
assert not w2.set_result.called
conn.close()
# limited available
conn = aiohttp.BaseConnector(loop=loop, limit=1)
w1, w2 = mock.Mock(), mock.Mock()
w1.done.return_value = True
w2.done.return_value = False
conn._waiters[key] = [w1, w2]
conn._release_waiter()
assert not w1.set_result.called
assert not w2.set_result.called
conn.close()
def test_release_waiter_per_host(loop, key, key2):
# no limit
conn = aiohttp.BaseConnector(loop=loop, 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] = [w1]
conn._waiters[key2] = [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))
conn.close()
def test_release_close(loop):
conn = aiohttp.BaseConnector(loop=loop)
proto = mock.Mock(should_close=True)
key = ('localhost', 80, False)
conn._acquired.add(proto)
conn._release(key, proto)
assert not conn._conns
assert proto.close.called
@asyncio.coroutine
def test_tcp_connector_resolve_host(loop):
conn = aiohttp.TCPConnector(loop=loop, use_dns_cache=True)
res = yield from 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):
@asyncio.coroutine
def coro():
# simulates a network operation
yield from asyncio.sleep(0, loop=loop)
return ["127.0.0.1"]
return coro
@asyncio.coroutine
def test_tcp_connector_dns_cache_not_expired(loop, dns_response):
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
loop=loop,
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
yield from conn._resolve_host('localhost', 8080)
yield from conn._resolve_host('localhost', 8080)
m_resolver().resolve.assert_called_once_with(
'localhost',
8080,
family=0
)
@asyncio.coroutine
def test_tcp_connector_dns_cache_forever(loop, dns_response):
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
loop=loop,
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
yield from conn._resolve_host('localhost', 8080)
yield from conn._resolve_host('localhost', 8080)
m_resolver().resolve.assert_called_once_with(
'localhost',
8080,
family=0
)
@asyncio.coroutine
def test_tcp_connector_use_dns_cache_disabled(loop, dns_response):
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(loop=loop, use_dns_cache=False)
m_resolver().resolve.return_value = dns_response()
yield from conn._resolve_host('localhost', 8080)
yield from conn._resolve_host('localhost', 8080)
m_resolver().resolve.assert_has_calls([
mock.call('localhost', 8080, family=0),
mock.call('localhost', 8080, family=0)
])
@asyncio.coroutine
def test_tcp_connector_dns_throttle_requests(loop, dns_response):
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
loop=loop,
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
helpers.ensure_future(conn._resolve_host('localhost', 8080), loop=loop)
helpers.ensure_future(conn._resolve_host('localhost', 8080), loop=loop)
yield from asyncio.sleep(0, loop=loop)
m_resolver().resolve.assert_called_once_with(
'localhost',
8080,
family=0
)
@asyncio.coroutine
def test_tcp_connector_dns_throttle_requests_exception_spread(loop):
with mock.patch('aiohttp.connector.DefaultResolver') as m_resolver:
conn = aiohttp.TCPConnector(
loop=loop,
use_dns_cache=True,
ttl_dns_cache=10
)
e = Exception()
m_resolver().resolve.side_effect = e
r1 = helpers.ensure_future(
conn._resolve_host('localhost', 8080),
loop=loop
)
r2 = helpers.ensure_future(
conn._resolve_host('localhost', 8080),
loop=loop
)
yield from asyncio.sleep(0, loop=loop)
assert r1.exception() == e
assert r2.exception() == e
@asyncio.coroutine
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(
loop=loop,
use_dns_cache=True,
ttl_dns_cache=10
)
m_resolver().resolve.return_value = dns_response()
helpers.ensure_future(
conn._resolve_host('localhost', 8080), loop=loop)
f = helpers.ensure_future(
conn._resolve_host('localhost', 8080), loop=loop)
yield from asyncio.sleep(0, loop=loop)
conn.close()
with pytest.raises(asyncio.futures.CancelledError):
yield from f
def test_get_pop_empty_conns(loop):
# see issue #473
conn = aiohttp.BaseConnector(loop=loop)
key = ('127.0.0.1', 80, False)
conn._conns[key] = []
proto = conn._get(key)
assert proto is None
assert not conn._conns
def test_release_close_do_not_add_to_pool(loop):
# see issue #473
conn = aiohttp.BaseConnector(loop=loop)
key = ('127.0.0.1', 80, False)
proto = mock.Mock(should_close=True)
conn._acquired.add(proto)
conn._release(key, proto)
assert not conn._conns
def test_release_close_do_not_delete_existing_connections(loop):
key = ('127.0.0.1', 80, False)
proto1 = mock.Mock()
conn = aiohttp.BaseConnector(loop=loop)
conn._conns[key] = [(proto1, 1)]
proto = mock.Mock(should_close=True)
conn._acquired.add(proto)
conn._release(key, proto)
assert conn._conns[key] == [(proto1, 1)]
assert proto.close.called
conn.close()
def test_release_not_started(loop):
conn = aiohttp.BaseConnector(loop=loop)
proto = mock.Mock(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.01)
assert not proto.close.called
conn.close()
def test_release_not_opened(loop):
conn = aiohttp.BaseConnector(loop=loop)
proto = mock.Mock()
key = ('localhost', 80, False)
conn._acquired.add(proto)
conn._release(key, proto)
assert proto.close.called
@asyncio.coroutine
def test_connect(loop):
proto = mock.Mock()
proto.is_connected.return_value = True
req = ClientRequest('GET', URL('http://host:80'), loop=loop)
conn = aiohttp.BaseConnector(loop=loop)
key = ('host', 80, False)
conn._conns[key] = [(proto, loop.time())]
conn._create_connection = mock.Mock()
conn._create_connection.return_value = helpers.create_future(loop)
conn._create_connection.return_value.set_result(proto)
connection = yield from conn.connect(req)
assert not conn._create_connection.called
assert connection._protocol is proto
assert connection.transport is proto.transport
assert isinstance(connection, Connection)
connection.close()
@asyncio.coroutine
def test_connect_connection_error(loop):
conn = aiohttp.BaseConnector(loop=loop)
conn._create_connection = mock.Mock()
conn._create_connection.return_value = helpers.create_future(loop)
err = OSError(1, 'permission error')
conn._create_connection.return_value.set_exception(err)
with pytest.raises(aiohttp.ClientConnectorError) as ctx:
req = mock.Mock()
yield from conn.connect(req)
assert 1 == ctx.value.errno
assert str(ctx.value).startswith('Cannot connect to')
assert str(ctx.value).endswith('[permission error]')
assert ctx.value.host == req.host
assert ctx.value.port == req.port
assert ctx.value.ssl == req.ssl
@asyncio.coroutine
def test_close_during_connect(loop):
proto = mock.Mock()
proto.is_connected.return_value = True
fut = helpers.create_future(loop)
req = ClientRequest('GET', URL('http://host:80'), loop=loop)
conn = aiohttp.BaseConnector(loop=loop)
conn._create_connection = mock.Mock()
conn._create_connection.return_value = fut
task = helpers.ensure_future(conn.connect(req), loop=loop)
yield from asyncio.sleep(0, loop=loop)
conn.close()
fut.set_result(proto)
with pytest.raises(aiohttp.ClientConnectionError):
yield from task
assert proto.close.called
def test_ctor_cleanup():
loop = mock.Mock()
loop.time.return_value = 1.5
conn = aiohttp.BaseConnector(
loop=loop, keepalive_timeout=10, enable_cleanup_closed=True)
assert conn._cleanup_handle is None
assert conn._cleanup_closed_handle is not None
def test_cleanup():
key = ('localhost', 80, False)
testset = {
key: [(mock.Mock(), 10),
(mock.Mock(), 300)],
}
testset[key][0][0].is_connected.return_value = True
testset[key][1][0].is_connected.return_value = False
loop = mock.Mock()
loop.time.return_value = 300
conn = aiohttp.BaseConnector(loop=loop)
conn._conns = testset
existing_handle = conn._cleanup_handle = mock.Mock()
conn._cleanup()
assert existing_handle.cancel.called
assert conn._conns == {}
assert conn._cleanup_handle is not None
def test_cleanup_close_ssl_transport():
proto = mock.Mock()
key = ('localhost', 80, True)
testset = {key: [(proto, 10)]}
loop = mock.Mock()
loop.time.return_value = 300
conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True)
conn._conns = testset
existing_handle = conn._cleanup_handle = mock.Mock()
conn._cleanup()
assert existing_handle.cancel.called
assert conn._conns == {}
assert conn._cleanup_closed_transports == [proto.close.return_value]
def test_cleanup2():
testset = {1: [(mock.Mock(), 300)]}
testset[1][0][0].is_connected.return_value = True
loop = mock.Mock()
loop.time.return_value = 300
conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)
conn._conns = testset
conn._cleanup()
assert conn._conns == testset
assert conn._cleanup_handle is not None
loop.call_at.assert_called_with(310, mock.ANY, mock.ANY)
conn.close()
def test_cleanup3():
key = ('localhost', 80, False)
testset = {key: [(mock.Mock(), 290.1),
(mock.Mock(), 305.1)]}
testset[key][0][0].is_connected.return_value = True
loop = mock.Mock()
loop.time.return_value = 308.5
conn = aiohttp.BaseConnector(loop=loop, keepalive_timeout=10)
conn._conns = testset
conn._cleanup()
assert conn._conns == {key: [testset[key][1]]}
assert conn._cleanup_handle is not None
loop.call_at.assert_called_with(319, mock.ANY, mock.ANY)
conn.close()
def test_cleanup_closed(loop, mocker):
if not hasattr(loop, '__dict__'):
pytest.skip("can not override loop attributes")
mocker.spy(loop, 'call_at')
conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True)
tr = mock.Mock()
conn._cleanup_closed_handle = cleanup_closed_handle = mock.Mock()
conn._cleanup_closed_transports = [tr]
conn._cleanup_closed()
assert tr.abort.called
assert not conn._cleanup_closed_transports
assert loop.call_at.called
assert cleanup_closed_handle.cancel.called
def test_cleanup_closed_disabled(loop, mocker):
conn = aiohttp.BaseConnector(
loop=loop, enable_cleanup_closed=False)
tr = mock.Mock()
conn._cleanup_closed_transports = [tr]
conn._cleanup_closed()
assert tr.abort.called
assert not conn._cleanup_closed_transports
def test_tcp_connector_ctor(loop):
conn = aiohttp.TCPConnector(loop=loop)
assert conn.verify_ssl
assert conn.fingerprint is None
assert conn.use_dns_cache
assert conn.family == 0
assert conn.cached_hosts == {}
def test_tcp_connector_ctor_fingerprint_valid(loop):
valid = b'\xa2\x06G\xad\xaa\xf5\xd8\\J\x99^by;\x06='
# md5 and sha1 are deprecated
with pytest.warns(DeprecationWarning):
conn = aiohttp.TCPConnector(loop=loop, fingerprint=valid)
assert conn.fingerprint == valid
def test_tcp_connector_fingerprint_invalid(loop):
invalid = b'\x00'
with pytest.raises(ValueError):
aiohttp.TCPConnector(loop=loop, fingerprint=invalid)
def test_tcp_connector_clear_dns_cache(loop):
conn = aiohttp.TCPConnector(loop=loop)
hosts = ['a', 'b']
conn._cached_hosts.add(('localhost', 123), hosts)
conn._cached_hosts.add(('localhost', 124), hosts)
conn.clear_dns_cache('localhost', 123)
assert ('localhost', 123) not in conn.cached_hosts
conn.clear_dns_cache('localhost', 123)
assert ('localhost', 123) not in conn.cached_hosts
conn.clear_dns_cache()
assert conn.cached_hosts == {}
def test_tcp_connector_clear_dns_cache_bad_args(loop):
conn = aiohttp.TCPConnector(loop=loop)
with pytest.raises(ValueError):
conn.clear_dns_cache('localhost')
def test_ambigous_verify_ssl_and_ssl_context(loop):
with pytest.raises(ValueError):
aiohttp.TCPConnector(
verify_ssl=False,
ssl_context=ssl.SSLContext(ssl.PROTOCOL_SSLv23),
loop=loop)
def test_dont_recreate_ssl_context(loop):
conn = aiohttp.TCPConnector(loop=loop)
ctx = conn.ssl_context
assert ctx is conn.ssl_context
def test_respect_precreated_ssl_context(loop):
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
conn = aiohttp.TCPConnector(loop=loop, ssl_context=ctx)
assert ctx is conn.ssl_context
def test_close_twice(loop):
proto = mock.Mock()
conn = aiohttp.BaseConnector(loop=loop)
conn._conns[1] = [(proto, object())]
conn.close()
assert not conn._conns
assert proto.close.called
assert conn.closed
conn._conns = 'Invalid' # fill with garbage
conn.close()
assert conn.closed
def test_close_cancels_cleanup_handle(loop):
conn = aiohttp.BaseConnector(loop=loop)
conn._release(1, mock.Mock(should_close=False))
assert conn._cleanup_handle is not None
conn.close()
assert conn._cleanup_handle is None
def test_close_abort_closed_transports(loop):
tr = mock.Mock()
conn = aiohttp.BaseConnector(loop=loop)
conn._cleanup_closed_transports.append(tr)
conn.close()
assert not conn._cleanup_closed_transports
assert tr.abort.called
assert conn.closed
def test_close_cancels_cleanup_closed_handle(loop):
conn = aiohttp.BaseConnector(loop=loop, enable_cleanup_closed=True)
assert conn._cleanup_closed_handle is not None
conn.close()
assert conn._cleanup_closed_handle is None
def test_ctor_with_default_loop():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
conn = aiohttp.BaseConnector()
assert loop is conn._loop
loop.close()
@asyncio.coroutine
def test_connect_with_limit(loop, key):
proto = mock.Mock()
proto.is_connected.return_value = True
req = ClientRequest('GET', URL('http://localhost1:80'),
loop=loop,
response_class=mock.Mock())
conn = aiohttp.BaseConnector(loop=loop, limit=1)
conn._conns[key] = [(proto, loop.time())]
conn._create_connection = mock.Mock()
conn._create_connection.return_value = helpers.create_future(loop)
conn._create_connection.return_value.set_result(proto)
connection1 = yield from conn.connect(req)
assert connection1._protocol == proto
assert 1 == len(conn._acquired)
assert proto in conn._acquired
assert key in conn._acquired_per_host
assert proto in conn._acquired_per_host[key]
acquired = False
@asyncio.coroutine
def f():
nonlocal acquired
connection2 = yield from conn.connect(req)
acquired = True
assert 1 == len(conn._acquired)
assert 1 == len(conn._acquired_per_host[key])
connection2.release()
task = helpers.ensure_future(f(), loop=loop)
yield from asyncio.sleep(0.01, loop=loop)
assert not acquired
connection1.release()
yield from asyncio.sleep(0, loop=loop)
assert acquired
yield from task
conn.close()
@asyncio.coroutine
def test_connect_with_limit_and_limit_per_host(loop, key):
proto = mock.Mock()
proto.is_connected.return_value = True
req = ClientRequest('GET', URL('http://localhost1:80'), loop=loop)
conn = aiohttp.BaseConnector(loop=loop, limit=1000, limit_per_host=1)
conn._conns[key] = [(proto, loop.time())]
conn._create_connection = mock.Mock()
conn._create_connection.return_value = helpers.create_future(loop)
conn._create_connection.return_value.set_result(proto)
acquired = False
connection1 = yield from conn.connect(req)
@asyncio.coroutine
def f():
nonlocal acquired
connection2 = yield from conn.connect(req)
acquired = True
assert 1 == len(conn._acquired)
assert 1 == len(conn._acquired_per_host[key])
connection2.release()
task = helpers.ensure_future(f(), loop=loop)
yield from asyncio.sleep(0.01, loop=loop)
assert not acquired
connection1.release()
yield from asyncio.sleep(0, loop=loop)
assert acquired
yield from task
conn.close()
@asyncio.coroutine
def test_connect_with_no_limit_and_limit_per_host(loop, key):
proto = mock.Mock()
proto.is_connected.return_value = True
req = ClientRequest('GET', URL('http://localhost1:80'), loop=loop)
conn = aiohttp.BaseConnector(loop=loop, limit=0, limit_per_host=1)
conn._conns[key] = [(proto, loop.time())]
conn._create_connection = mock.Mock()
conn._create_connection.return_value = helpers.create_future(loop)
conn._create_connection.return_value.set_result(proto)
acquired = False
connection1 = yield from conn.connect(req)
@asyncio.coroutine
def f():
nonlocal acquired
connection2 = yield from conn.connect(req)
acquired = True
connection2.release()
task = helpers.ensure_future(f(), loop=loop)
yield from asyncio.sleep(0.01, loop=loop)
assert not acquired
connection1.release()
yield from asyncio.sleep(0, loop=loop)
assert acquired
yield from task
conn.close()
@asyncio.coroutine
def test_connect_with_no_limits(loop, key):
proto = mock.Mock()
proto.is_connected.return_value = True
req = ClientRequest('GET', URL('http://localhost1:80'), loop=loop)
conn = aiohttp.BaseConnector(loop=loop, limit=0, limit_per_host=0)
conn._conns[key] = [(proto, loop.time())]
conn._create_connection = mock.Mock()
conn._create_connection.return_value = helpers.create_future(loop)
conn._create_connection.return_value.set_result(proto)
acquired = False
connection1 = yield from conn.connect(req)
@asyncio.coroutine
def f():
nonlocal acquired
connection2 = yield from conn.connect(req)
acquired = True
assert 1 == len(conn._acquired)
assert 1 == len(conn._acquired_per_host[key])
connection2.release()
task = helpers.ensure_future(f(), loop=loop)
yield from asyncio.sleep(0.01, loop=loop)
assert acquired
connection1.release()
yield from task
conn.close()
@asyncio.coroutine
def test_connect_with_limit_cancelled(loop):
proto = mock.Mock()
proto.is_connected.return_value = True
req = ClientRequest('GET', URL('http://host:80'), loop=loop)
conn = aiohttp.BaseConnector(loop=loop, limit=1)
key = ('host', 80, False)
conn._conns[key] = [(proto, loop.time())]
conn._create_connection = mock.Mock()