forked from urllib3/urllib3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_socketlevel.py
1524 lines (1227 loc) · 52.1 KB
/
test_socketlevel.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
# TODO: Break this module up into pieces. Maybe group by functionality tested
# rather than the socket level-ness of it.
from urllib3 import HTTPConnectionPool, HTTPSConnectionPool
from urllib3.poolmanager import proxy_from_url
from urllib3.exceptions import (
MaxRetryError,
ProxyError,
ReadTimeoutError,
SSLError,
ProtocolError,
)
from urllib3.response import httplib
from urllib3.util.ssl_ import HAS_SNI
from urllib3.util.timeout import Timeout
from urllib3.util.retry import Retry
from urllib3._collections import HTTPHeaderDict
from dummyserver.testcase import SocketDummyServerTestCase, consume_socket
from dummyserver.server import (
DEFAULT_CERTS, DEFAULT_CA, COMBINED_CERT_AND_KEY, get_unreachable_address)
from .. import onlyPy3, LogRecorder
try:
from mimetools import Message as MimeToolMessage
except ImportError:
class MimeToolMessage(object):
pass
from collections import OrderedDict
from threading import Event
import select
import socket
import ssl
import pytest
from test import fails_on_travis_gce
class TestCookies(SocketDummyServerTestCase):
def test_multi_setcookie(self):
def multicookie_response_handler(listener):
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
sock.send(b'HTTP/1.1 200 OK\r\n'
b'Set-Cookie: foo=1\r\n'
b'Set-Cookie: bar=1\r\n'
b'\r\n')
sock.close()
self._start_server(multicookie_response_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
r = pool.request('GET', '/', retries=0)
self.assertEqual(r.headers, {'set-cookie': 'foo=1, bar=1'})
self.assertEqual(r.headers.getlist('set-cookie'), ['foo=1', 'bar=1'])
class TestSNI(SocketDummyServerTestCase):
@pytest.mark.skipif(not HAS_SNI, reason='SNI-support not available')
def test_hostname_in_first_request_packet(self):
done_receiving = Event()
self.buf = b''
def socket_handler(listener):
sock = listener.accept()[0]
self.buf = sock.recv(65536) # We only accept one packet
done_receiving.set() # let the test know it can proceed
sock.close()
self._start_server(socket_handler)
pool = HTTPSConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
try:
pool.request('GET', '/', retries=0)
except MaxRetryError: # We are violating the protocol
pass
done_receiving.wait()
self.assertIn(self.host.encode('ascii'), self.buf,
"missing hostname in SSL handshake")
class TestClientCerts(SocketDummyServerTestCase):
"""
Tests for client certificate support.
"""
def _wrap_in_ssl(self, sock):
"""
Given a single socket, wraps it in TLS.
"""
return ssl.wrap_socket(
sock,
ssl_version=ssl.PROTOCOL_SSLv23,
cert_reqs=ssl.CERT_REQUIRED,
ca_certs=DEFAULT_CA,
certfile=DEFAULT_CERTS['certfile'],
keyfile=DEFAULT_CERTS['keyfile'],
server_side=True
)
def test_client_certs_two_files(self):
"""
Having a client cert in a separate file to its associated key works
properly.
"""
done_receiving = Event()
client_certs = []
def socket_handler(listener):
sock = listener.accept()[0]
sock = self._wrap_in_ssl(sock)
client_certs.append(sock.getpeercert())
data = b''
while not data.endswith(b'\r\n\r\n'):
data += sock.recv(8192)
sock.sendall(
b'HTTP/1.1 200 OK\r\n'
b'Server: testsocket\r\n'
b'Connection: close\r\n'
b'Content-Length: 6\r\n'
b'\r\n'
b'Valid!'
)
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
pool = HTTPSConnectionPool(
self.host,
self.port,
cert_file=DEFAULT_CERTS['certfile'],
key_file=DEFAULT_CERTS['keyfile'],
cert_reqs='REQUIRED',
ca_certs=DEFAULT_CA,
)
self.addCleanup(pool.close)
pool.request('GET', '/', retries=0)
done_receiving.set()
self.assertEqual(len(client_certs), 1)
def test_client_certs_one_file(self):
"""
Having a client cert and its associated private key in just one file
works properly.
"""
done_receiving = Event()
client_certs = []
def socket_handler(listener):
sock = listener.accept()[0]
sock = self._wrap_in_ssl(sock)
client_certs.append(sock.getpeercert())
data = b''
while not data.endswith(b'\r\n\r\n'):
data += sock.recv(8192)
sock.sendall(
b'HTTP/1.1 200 OK\r\n'
b'Server: testsocket\r\n'
b'Connection: close\r\n'
b'Content-Length: 6\r\n'
b'\r\n'
b'Valid!'
)
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
pool = HTTPSConnectionPool(
self.host,
self.port,
cert_file=COMBINED_CERT_AND_KEY,
cert_reqs='REQUIRED',
ca_certs=DEFAULT_CA,
)
self.addCleanup(pool.close)
pool.request('GET', '/', retries=0)
done_receiving.set()
self.assertEqual(len(client_certs), 1)
def test_missing_client_certs_raises_error(self):
"""
Having client certs not be present causes an error.
"""
done_receiving = Event()
def socket_handler(listener):
sock = listener.accept()[0]
try:
self._wrap_in_ssl(sock)
except ssl.SSLError:
pass
done_receiving.wait(5)
sock.close()
self._start_server(socket_handler)
pool = HTTPSConnectionPool(
self.host,
self.port,
cert_reqs='REQUIRED',
ca_certs=DEFAULT_CA,
)
self.addCleanup(pool.close)
try:
pool.request('GET', '/', retries=0)
except MaxRetryError:
done_receiving.set()
else:
done_receiving.set()
self.fail(
"Expected server to reject connection due to missing client "
"certificates"
)
class TestSocketClosing(SocketDummyServerTestCase):
def test_recovery_when_server_closes_connection(self):
# Does the pool work seamlessly if an open connection in the
# connection pool gets hung up on by the server, then reaches
# the front of the queue again?
done_closing = Event()
def socket_handler(listener):
for i in 0, 1:
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65536)
body = 'Response %d' % i
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(body), body)).encode('utf-8'))
sock.close() # simulate a server timing out, closing socket
done_closing.set() # let the test know it can proceed
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
response = pool.request('GET', '/', retries=0)
self.assertEqual(response.status, 200)
self.assertEqual(response.data, b'Response 0')
done_closing.wait() # wait until the socket in our pool gets closed
response = pool.request('GET', '/', retries=0)
self.assertEqual(response.status, 200)
self.assertEqual(response.data, b'Response 1')
def test_connection_refused(self):
# Does the pool retry if there is no listener on the port?
host, port = get_unreachable_address()
http = HTTPConnectionPool(host, port, maxsize=3, block=True)
self.addCleanup(http.close)
self.assertRaises(MaxRetryError, http.request, 'GET', '/', retries=0, release_conn=False)
self.assertEqual(http.pool.qsize(), http.pool.maxsize)
def test_connection_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
while not sock.recv(65536).endswith(b'\r\n\r\n'):
pass
timed_out.wait()
sock.close()
self._start_server(socket_handler)
http = HTTPConnectionPool(self.host, self.port,
timeout=0.001,
retries=False,
maxsize=3,
block=True)
self.addCleanup(http.close)
try:
self.assertRaises(ReadTimeoutError, http.request, 'GET', '/', release_conn=False)
finally:
timed_out.set()
self.assertEqual(http.pool.qsize(), http.pool.maxsize)
def test_read_timeout_dont_retry_method_not_in_whitelist(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
sock.recv(65536)
timed_out.wait()
sock.close()
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port, timeout=0.001, retries=True)
self.addCleanup(pool.close)
try:
self.assertRaises(ReadTimeoutError, pool.request, 'POST', '/')
finally:
timed_out.set()
def test_https_connection_read_timeout(self):
""" Handshake timeouts should fail with a Timeout"""
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
while not sock.recv(65536):
pass
timed_out.wait()
sock.close()
self._start_server(socket_handler)
pool = HTTPSConnectionPool(self.host, self.port, timeout=0.001, retries=False)
self.addCleanup(pool.close)
try:
self.assertRaises(ReadTimeoutError, pool.request, 'GET', '/')
finally:
timed_out.set()
def test_timeout_errors_cause_retries(self):
def socket_handler(listener):
sock_timeout = listener.accept()[0]
# Wait for a second request before closing the first socket.
sock = listener.accept()[0]
sock_timeout.close()
# Second request.
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
# Now respond immediately.
body = 'Response 2'
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(body), body)).encode('utf-8'))
sock.close()
# In situations where the main thread throws an exception, the server
# thread can hang on an accept() call. This ensures everything times
# out within 1 second. This should be long enough for any socket
# operations in the test suite to complete
default_timeout = socket.getdefaulttimeout()
socket.setdefaulttimeout(1)
try:
self._start_server(socket_handler)
t = Timeout(connect=0.001, read=0.001)
pool = HTTPConnectionPool(self.host, self.port, timeout=t)
self.addCleanup(pool.close)
response = pool.request('GET', '/', retries=1)
self.assertEqual(response.status, 200)
self.assertEqual(response.data, b'Response 2')
finally:
socket.setdefaulttimeout(default_timeout)
def test_delayed_body_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b''
body = 'Hi'
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n' % len(body)).encode('utf-8'))
timed_out.wait()
sock.send(body.encode('utf-8'))
sock.close()
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
response = pool.urlopen('GET', '/', retries=0, preload_content=False,
timeout=Timeout(connect=1, read=0.001))
try:
self.assertRaises(ReadTimeoutError, response.read)
finally:
timed_out.set()
def test_delayed_body_read_timeout_with_preload(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b''
body = 'Hi'
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n' % len(body)).encode('utf-8'))
timed_out.wait(5)
sock.close()
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
try:
self.assertRaises(ReadTimeoutError, pool.urlopen,
'GET', '/', retries=False,
timeout=Timeout(connect=1, read=0.001))
finally:
timed_out.set()
def test_incomplete_response(self):
body = 'Response'
partial_body = body[:2]
def socket_handler(listener):
sock = listener.accept()[0]
# Consume request
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65536)
# Send partial response and close socket.
sock.send((
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(body), partial_body)).encode('utf-8')
)
sock.close()
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
response = pool.request('GET', '/', retries=0, preload_content=False)
self.assertRaises(ProtocolError, response.read)
def test_retry_weird_http_version(self):
""" Retry class should handle httplib.BadStatusLine errors properly """
def socket_handler(listener):
sock = listener.accept()[0]
# First request.
# Pause before responding so the first request times out.
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
# send unknown http protocol
body = "bad http 0.5 response"
sock.send(('HTTP/0.5 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(body), body)).encode('utf-8'))
sock.close()
# Second request.
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
# Now respond immediately.
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'foo' % (len('foo'))).encode('utf-8'))
sock.close() # Close the socket.
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
retry = Retry(read=1)
response = pool.request('GET', '/', retries=retry)
self.assertEqual(response.status, 200)
self.assertEqual(response.data, b'foo')
def test_connection_cleanup_on_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b''
body = 'Hi'
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n' % len(body)).encode('utf-8'))
timed_out.wait()
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
poolsize = pool.pool.qsize()
response = pool.urlopen('GET', '/', retries=0, preload_content=False,
timeout=Timeout(connect=1, read=0.001))
try:
self.assertRaises(ReadTimeoutError, response.read)
self.assertEqual(poolsize, pool.pool.qsize())
finally:
timed_out.set()
def test_connection_cleanup_on_protocol_error_during_read(self):
body = 'Response'
partial_body = body[:2]
def socket_handler(listener):
sock = listener.accept()[0]
# Consume request
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65536)
# Send partial response and close socket.
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(body), partial_body)).encode('utf-8'))
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
poolsize = pool.pool.qsize()
response = pool.request('GET', '/', retries=0, preload_content=False)
self.assertRaises(ProtocolError, response.read)
self.assertEqual(poolsize, pool.pool.qsize())
def test_connection_closed_on_read_timeout_preload_false(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
# Consume request
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65535)
# Send partial chunked response and then hang.
sock.send((
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Transfer-Encoding: chunked\r\n'
'\r\n'
'8\r\n'
'12345678\r\n').encode('utf-8')
)
timed_out.wait(5)
# Expect a new request, but keep hold of the old socket to avoid
# leaking it. Because we don't want to hang this thread, we
# actually use select.select to confirm that a new request is
# coming in: this lets us time the thread out.
rlist, _, _ = select.select([listener], [], [], 1)
assert rlist
new_sock = listener.accept()[0]
# Consume request
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf = new_sock.recv(65535)
# Send complete chunked response.
new_sock.send((
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Transfer-Encoding: chunked\r\n'
'\r\n'
'8\r\n'
'12345678\r\n'
'0\r\n\r\n').encode('utf-8')
)
new_sock.close()
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port) as pool:
# First request should fail.
response = pool.urlopen('GET', '/', retries=0,
preload_content=False,
timeout=Timeout(connect=1, read=0.1))
try:
self.assertRaises(ReadTimeoutError, response.read)
finally:
timed_out.set()
# Second should succeed.
response = pool.urlopen('GET', '/', retries=0,
preload_content=False,
timeout=Timeout(connect=1, read=0.1))
self.assertEqual(len(response.read()), 8)
def test_closing_response_actually_closes_connection(self):
done_closing = Event()
complete = Event()
def socket_handler(listener):
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf = sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: 0\r\n'
'\r\n').encode('utf-8'))
# Wait for the socket to close.
done_closing.wait(timeout=1)
# Look for the empty string to show that the connection got closed.
# Don't get stuck in a timeout.
sock.settimeout(1)
new_data = sock.recv(65536)
self.assertFalse(new_data)
sock.close()
complete.set()
self._start_server(socket_handler)
pool = HTTPConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
response = pool.request('GET', '/', retries=0, preload_content=False)
self.assertEqual(response.status, 200)
response.close()
done_closing.set() # wait until the socket in our pool gets closed
successful = complete.wait(timeout=1)
if not successful:
self.fail("Timed out waiting for connection close")
def test_release_conn_param_is_respected_after_timeout_retry(self):
"""For successful ```urlopen(release_conn=False)```,
the connection isn't released, even after a retry.
This test allows a retry: one request fails, the next request succeeds.
This is a regression test for issue #651 [1], where the connection
would be released if the initial request failed, even if a retry
succeeded.
[1] <https://github.com/shazow/urllib3/issues/651>
"""
def socket_handler(listener):
sock = listener.accept()[0]
consume_socket(sock)
# Close the connection, without sending any response (not even the
# HTTP status line). This will trigger a `Timeout` on the client,
# inside `urlopen()`.
sock.close()
# Expect a new request. Because we don't want to hang this thread,
# we actually use select.select to confirm that a new request is
# coming in: this lets us time the thread out.
rlist, _, _ = select.select([listener], [], [], 5)
assert rlist
sock = listener.accept()[0]
consume_socket(sock)
# Send complete chunked response.
sock.send((
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Transfer-Encoding: chunked\r\n'
'\r\n'
'8\r\n'
'12345678\r\n'
'0\r\n\r\n').encode('utf-8')
)
sock.close()
self._start_server(socket_handler)
with HTTPConnectionPool(self.host, self.port, maxsize=1) as pool:
# First request should fail, but the timeout and `retries=1` should
# save it.
response = pool.urlopen('GET', '/', retries=1,
release_conn=False, preload_content=False,
timeout=Timeout(connect=1, read=0.001))
# The connection should still be on the response object, and none
# should be in the pool. We opened two though.
self.assertEqual(pool.num_connections, 2)
self.assertEqual(pool.pool.qsize(), 0)
self.assertIsNotNone(response.connection)
# Consume the data. This should put the connection back.
response.read()
self.assertEqual(pool.pool.qsize(), 1)
self.assertIsNone(response.connection)
class TestProxyManager(SocketDummyServerTestCase):
def test_simple(self):
def echo_socket_handler(listener):
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(buf), buf.decode('utf-8'))).encode('utf-8'))
sock.close()
self._start_server(echo_socket_handler)
base_url = 'http://%s:%d' % (self.host, self.port)
proxy = proxy_from_url(base_url)
self.addCleanup(proxy.clear)
r = proxy.request('GET', 'http://google.com/')
self.assertEqual(r.status, 200)
# FIXME: The order of the headers is not predictable right now. We
# should fix that someday (maybe when we migrate to
# OrderedDict/MultiDict).
self.assertEqual(sorted(r.data.split(b'\r\n')),
sorted([
b'GET http://google.com/ HTTP/1.1',
b'Host: google.com',
b'Accept-Encoding: identity',
b'Accept: */*',
b'',
b'',
]))
def test_headers(self):
def echo_socket_handler(listener):
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(buf), buf.decode('utf-8'))).encode('utf-8'))
sock.close()
self._start_server(echo_socket_handler)
base_url = 'http://%s:%d' % (self.host, self.port)
# Define some proxy headers.
proxy_headers = HTTPHeaderDict({'For The Proxy': 'YEAH!'})
proxy = proxy_from_url(base_url, proxy_headers=proxy_headers)
self.addCleanup(proxy.clear)
conn = proxy.connection_from_url('http://www.google.com/')
r = conn.urlopen('GET', 'http://www.google.com/', assert_same_host=False)
self.assertEqual(r.status, 200)
# FIXME: The order of the headers is not predictable right now. We
# should fix that someday (maybe when we migrate to
# OrderedDict/MultiDict).
self.assertIn(b'For The Proxy: YEAH!\r\n', r.data)
def test_retries(self):
close_event = Event()
def echo_socket_handler(listener):
sock = listener.accept()[0]
# First request, which should fail
sock.close()
# Second request
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: %d\r\n'
'\r\n'
'%s' % (len(buf), buf.decode('utf-8'))).encode('utf-8'))
sock.close()
close_event.set()
self._start_server(echo_socket_handler)
base_url = 'http://%s:%d' % (self.host, self.port)
proxy = proxy_from_url(base_url)
self.addCleanup(proxy.clear)
conn = proxy.connection_from_url('http://www.google.com')
r = conn.urlopen('GET', 'http://www.google.com',
assert_same_host=False, retries=1)
self.assertEqual(r.status, 200)
close_event.wait(timeout=1)
self.assertRaises(ProxyError, conn.urlopen, 'GET',
'http://www.google.com',
assert_same_host=False, retries=False)
def test_connect_reconn(self):
def proxy_ssl_one(listener):
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
s = buf.decode('utf-8')
if not s.startswith('CONNECT '):
sock.send(('HTTP/1.1 405 Method not allowed\r\n'
'Allow: CONNECT\r\n\r\n').encode('utf-8'))
sock.close()
return
if not s.startswith('CONNECT %s:443' % (self.host,)):
sock.send(('HTTP/1.1 403 Forbidden\r\n\r\n').encode('utf-8'))
sock.close()
return
sock.send(('HTTP/1.1 200 Connection Established\r\n\r\n').encode('utf-8'))
ssl_sock = ssl.wrap_socket(sock,
server_side=True,
keyfile=DEFAULT_CERTS['keyfile'],
certfile=DEFAULT_CERTS['certfile'],
ca_certs=DEFAULT_CA)
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += ssl_sock.recv(65536)
ssl_sock.send(('HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: 2\r\n'
'Connection: close\r\n'
'\r\n'
'Hi').encode('utf-8'))
ssl_sock.close()
def echo_socket_handler(listener):
proxy_ssl_one(listener)
proxy_ssl_one(listener)
self._start_server(echo_socket_handler)
base_url = 'http://%s:%d' % (self.host, self.port)
proxy = proxy_from_url(base_url)
self.addCleanup(proxy.clear)
url = 'https://{0}'.format(self.host)
conn = proxy.connection_from_url(url)
r = conn.urlopen('GET', url, retries=0)
self.assertEqual(r.status, 200)
r = conn.urlopen('GET', url, retries=0)
self.assertEqual(r.status, 200)
def test_connect_ipv6_addr(self):
ipv6_addr = '2001:4998:c:a06::2:4008'
def echo_socket_handler(listener):
sock = listener.accept()[0]
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += sock.recv(65536)
s = buf.decode('utf-8')
if s.startswith('CONNECT [%s]:443' % (ipv6_addr,)):
sock.send(b'HTTP/1.1 200 Connection Established\r\n\r\n')
ssl_sock = ssl.wrap_socket(sock,
server_side=True,
keyfile=DEFAULT_CERTS['keyfile'],
certfile=DEFAULT_CERTS['certfile'])
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += ssl_sock.recv(65536)
ssl_sock.send(b'HTTP/1.1 200 OK\r\n'
b'Content-Type: text/plain\r\n'
b'Content-Length: 2\r\n'
b'Connection: close\r\n'
b'\r\n'
b'Hi')
ssl_sock.close()
else:
sock.close()
self._start_server(echo_socket_handler)
base_url = 'http://%s:%d' % (self.host, self.port)
proxy = proxy_from_url(base_url)
self.addCleanup(proxy.clear)
url = 'https://[{0}]'.format(ipv6_addr)
conn = proxy.connection_from_url(url)
try:
r = conn.urlopen('GET', url, retries=0)
self.assertEqual(r.status, 200)
except MaxRetryError:
self.fail('Invalid IPv6 format in HTTP CONNECT request')
class TestSSL(SocketDummyServerTestCase):
def test_ssl_failure_midway_through_conn(self):
def socket_handler(listener):
sock = listener.accept()[0]
sock2 = sock.dup()
ssl_sock = ssl.wrap_socket(sock,
server_side=True,
keyfile=DEFAULT_CERTS['keyfile'],
certfile=DEFAULT_CERTS['certfile'],
ca_certs=DEFAULT_CA)
buf = b''
while not buf.endswith(b'\r\n\r\n'):
buf += ssl_sock.recv(65536)
# Deliberately send from the non-SSL socket.
sock2.send((
'HTTP/1.1 200 OK\r\n'
'Content-Type: text/plain\r\n'
'Content-Length: 2\r\n'
'\r\n'
'Hi').encode('utf-8'))
sock2.close()
ssl_sock.close()
self._start_server(socket_handler)
pool = HTTPSConnectionPool(self.host, self.port)
self.addCleanup(pool.close)
with self.assertRaises(MaxRetryError) as cm:
pool.request('GET', '/', retries=0)
self.assertIsInstance(cm.exception.reason, SSLError)
def test_ssl_read_timeout(self):
timed_out = Event()
def socket_handler(listener):
sock = listener.accept()[0]
ssl_sock = ssl.wrap_socket(sock,
server_side=True,
keyfile=DEFAULT_CERTS['keyfile'],
certfile=DEFAULT_CERTS['certfile'],
ca_certs=DEFAULT_CA)
buf = b''
while not buf.endswith(b'\r\n\r\n'):