Debian Codegraph @

Lib/test/test_httplib.py

raw
1 import enum
2 import errno
3 from http import client, HTTPStatus
4 import io
5 import itertools
6 import os
7 import array
8 import re
9 import socket
10 import threading
11
12 import unittest
13 from unittest import mock
14 TestCase = unittest.TestCase
15
16 from test import support
17 from test.support import os_helper
18 from test.support import socket_helper
19 from test.support.testcase import ExtraAssertions
20
21 support.requires_working_socket(module=True)
22
23 here = os.path.dirname(__file__)
24 # Self-signed cert file for 'localhost'
25 CERT_localhost = os.path.join(here, 'certdata', 'keycert.pem')
26 # Self-signed cert file for 'fakehostname'
27 CERT_fakehostname = os.path.join(here, 'certdata', 'keycert2.pem')
28 # Self-signed cert file for self-signed.pythontest.net
29 CERT_selfsigned_pythontestdotnet = os.path.join(
30 here, 'certdata', 'selfsigned_pythontestdotnet.pem',
31 )
32
33 # constants for testing chunked encoding
34 chunked_start = (
35 'HTTP/1.1 200 OK\r\n'
36 'Transfer-Encoding: chunked\r\n\r\n'
37 'a\r\n'
38 'hello worl\r\n'
39 '3\r\n'
40 'd! \r\n'
41 '8\r\n'
42 'and now \r\n'
43 '22\r\n'
44 'for something completely different\r\n'
45 )
46 chunked_expected = b'hello world! and now for something completely different'
47 chunk_extension = ";foo=bar"
48 last_chunk = "0\r\n"
49 last_chunk_extended = "0" + chunk_extension + "\r\n"
50 trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
51 chunked_end = "\r\n"
52
53 HOST = socket_helper.HOST
54
55 class FakeSocket:
56 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
57 if isinstance(text, str):
58 text = text.encode("ascii")
59 self.text = text
60 self.fileclass = fileclass
61 self.data = b''
62 self.sendall_calls = 0
63 self.file_closed = False
64 self.host = host
65 self.port = port
66
67 def sendall(self, data):
68 self.sendall_calls += 1
69 self.data += data
70
71 def makefile(self, mode, bufsize=None):
72 if mode != 'r' and mode != 'rb':
73 raise client.UnimplementedFileMode()
74 # keep the file around so we can check how much was read from it
75 self.file = self.fileclass(self.text)
76 self.file.close = self.file_close #nerf close ()
77 return self.file
78
79 def file_close(self):
80 self.file_closed = True
81
82 def close(self):
83 pass
84
85 def setsockopt(self, level, optname, value):
86 pass
87
88 class EPipeSocket(FakeSocket):
89
90 def __init__(self, text, pipe_trigger):
91 # When sendall() is called with pipe_trigger, raise EPIPE.
92 FakeSocket.__init__(self, text)
93 self.pipe_trigger = pipe_trigger
94
95 def sendall(self, data):
96 if self.pipe_trigger in data:
97 raise OSError(errno.EPIPE, "gotcha")
98 self.data += data
99
100 def close(self):
101 pass
102
103 class NoEOFBytesIO(io.BytesIO):
104 """Like BytesIO, but raises AssertionError on EOF.
105
106 This is used below to test that http.client doesn't try to read
107 more from the underlying file than it should.
108 """
109 def read(self, n=-1):
110 data = io.BytesIO.read(self, n)
111 if data == b'':
112 raise AssertionError('caller tried to read past EOF')
113 return data
114
115 def readline(self, length=None):
116 data = io.BytesIO.readline(self, length)
117 if data == b'':
118 raise AssertionError('caller tried to read past EOF')
119 return data
120
121 class FakeSocketHTTPConnection(client.HTTPConnection):
122 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
123
124 def __init__(self, *args):
125 self.connections = 0
126 super().__init__('example.com')
127 self.fake_socket_args = args
128 self._create_connection = self.create_connection
129
130 def connect(self):
131 """Count the number of times connect() is invoked"""
132 self.connections += 1
133 return super().connect()
134
135 def create_connection(self, *pos, **kw):
136 return FakeSocket(*self.fake_socket_args)
137
138 class HeaderTests(TestCase, ExtraAssertions):
139 def test_auto_headers(self):
140 # Some headers are added automatically, but should not be added by
141 # .request() if they are explicitly set.
142
143 class HeaderCountingBuffer(list):
144 def __init__(self):
145 self.count = {}
146 def append(self, item):
147 kv = item.split(b':')
148 if len(kv) > 1:
149 # item is a 'Key: Value' header string
150 lcKey = kv[0].decode('ascii').lower()
151 self.count.setdefault(lcKey, 0)
152 self.count[lcKey] += 1
153 list.append(self, item)
154
155 for explicit_header in True, False:
156 for header in 'Content-length', 'Host', 'Accept-encoding':
157 conn = client.HTTPConnection('example.com')
158 conn.sock = FakeSocket('blahblahblah')
159 conn._buffer = HeaderCountingBuffer()
160
161 body = 'spamspamspam'
162 headers = {}
163 if explicit_header:
164 headers[header] = str(len(body))
165 conn.request('POST', '/', body, headers)
166 self.assertEqual(conn._buffer.count[header.lower()], 1)
167
168 def test_content_length_0(self):
169
170 class ContentLengthChecker(list):
171 def __init__(self):
172 list.__init__(self)
173 self.content_length = None
174 def append(self, item):
175 kv = item.split(b':', 1)
176 if len(kv) > 1 and kv[0].lower() == b'content-length':
177 self.content_length = kv[1].strip()
178 list.append(self, item)
179
180 # Here, we're testing that methods expecting a body get a
181 # content-length set to zero if the body is empty (either None or '')
182 bodies = (None, '')
183 methods_with_body = ('PUT', 'POST', 'PATCH')
184 for method, body in itertools.product(methods_with_body, bodies):
185 conn = client.HTTPConnection('example.com')
186 conn.sock = FakeSocket(None)
187 conn._buffer = ContentLengthChecker()
188 conn.request(method, '/', body)
189 self.assertEqual(
190 conn._buffer.content_length, b'0',
191 'Header Content-Length incorrect on {}'.format(method)
192 )
193
194 # For these methods, we make sure that content-length is not set when
195 # the body is None because it might cause unexpected behaviour on the
196 # server.
197 methods_without_body = (
198 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
199 )
200 for method in methods_without_body:
201 conn = client.HTTPConnection('example.com')
202 conn.sock = FakeSocket(None)
203 conn._buffer = ContentLengthChecker()
204 conn.request(method, '/', None)
205 self.assertEqual(
206 conn._buffer.content_length, None,
207 'Header Content-Length set for empty body on {}'.format(method)
208 )
209
210 # If the body is set to '', that's considered to be "present but
211 # empty" rather than "missing", so content length would be set, even
212 # for methods that don't expect a body.
213 for method in methods_without_body:
214 conn = client.HTTPConnection('example.com')
215 conn.sock = FakeSocket(None)
216 conn._buffer = ContentLengthChecker()
217 conn.request(method, '/', '')
218 self.assertEqual(
219 conn._buffer.content_length, b'0',
220 'Header Content-Length incorrect on {}'.format(method)
221 )
222
223 # If the body is set, make sure Content-Length is set.
224 for method in itertools.chain(methods_without_body, methods_with_body):
225 conn = client.HTTPConnection('example.com')
226 conn.sock = FakeSocket(None)
227 conn._buffer = ContentLengthChecker()
228 conn.request(method, '/', ' ')
229 self.assertEqual(
230 conn._buffer.content_length, b'1',
231 'Header Content-Length incorrect on {}'.format(method)
232 )
233
234 def test_putheader(self):
235 conn = client.HTTPConnection('example.com')
236 conn.sock = FakeSocket(None)
237 conn.putrequest('GET','/')
238 conn.putheader('Content-length', 42)
239 self.assertIn(b'Content-length: 42', conn._buffer)
240
241 conn.putheader('Foo', ' bar ')
242 self.assertIn(b'Foo: bar ', conn._buffer)
243 conn.putheader('Bar', '\tbaz\t')
244 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
245 conn.putheader('Authorization', 'Bearer mytoken')
246 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
247 conn.putheader('IterHeader', 'IterA', 'IterB')
248 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
249 conn.putheader('LatinHeader', b'\xFF')
250 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
251 conn.putheader('Utf8Header', b'\xc3\x80')
252 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
253 conn.putheader('C1-Control', b'next\x85line')
254 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
255 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
256 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
257 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
258 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
259 conn.putheader('Key Space', 'value')
260 self.assertIn(b'Key Space: value', conn._buffer)
261 conn.putheader('KeySpace ', 'value')
262 self.assertIn(b'KeySpace : value', conn._buffer)
263 conn.putheader(b'Nonbreak\xa0Space', 'value')
264 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
265 conn.putheader(b'\xa0NonbreakSpace', 'value')
266 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
267
268 def test_ipv6host_header(self):
269 # Default host header on IPv6 transaction should be wrapped by [] if
270 # it is an IPv6 address
271 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
272 b'Accept-Encoding: identity\r\n\r\n'
273 conn = client.HTTPConnection('[2001::]:81')
274 sock = FakeSocket('')
275 conn.sock = sock
276 conn.request('GET', '/foo')
277 self.assertStartsWith(sock.data, expected)
278
279 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
280 b'Accept-Encoding: identity\r\n\r\n'
281 conn = client.HTTPConnection('[2001:102A::]')
282 sock = FakeSocket('')
283 conn.sock = sock
284 conn.request('GET', '/foo')
285 self.assertStartsWith(sock.data, expected)
286
287 expected = b'GET /foo HTTP/1.1\r\nHost: [fe80::]\r\n' \
288 b'Accept-Encoding: identity\r\n\r\n'
289 conn = client.HTTPConnection('[fe80::%2]')
290 sock = FakeSocket('')
291 conn.sock = sock
292 conn.request('GET', '/foo')
293 self.assertStartsWith(sock.data, expected)
294
295 expected = b'GET /foo HTTP/1.1\r\nHost: [fe80::]:81\r\n' \
296 b'Accept-Encoding: identity\r\n\r\n'
297 conn = client.HTTPConnection('[fe80::%2]:81')
298 sock = FakeSocket('')
299 conn.sock = sock
300 conn.request('GET', '/foo')
301 self.assertStartsWith(sock.data, expected)
302
303 def test_malformed_headers_coped_with(self):
304 # Issue 19996
305 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
306 sock = FakeSocket(body)
307 resp = client.HTTPResponse(sock)
308 resp.begin()
309
310 self.assertEqual(resp.getheader('First'), 'val')
311 self.assertEqual(resp.getheader('Second'), 'val')
312
313 def test_parse_all_octets(self):
314 # Ensure no valid header field octet breaks the parser
315 body = (
316 b'HTTP/1.1 200 OK\r\n'
317 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
318 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
319 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
320 b'obs-fold: text\r\n'
321 b' folded with space\r\n'
322 b'\tfolded with tab\r\n'
323 b'Content-Length: 0\r\n'
324 b'\r\n'
325 )
326 sock = FakeSocket(body)
327 resp = client.HTTPResponse(sock)
328 resp.begin()
329 self.assertEqual(resp.getheader('Content-Length'), '0')
330 self.assertEqual(resp.msg['Content-Length'], '0')
331 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
332 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
333 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
334 self.assertEqual(resp.getheader('VCHAR'), vchar)
335 self.assertEqual(resp.msg['VCHAR'], vchar)
336 self.assertIsNotNone(resp.getheader('obs-text'))
337 self.assertIn('obs-text', resp.msg)
338 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
339 self.assertStartsWith(folded, 'text')
340 self.assertIn(' folded with space', folded)
341 self.assertEndsWith(folded, 'folded with tab')
342
343 def test_invalid_headers(self):
344 conn = client.HTTPConnection('example.com')
345 conn.sock = FakeSocket('')
346 conn.putrequest('GET', '/')
347
348 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
349 # longer allowed in header names
350 cases = (
351 (b'Invalid\r\nName', b'ValidValue'),
352 (b'Invalid\rName', b'ValidValue'),
353 (b'Invalid\nName', b'ValidValue'),
354 (b'\r\nInvalidName', b'ValidValue'),
355 (b'\rInvalidName', b'ValidValue'),
356 (b'\nInvalidName', b'ValidValue'),
357 (b' InvalidName', b'ValidValue'),
358 (b'\tInvalidName', b'ValidValue'),
359 (b'Invalid:Name', b'ValidValue'),
360 (b':InvalidName', b'ValidValue'),
361 (b'ValidName', b'Invalid\r\nValue'),
362 (b'ValidName', b'Invalid\rValue'),
363 (b'ValidName', b'Invalid\nValue'),
364 (b'ValidName', b'InvalidValue\r\n'),
365 (b'ValidName', b'InvalidValue\r'),
366 (b'ValidName', b'InvalidValue\n'),
367 )
368 for name, value in cases:
369 with self.subTest((name, value)):
370 with self.assertRaisesRegex(ValueError, 'Invalid header'):
371 conn.putheader(name, value)
372
373 def test_headers_debuglevel(self):
374 body = (
375 b'HTTP/1.1 200 OK\r\n'
376 b'First: val\r\n'
377 b'Second: val1\r\n'
378 b'Second: val2\r\n'
379 )
380 sock = FakeSocket(body)
381 resp = client.HTTPResponse(sock, debuglevel=1)
382 with support.captured_stdout() as output:
383 resp.begin()
384 lines = output.getvalue().splitlines()
385 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
386 self.assertEqual(lines[1], "header: First: val")
387 self.assertEqual(lines[2], "header: Second: val1")
388 self.assertEqual(lines[3], "header: Second: val2")
389
390
391 class HttpMethodTests(TestCase):
392 def test_invalid_method_names(self):
393 methods = (
394 'GET\r',
395 'POST\n',
396 'PUT\n\r',
397 'POST\nValue',
398 'POST\nHOST:abc',
399 'GET\nrHost:abc\n',
400 'POST\rRemainder:\r',
401 'GET\rHOST:\n',
402 '\nPUT'
403 )
404
405 for method in methods:
406 with self.assertRaisesRegex(
407 ValueError, "method can't contain control characters"):
408 conn = client.HTTPConnection('example.com')
409 conn.sock = FakeSocket(None)
410 conn.request(method=method, url="/")
411
412
413 class TransferEncodingTest(TestCase):
414 expected_body = b"It's just a flesh wound"
415
416 def test_endheaders_chunked(self):
417 conn = client.HTTPConnection('example.com')
418 conn.sock = FakeSocket(b'')
419 conn.putrequest('POST', '/')
420 conn.endheaders(self._make_body(), encode_chunked=True)
421
422 _, _, body = self._parse_request(conn.sock.data)
423 body = self._parse_chunked(body)
424 self.assertEqual(body, self.expected_body)
425
426 def test_explicit_headers(self):
427 # explicit chunked
428 conn = client.HTTPConnection('example.com')
429 conn.sock = FakeSocket(b'')
430 # this shouldn't actually be automatically chunk-encoded because the
431 # calling code has explicitly stated that it's taking care of it
432 conn.request(
433 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
434
435 _, headers, body = self._parse_request(conn.sock.data)
436 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
437 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
438 self.assertEqual(body, self.expected_body)
439
440 # explicit chunked, string body
441 conn = client.HTTPConnection('example.com')
442 conn.sock = FakeSocket(b'')
443 conn.request(
444 'POST', '/', self.expected_body.decode('latin-1'),
445 {'Transfer-Encoding': 'chunked'})
446
447 _, headers, body = self._parse_request(conn.sock.data)
448 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
449 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
450 self.assertEqual(body, self.expected_body)
451
452 # User-specified TE, but request() does the chunk encoding
453 conn = client.HTTPConnection('example.com')
454 conn.sock = FakeSocket(b'')
455 conn.request('POST', '/',
456 headers={'Transfer-Encoding': 'gzip, chunked'},
457 encode_chunked=True,
458 body=self._make_body())
459 _, headers, body = self._parse_request(conn.sock.data)
460 self.assertNotIn('content-length', [k.lower() for k in headers])
461 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
462 self.assertEqual(self._parse_chunked(body), self.expected_body)
463
464 def test_request(self):
465 for empty_lines in (False, True,):
466 conn = client.HTTPConnection('example.com')
467 conn.sock = FakeSocket(b'')
468 conn.request(
469 'POST', '/', self._make_body(empty_lines=empty_lines))
470
471 _, headers, body = self._parse_request(conn.sock.data)
472 body = self._parse_chunked(body)
473 self.assertEqual(body, self.expected_body)
474 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
475
476 # Content-Length and Transfer-Encoding SHOULD not be sent in the
477 # same request
478 self.assertNotIn('content-length', [k.lower() for k in headers])
479
480 def test_empty_body(self):
481 # Zero-length iterable should be treated like any other iterable
482 conn = client.HTTPConnection('example.com')
483 conn.sock = FakeSocket(b'')
484 conn.request('POST', '/', ())
485 _, headers, body = self._parse_request(conn.sock.data)
486 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
487 self.assertNotIn('content-length', [k.lower() for k in headers])
488 self.assertEqual(body, b"0\r\n\r\n")
489
490 def _make_body(self, empty_lines=False):
491 lines = self.expected_body.split(b' ')
492 for idx, line in enumerate(lines):
493 # for testing handling empty lines
494 if empty_lines and idx % 2:
495 yield b''
496 if idx < len(lines) - 1:
497 yield line + b' '
498 else:
499 yield line
500
501 def _parse_request(self, data):
502 lines = data.split(b'\r\n')
503 request = lines[0]
504 headers = {}
505 n = 1
506 while n < len(lines) and len(lines[n]) > 0:
507 key, val = lines[n].split(b':')
508 key = key.decode('latin-1').strip()
509 headers[key] = val.decode('latin-1').strip()
510 n += 1
511
512 return request, headers, b'\r\n'.join(lines[n + 1:])
513
514 def _parse_chunked(self, data):
515 body = []
516 trailers = {}
517 n = 0
518 lines = data.split(b'\r\n')
519 # parse body
520 while True:
521 size, chunk = lines[n:n+2]
522 size = int(size, 16)
523
524 if size == 0:
525 n += 1
526 break
527
528 self.assertEqual(size, len(chunk))
529 body.append(chunk)
530
531 n += 2
532 # we /should/ hit the end chunk, but check against the size of
533 # lines so we're not stuck in an infinite loop should we get
534 # malformed data
535 if n > len(lines):
536 break
537
538 return b''.join(body)
539
540
541 class BasicTest(TestCase, ExtraAssertions):
542 def test_dir_with_added_behavior_on_status(self):
543 # see issue40084
544 self.assertTrue({'description', 'name', 'phrase', 'value'} <= set(dir(HTTPStatus(404))))
545
546 def test_simple_httpstatus(self):
547 class CheckedHTTPStatus(enum.IntEnum):
548 """HTTP status codes and reason phrases
549
550 Status codes from the following RFCs are all observed:
551
552 * RFC 7231: Hypertext Transfer Protocol (HTTP/1.1), obsoletes 2616
553 * RFC 6585: Additional HTTP Status Codes
554 * RFC 3229: Delta encoding in HTTP
555 * RFC 4918: HTTP Extensions for WebDAV, obsoletes 2518
556 * RFC 5842: Binding Extensions to WebDAV
557 * RFC 7238: Permanent Redirect
558 * RFC 2295: Transparent Content Negotiation in HTTP
559 * RFC 2774: An HTTP Extension Framework
560 * RFC 7725: An HTTP Status Code to Report Legal Obstacles
561 * RFC 7540: Hypertext Transfer Protocol Version 2 (HTTP/2)
562 * RFC 2324: Hyper Text Coffee Pot Control Protocol (HTCPCP/1.0)
563 * RFC 8297: An HTTP Status Code for Indicating Hints
564 * RFC 8470: Using Early Data in HTTP
565 """
566 def __new__(cls, value, phrase, description=''):
567 obj = int.__new__(cls, value)
568 obj._value_ = value
569
570 obj.phrase = phrase
571 obj.description = description
572 return obj
573
574 @property
575 def is_informational(self):
576 return 100 <= self <= 199
577
578 @property
579 def is_success(self):
580 return 200 <= self <= 299
581
582 @property
583 def is_redirection(self):
584 return 300 <= self <= 399
585
586 @property
587 def is_client_error(self):
588 return 400 <= self <= 499
589
590 @property
591 def is_server_error(self):
592 return 500 <= self <= 599
593
594 # informational
595 CONTINUE = 100, 'Continue', 'Request received, please continue'
596 SWITCHING_PROTOCOLS = (101, 'Switching Protocols',
597 'Switching to new protocol; obey Upgrade header')
598 PROCESSING = 102, 'Processing'
599 EARLY_HINTS = 103, 'Early Hints'
600 # success
601 OK = 200, 'OK', 'Request fulfilled, document follows'
602 CREATED = 201, 'Created', 'Document created, URL follows'
603 ACCEPTED = (202, 'Accepted',
604 'Request accepted, processing continues off-line')
605 NON_AUTHORITATIVE_INFORMATION = (203,
606 'Non-Authoritative Information', 'Request fulfilled from cache')
607 NO_CONTENT = 204, 'No Content', 'Request fulfilled, nothing follows'
608 RESET_CONTENT = 205, 'Reset Content', 'Clear input form for further input'
609 PARTIAL_CONTENT = 206, 'Partial Content', 'Partial content follows'
610 MULTI_STATUS = 207, 'Multi-Status'
611 ALREADY_REPORTED = 208, 'Already Reported'
612 IM_USED = 226, 'IM Used'
613 # redirection
614 MULTIPLE_CHOICES = (300, 'Multiple Choices',
615 'Object has several resources -- see URI list')
616 MOVED_PERMANENTLY = (301, 'Moved Permanently',
617 'Object moved permanently -- see URI list')
618 FOUND = 302, 'Found', 'Object moved temporarily -- see URI list'
619 SEE_OTHER = 303, 'See Other', 'Object moved -- see Method and URL list'
620 NOT_MODIFIED = (304, 'Not Modified',
621 'Document has not changed since given time')
622 USE_PROXY = (305, 'Use Proxy',
623 'You must use proxy specified in Location to access this resource')
624 TEMPORARY_REDIRECT = (307, 'Temporary Redirect',
625 'Object moved temporarily -- see URI list')
626 PERMANENT_REDIRECT = (308, 'Permanent Redirect',
627 'Object moved permanently -- see URI list')
628 # client error
629 BAD_REQUEST = (400, 'Bad Request',
630 'Bad request syntax or unsupported method')
631 UNAUTHORIZED = (401, 'Unauthorized',
632 'No permission -- see authorization schemes')
633 PAYMENT_REQUIRED = (402, 'Payment Required',
634 'No payment -- see charging schemes')
635 FORBIDDEN = (403, 'Forbidden',
636 'Request forbidden -- authorization will not help')
637 NOT_FOUND = (404, 'Not Found',
638 'Nothing matches the given URI')
639 METHOD_NOT_ALLOWED = (405, 'Method Not Allowed',
640 'Specified method is invalid for this resource')
641 NOT_ACCEPTABLE = (406, 'Not Acceptable',
642 'URI not available in preferred format')
643 PROXY_AUTHENTICATION_REQUIRED = (407,
644 'Proxy Authentication Required',
645 'You must authenticate with this proxy before proceeding')
646 REQUEST_TIMEOUT = (408, 'Request Timeout',
647 'Request timed out; try again later')
648 CONFLICT = 409, 'Conflict', 'Request conflict'
649 GONE = (410, 'Gone',
650 'URI no longer exists and has been permanently removed')
651 LENGTH_REQUIRED = (411, 'Length Required',
652 'Client must specify Content-Length')
653 PRECONDITION_FAILED = (412, 'Precondition Failed',
654 'Precondition in headers is false')
655 CONTENT_TOO_LARGE = (413, 'Content Too Large',
656 'Content is too large')
657 REQUEST_ENTITY_TOO_LARGE = CONTENT_TOO_LARGE
658 URI_TOO_LONG = (414, 'URI Too Long', 'URI is too long')
659 REQUEST_URI_TOO_LONG = URI_TOO_LONG
660 UNSUPPORTED_MEDIA_TYPE = (415, 'Unsupported Media Type',
661 'Entity body in unsupported format')
662 RANGE_NOT_SATISFIABLE = (416,
663 'Range Not Satisfiable',
664 'Cannot satisfy request range')
665 REQUESTED_RANGE_NOT_SATISFIABLE = RANGE_NOT_SATISFIABLE
666 EXPECTATION_FAILED = (417, 'Expectation Failed',
667 'Expect condition could not be satisfied')
668 IM_A_TEAPOT = (418, 'I\'m a Teapot',
669 'Server refuses to brew coffee because it is a teapot.')
670 MISDIRECTED_REQUEST = (421, 'Misdirected Request',
671 'Server is not able to produce a response')
672 UNPROCESSABLE_CONTENT = 422, 'Unprocessable Content'
673 UNPROCESSABLE_ENTITY = UNPROCESSABLE_CONTENT
674 LOCKED = 423, 'Locked'
675 FAILED_DEPENDENCY = 424, 'Failed Dependency'
676 TOO_EARLY = 425, 'Too Early'
677 UPGRADE_REQUIRED = 426, 'Upgrade Required'
678 PRECONDITION_REQUIRED = (428, 'Precondition Required',
679 'The origin server requires the request to be conditional')
680 TOO_MANY_REQUESTS = (429, 'Too Many Requests',
681 'The user has sent too many requests in '
682 'a given amount of time ("rate limiting")')
683 REQUEST_HEADER_FIELDS_TOO_LARGE = (431,
684 'Request Header Fields Too Large',
685 'The server is unwilling to process the request because its header '
686 'fields are too large')
687 UNAVAILABLE_FOR_LEGAL_REASONS = (451,
688 'Unavailable For Legal Reasons',
689 'The server is denying access to the '
690 'resource as a consequence of a legal demand')
691 # server errors
692 INTERNAL_SERVER_ERROR = (500, 'Internal Server Error',
693 'Server got itself in trouble')
694 NOT_IMPLEMENTED = (501, 'Not Implemented',
695 'Server does not support this operation')
696 BAD_GATEWAY = (502, 'Bad Gateway',
697 'Invalid responses from another server/proxy')
698 SERVICE_UNAVAILABLE = (503, 'Service Unavailable',
699 'The server cannot process the request due to a high load')
700 GATEWAY_TIMEOUT = (504, 'Gateway Timeout',
701 'The gateway server did not receive a timely response')
702 HTTP_VERSION_NOT_SUPPORTED = (505, 'HTTP Version Not Supported',
703 'Cannot fulfill request')
704 VARIANT_ALSO_NEGOTIATES = 506, 'Variant Also Negotiates'
705 INSUFFICIENT_STORAGE = 507, 'Insufficient Storage'
706 LOOP_DETECTED = 508, 'Loop Detected'
707 NOT_EXTENDED = 510, 'Not Extended'
708 NETWORK_AUTHENTICATION_REQUIRED = (511,
709 'Network Authentication Required',
710 'The client needs to authenticate to gain network access')
711 enum._test_simple_enum(CheckedHTTPStatus, HTTPStatus)
712
713 def test_httpstatus_range(self):
714 """Checks that the statuses are in the 100-599 range"""
715
716 for member in HTTPStatus.__members__.values():
717 self.assertGreaterEqual(member, 100)
718 self.assertLessEqual(member, 599)
719
720 def test_httpstatus_category(self):
721 """Checks that the statuses belong to the standard categories"""
722
723 categories = (
724 ((100, 199), "is_informational"),
725 ((200, 299), "is_success"),
726 ((300, 399), "is_redirection"),
727 ((400, 499), "is_client_error"),
728 ((500, 599), "is_server_error"),
729 )
730 for member in HTTPStatus.__members__.values():
731 for (lower, upper), category in categories:
732 category_indicator = getattr(member, category)
733 if lower <= member <= upper:
734 self.assertTrue(category_indicator)
735 else:
736 self.assertFalse(category_indicator)
737
738 def test_status_lines(self):
739 # Test HTTP status lines
740
741 body = "HTTP/1.1 200 Ok\r\n\r\nText"
742 sock = FakeSocket(body)
743 resp = client.HTTPResponse(sock)
744 resp.begin()
745 self.assertEqual(resp.read(0), b'') # Issue #20007
746 self.assertFalse(resp.isclosed())
747 self.assertFalse(resp.closed)
748 self.assertEqual(resp.read(), b"Text")
749 self.assertTrue(resp.isclosed())
750 self.assertFalse(resp.closed)
751 resp.close()
752 self.assertTrue(resp.closed)
753
754 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
755 sock = FakeSocket(body)
756 resp = client.HTTPResponse(sock)
757 self.assertRaises(client.BadStatusLine, resp.begin)
758
759 def test_bad_status_repr(self):
760 exc = client.BadStatusLine('')
761 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
762
763 def test_partial_reads(self):
764 # if we have Content-Length, HTTPResponse knows when to close itself,
765 # the same behaviour as when we read the whole thing with read()
766 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
767 sock = FakeSocket(body)
768 resp = client.HTTPResponse(sock)
769 resp.begin()
770 self.assertEqual(resp.read(2), b'Te')
771 self.assertFalse(resp.isclosed())
772 self.assertEqual(resp.read(2), b'xt')
773 self.assertTrue(resp.isclosed())
774 self.assertFalse(resp.closed)
775 resp.close()
776 self.assertTrue(resp.closed)
777
778 def test_mixed_reads(self):
779 # readline() should update the remaining length, so that read() knows
780 # how much data is left and does not raise IncompleteRead
781 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
782 sock = FakeSocket(body)
783 resp = client.HTTPResponse(sock)
784 resp.begin()
785 self.assertEqual(resp.readline(), b'Text\r\n')
786 self.assertFalse(resp.isclosed())
787 self.assertEqual(resp.read(), b'Another')
788 self.assertTrue(resp.isclosed())
789 self.assertFalse(resp.closed)
790 resp.close()
791 self.assertTrue(resp.closed)
792
793 def test_partial_readintos(self):
794 # if we have Content-Length, HTTPResponse knows when to close itself,
795 # the same behaviour as when we read the whole thing with read()
796 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
797 sock = FakeSocket(body)
798 resp = client.HTTPResponse(sock)
799 resp.begin()
800 b = bytearray(2)
801 n = resp.readinto(b)
802 self.assertEqual(n, 2)
803 self.assertEqual(bytes(b), b'Te')
804 self.assertFalse(resp.isclosed())
805 n = resp.readinto(b)
806 self.assertEqual(n, 2)
807 self.assertEqual(bytes(b), b'xt')
808 self.assertTrue(resp.isclosed())
809 self.assertFalse(resp.closed)
810 resp.close()
811 self.assertTrue(resp.closed)
812
813 def test_partial_reads_past_end(self):
814 # if we have Content-Length, clip reads to the end
815 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
816 sock = FakeSocket(body)
817 resp = client.HTTPResponse(sock)
818 resp.begin()
819 self.assertEqual(resp.read(10), b'Text')
820 self.assertTrue(resp.isclosed())
821 self.assertFalse(resp.closed)
822 resp.close()
823 self.assertTrue(resp.closed)
824
825 def test_partial_readintos_past_end(self):
826 # if we have Content-Length, clip readintos to the end
827 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
828 sock = FakeSocket(body)
829 resp = client.HTTPResponse(sock)
830 resp.begin()
831 b = bytearray(10)
832 n = resp.readinto(b)
833 self.assertEqual(n, 4)
834 self.assertEqual(bytes(b)[:4], b'Text')
835 self.assertTrue(resp.isclosed())
836 self.assertFalse(resp.closed)
837 resp.close()
838 self.assertTrue(resp.closed)
839
840 def test_partial_reads_no_content_length(self):
841 # when no length is present, the socket should be gracefully closed when
842 # all data was read
843 body = "HTTP/1.1 200 Ok\r\n\r\nText"
844 sock = FakeSocket(body)
845 resp = client.HTTPResponse(sock)
846 resp.begin()
847 self.assertEqual(resp.read(2), b'Te')
848 self.assertFalse(resp.isclosed())
849 self.assertEqual(resp.read(2), b'xt')
850 self.assertEqual(resp.read(1), b'')
851 self.assertTrue(resp.isclosed())
852 self.assertFalse(resp.closed)
853 resp.close()
854 self.assertTrue(resp.closed)
855
856 def test_partial_readintos_no_content_length(self):
857 # when no length is present, the socket should be gracefully closed when
858 # all data was read
859 body = "HTTP/1.1 200 Ok\r\n\r\nText"
860 sock = FakeSocket(body)
861 resp = client.HTTPResponse(sock)
862 resp.begin()
863 b = bytearray(2)
864 n = resp.readinto(b)
865 self.assertEqual(n, 2)
866 self.assertEqual(bytes(b), b'Te')
867 self.assertFalse(resp.isclosed())
868 n = resp.readinto(b)
869 self.assertEqual(n, 2)
870 self.assertEqual(bytes(b), b'xt')
871 n = resp.readinto(b)
872 self.assertEqual(n, 0)
873 self.assertTrue(resp.isclosed())
874
875 def test_partial_reads_incomplete_body(self):
876 # if the server shuts down the connection before the whole
877 # content-length is delivered, the socket is gracefully closed
878 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
879 sock = FakeSocket(body)
880 resp = client.HTTPResponse(sock)
881 resp.begin()
882 self.assertEqual(resp.read(2), b'Te')
883 self.assertFalse(resp.isclosed())
884 self.assertEqual(resp.read(2), b'xt')
885 self.assertEqual(resp.read(1), b'')
886 self.assertTrue(resp.isclosed())
887
888 def test_partial_readintos_incomplete_body(self):
889 # if the server shuts down the connection before the whole
890 # content-length is delivered, the socket is gracefully closed
891 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
892 sock = FakeSocket(body)
893 resp = client.HTTPResponse(sock)
894 resp.begin()
895 b = bytearray(2)
896 n = resp.readinto(b)
897 self.assertEqual(n, 2)
898 self.assertEqual(bytes(b), b'Te')
899 self.assertFalse(resp.isclosed())
900 n = resp.readinto(b)
901 self.assertEqual(n, 2)
902 self.assertEqual(bytes(b), b'xt')
903 n = resp.readinto(b)
904 self.assertEqual(n, 0)
905 self.assertTrue(resp.isclosed())
906 self.assertFalse(resp.closed)
907 resp.close()
908 self.assertTrue(resp.closed)
909
910 def test_host_port(self):
911 # Check invalid host_port
912
913 for hp in ("www.python.org:abc", "user:[email protected]"):
914 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
915
916 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
917 "fe80::207:e9ff:fe9b", 8000),
918 ("www.python.org:80", "www.python.org", 80),
919 ("www.python.org:", "www.python.org", 80),
920 ("www.python.org", "www.python.org", 80),
921 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
922 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
923 c = client.HTTPConnection(hp)
924 self.assertEqual(h, c.host)
925 self.assertEqual(p, c.port)
926
927 def test_response_headers(self):
928 # test response with multiple message headers with the same field name.
929 text = ('HTTP/1.1 200 OK\r\n'
930 'Set-Cookie: Customer="WILE_E_COYOTE"; '
931 'Version="1"; Path="/acme"\r\n'
932 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
933 ' Path="/acme"\r\n'
934 '\r\n'
935 'No body\r\n')
936 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
937 ', '
938 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
939 s = FakeSocket(text)
940 r = client.HTTPResponse(s)
941 r.begin()
942 cookies = r.getheader("Set-Cookie")
943 self.assertEqual(cookies, hdr)
944
945 def test_read_head(self):
946 # Test that the library doesn't attempt to read any data
947 # from a HEAD request. (Tickles SF bug #622042.)
948 sock = FakeSocket(
949 'HTTP/1.1 200 OK\r\n'
950 'Content-Length: 14432\r\n'
951 '\r\n',
952 NoEOFBytesIO)
953 resp = client.HTTPResponse(sock, method="HEAD")
954 resp.begin()
955 if resp.read():
956 self.fail("Did not expect response from HEAD request")
957
958 def test_readinto_head(self):
959 # Test that the library doesn't attempt to read any data
960 # from a HEAD request. (Tickles SF bug #622042.)
961 sock = FakeSocket(
962 'HTTP/1.1 200 OK\r\n'
963 'Content-Length: 14432\r\n'
964 '\r\n',
965 NoEOFBytesIO)
966 resp = client.HTTPResponse(sock, method="HEAD")
967 resp.begin()
968 b = bytearray(5)
969 if resp.readinto(b) != 0:
970 self.fail("Did not expect response from HEAD request")
971 self.assertEqual(bytes(b), b'\x00'*5)
972
973 def test_too_many_headers(self):
974 headers = '\r\n'.join('Header%d: foo' % i
975 for i in range(client._MAXHEADERS + 1)) + '\r\n'
976 text = ('HTTP/1.1 200 OK\r\n' + headers)
977 s = FakeSocket(text)
978 r = client.HTTPResponse(s)
979 self.assertRaisesRegex(client.HTTPException,
980 r"got more than \d+ headers", r.begin)
981
982 def test_send_file(self):
983 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
984 b'Accept-Encoding: identity\r\n'
985 b'Transfer-Encoding: chunked\r\n'
986 b'\r\n')
987
988 with open(__file__, 'rb') as body:
989 conn = client.HTTPConnection('example.com')
990 sock = FakeSocket(body)
991 conn.sock = sock
992 conn.request('GET', '/foo', body)
993 self.assertStartsWith(sock.data, expected)
994
995 def test_send(self):
996 expected = b'this is a test this is only a test'
997 conn = client.HTTPConnection('example.com')
998 sock = FakeSocket(None)
999 conn.sock = sock
1000 conn.send(expected)
1001 self.assertEqual(expected, sock.data)
1002 sock.data = b''
1003 conn.send(array.array('b', expected))
1004 self.assertEqual(expected, sock.data)
1005 sock.data = b''
1006 conn.send(io.BytesIO(expected))
1007 self.assertEqual(expected, sock.data)
1008
1009 def test_send_updating_file(self):
1010 def data():
1011 yield 'data'
1012 yield None
1013 yield 'data_two'
1014
1015 class UpdatingFile(io.TextIOBase):
1016 mode = 'r'
1017 d = data()
1018 def read(self, blocksize=-1):
1019 return next(self.d)
1020
1021 expected = b'data'
1022
1023 conn = client.HTTPConnection('example.com')
1024 sock = FakeSocket("")
1025 conn.sock = sock
1026 conn.send(UpdatingFile())
1027 self.assertEqual(sock.data, expected)
1028
1029
1030 def test_send_iter(self):
1031 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
1032 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
1033 b'\r\nonetwothree'
1034
1035 def body():
1036 yield b"one"
1037 yield b"two"
1038 yield b"three"
1039
1040 conn = client.HTTPConnection('example.com')
1041 sock = FakeSocket("")
1042 conn.sock = sock
1043 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
1044 self.assertEqual(sock.data, expected)
1045
1046 def test_blocksize_request(self):
1047 """Check that request() respects the configured block size."""
1048 blocksize = 8 # For easy debugging.
1049 conn = client.HTTPConnection('example.com', blocksize=blocksize)
1050 sock = FakeSocket(None)
1051 conn.sock = sock
1052 expected = b"a" * blocksize + b"b"
1053 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
1054 self.assertEqual(sock.sendall_calls, 3)
1055 body = sock.data.split(b"\r\n\r\n", 1)[1]
1056 self.assertEqual(body, expected)
1057
1058 def test_blocksize_send(self):
1059 """Check that send() respects the configured block size."""
1060 blocksize = 8 # For easy debugging.
1061 conn = client.HTTPConnection('example.com', blocksize=blocksize)
1062 sock = FakeSocket(None)
1063 conn.sock = sock
1064 expected = b"a" * blocksize + b"b"
1065 conn.send(io.BytesIO(expected))
1066 self.assertEqual(sock.sendall_calls, 2)
1067 self.assertEqual(sock.data, expected)
1068
1069 def test_send_type_error(self):
1070 # See: Issue #12676
1071 conn = client.HTTPConnection('example.com')
1072 conn.sock = FakeSocket('')
1073 with self.assertRaises(TypeError):
1074 conn.request('POST', 'test', conn)
1075
1076 def test_chunked(self):
1077 expected = chunked_expected
1078 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1079 resp = client.HTTPResponse(sock, method="GET")
1080 resp.begin()
1081 self.assertEqual(resp.read(), expected)
1082 resp.close()
1083
1084 # Explicit full read
1085 for n in (-123, -1, None):
1086 with self.subTest('full read', n=n):
1087 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1088 resp = client.HTTPResponse(sock, method="GET")
1089 resp.begin()
1090 self.assertTrue(resp.chunked)
1091 self.assertEqual(resp.read(n), expected)
1092 resp.close()
1093
1094 # Read first chunk
1095 with self.subTest('read1(-1)'):
1096 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1097 resp = client.HTTPResponse(sock, method="GET")
1098 resp.begin()
1099 self.assertTrue(resp.chunked)
1100 self.assertEqual(resp.read1(-1), b"hello worl")
1101 resp.close()
1102
1103 # Various read sizes
1104 for n in range(1, 12):
1105 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1106 resp = client.HTTPResponse(sock, method="GET")
1107 resp.begin()
1108 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
1109 resp.close()
1110
1111 for x in ('', 'foo\r\n'):
1112 sock = FakeSocket(chunked_start + x)
1113 resp = client.HTTPResponse(sock, method="GET")
1114 resp.begin()
1115 try:
1116 resp.read()
1117 except client.IncompleteRead as i:
1118 self.assertEqual(i.partial, expected)
1119 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
1120 self.assertEqual(repr(i), expected_message)
1121 self.assertEqual(str(i), expected_message)
1122 else:
1123 self.fail('IncompleteRead expected')
1124 finally:
1125 resp.close()
1126
1127 def test_readinto_chunked(self):
1128
1129 expected = chunked_expected
1130 nexpected = len(expected)
1131 b = bytearray(128)
1132
1133 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1134 resp = client.HTTPResponse(sock, method="GET")
1135 resp.begin()
1136 n = resp.readinto(b)
1137 self.assertEqual(b[:nexpected], expected)
1138 self.assertEqual(n, nexpected)
1139 resp.close()
1140
1141 # Various read sizes
1142 for n in range(1, 12):
1143 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1144 resp = client.HTTPResponse(sock, method="GET")
1145 resp.begin()
1146 m = memoryview(b)
1147 i = resp.readinto(m[0:n])
1148 i += resp.readinto(m[i:n + i])
1149 i += resp.readinto(m[i:])
1150 self.assertEqual(b[:nexpected], expected)
1151 self.assertEqual(i, nexpected)
1152 resp.close()
1153
1154 for x in ('', 'foo\r\n'):
1155 sock = FakeSocket(chunked_start + x)
1156 resp = client.HTTPResponse(sock, method="GET")
1157 resp.begin()
1158 try:
1159 n = resp.readinto(b)
1160 except client.IncompleteRead as i:
1161 self.assertEqual(i.partial, expected)
1162 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
1163 self.assertEqual(repr(i), expected_message)
1164 self.assertEqual(str(i), expected_message)
1165 else:
1166 self.fail('IncompleteRead expected')
1167 finally:
1168 resp.close()
1169
1170 def test_chunked_head(self):
1171 chunked_start = (
1172 'HTTP/1.1 200 OK\r\n'
1173 'Transfer-Encoding: chunked\r\n\r\n'
1174 'a\r\n'
1175 'hello world\r\n'
1176 '1\r\n'
1177 'd\r\n'
1178 )
1179 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1180 resp = client.HTTPResponse(sock, method="HEAD")
1181 resp.begin()
1182 self.assertEqual(resp.read(), b'')
1183 self.assertEqual(resp.status, 200)
1184 self.assertEqual(resp.reason, 'OK')
1185 self.assertTrue(resp.isclosed())
1186 self.assertFalse(resp.closed)
1187 resp.close()
1188 self.assertTrue(resp.closed)
1189
1190 def test_readinto_chunked_head(self):
1191 chunked_start = (
1192 'HTTP/1.1 200 OK\r\n'
1193 'Transfer-Encoding: chunked\r\n\r\n'
1194 'a\r\n'
1195 'hello world\r\n'
1196 '1\r\n'
1197 'd\r\n'
1198 )
1199 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
1200 resp = client.HTTPResponse(sock, method="HEAD")
1201 resp.begin()
1202 b = bytearray(5)
1203 n = resp.readinto(b)
1204 self.assertEqual(n, 0)
1205 self.assertEqual(bytes(b), b'\x00'*5)
1206 self.assertEqual(resp.status, 200)
1207 self.assertEqual(resp.reason, 'OK')
1208 self.assertTrue(resp.isclosed())
1209 self.assertFalse(resp.closed)
1210 resp.close()
1211 self.assertTrue(resp.closed)
1212
1213 def test_negative_content_length(self):
1214 sock = FakeSocket(
1215 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
1216 resp = client.HTTPResponse(sock, method="GET")
1217 resp.begin()
1218 self.assertEqual(resp.read(), b'Hello\r\n')
1219 self.assertTrue(resp.isclosed())
1220
1221 def test_incomplete_read(self):
1222 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
1223 resp = client.HTTPResponse(sock, method="GET")
1224 resp.begin()
1225 try:
1226 resp.read()
1227 except client.IncompleteRead as i:
1228 self.assertEqual(i.partial, b'Hello\r\n')
1229 self.assertEqual(repr(i),
1230 "IncompleteRead(7 bytes read, 3 more expected)")
1231 self.assertEqual(str(i),
1232 "IncompleteRead(7 bytes read, 3 more expected)")
1233 self.assertTrue(resp.isclosed())
1234 else:
1235 self.fail('IncompleteRead expected')
1236
1237 def test_epipe(self):
1238 sock = EPipeSocket(
1239 "HTTP/1.0 401 Authorization Required\r\n"
1240 "Content-type: text/html\r\n"
1241 "WWW-Authenticate: Basic realm=\"example\"\r\n",
1242 b"Content-Length")
1243 conn = client.HTTPConnection("example.com")
1244 conn.sock = sock
1245 self.assertRaises(OSError,
1246 lambda: conn.request("PUT", "/url", "body"))
1247 resp = conn.getresponse()
1248 self.assertEqual(401, resp.status)
1249 self.assertEqual("Basic realm=\"example\"",
1250 resp.getheader("www-authenticate"))
1251
1252 # Test lines overflowing the max line size (_MAXLINE in http.client)
1253
1254 def test_overflowing_status_line(self):
1255 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
1256 resp = client.HTTPResponse(FakeSocket(body))
1257 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
1258
1259 def test_overflowing_header_line(self):
1260 body = (
1261 'HTTP/1.1 200 OK\r\n'
1262 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1263 )
1264 resp = client.HTTPResponse(FakeSocket(body))
1265 self.assertRaises(client.LineTooLong, resp.begin)
1266
1267 def test_overflowing_header_limit_after_100(self):
1268 body = (
1269 'HTTP/1.1 100 OK\r\n'
1270 'r\n' * 32768
1271 )
1272 resp = client.HTTPResponse(FakeSocket(body))
1273 with self.assertRaises(client.HTTPException) as cm:
1274 resp.begin()
1275 # We must assert more because other reasonable errors that we
1276 # do not want can also be HTTPException derived.
1277 self.assertIn('got more than ', str(cm.exception))
1278 self.assertIn('headers', str(cm.exception))
1279
1280 def test_overflowing_chunked_line(self):
1281 body = (
1282 'HTTP/1.1 200 OK\r\n'
1283 'Transfer-Encoding: chunked\r\n\r\n'
1284 + '0' * 65536 + 'a\r\n'
1285 'hello world\r\n'
1286 '0\r\n'
1287 '\r\n'
1288 )
1289 resp = client.HTTPResponse(FakeSocket(body))
1290 resp.begin()
1291 self.assertRaises(client.LineTooLong, resp.read)
1292
1293 def test_early_eof(self):
1294 # Test httpresponse with no \r\n termination,
1295 body = "HTTP/1.1 200 Ok"
1296 sock = FakeSocket(body)
1297 resp = client.HTTPResponse(sock)
1298 resp.begin()
1299 self.assertEqual(resp.read(), b'')
1300 self.assertTrue(resp.isclosed())
1301 self.assertFalse(resp.closed)
1302 resp.close()
1303 self.assertTrue(resp.closed)
1304
1305 def test_error_leak(self):
1306 # Test that the socket is not leaked if getresponse() fails
1307 conn = client.HTTPConnection('example.com')
1308 response = None
1309 class Response(client.HTTPResponse):
1310 def __init__(self, *pos, **kw):
1311 nonlocal response
1312 response = self # Avoid garbage collector closing the socket
1313 client.HTTPResponse.__init__(self, *pos, **kw)
1314 conn.response_class = Response
1315 conn.sock = FakeSocket('Invalid status line')
1316 conn.request('GET', '/')
1317 self.assertRaises(client.BadStatusLine, conn.getresponse)
1318 self.assertTrue(response.closed)
1319 self.assertTrue(conn.sock.file_closed)
1320
1321 def test_chunked_extension(self):
1322 extra = '3;foo=bar\r\n' + 'abc\r\n'
1323 expected = chunked_expected + b'abc'
1324
1325 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1326 resp = client.HTTPResponse(sock, method="GET")
1327 resp.begin()
1328 self.assertEqual(resp.read(), expected)
1329 resp.close()
1330
1331 def test_chunked_missing_end(self):
1332 """some servers may serve up a short chunked encoding stream"""
1333 expected = chunked_expected
1334 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1335 resp = client.HTTPResponse(sock, method="GET")
1336 resp.begin()
1337 self.assertEqual(resp.read(), expected)
1338 resp.close()
1339
1340 def test_chunked_trailers(self):
1341 """See that trailers are read and ignored"""
1342 expected = chunked_expected
1343 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1344 resp = client.HTTPResponse(sock, method="GET")
1345 resp.begin()
1346 self.assertEqual(resp.read(), expected)
1347 # we should have reached the end of the file
1348 self.assertEqual(sock.file.read(), b"") #we read to the end
1349 resp.close()
1350
1351 def test_chunked_sync(self):
1352 """Check that we don't read past the end of the chunked-encoding stream"""
1353 expected = chunked_expected
1354 extradata = "extradata"
1355 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1356 resp = client.HTTPResponse(sock, method="GET")
1357 resp.begin()
1358 self.assertEqual(resp.read(), expected)
1359 # the file should now have our extradata ready to be read
1360 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
1361 resp.close()
1362
1363 def test_content_length_sync(self):
1364 """Check that we don't read past the end of the Content-Length stream"""
1365 extradata = b"extradata"
1366 expected = b"Hello123\r\n"
1367 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1368 resp = client.HTTPResponse(sock, method="GET")
1369 resp.begin()
1370 self.assertEqual(resp.read(), expected)
1371 # the file should now have our extradata ready to be read
1372 self.assertEqual(sock.file.read(), extradata) #we read to the end
1373 resp.close()
1374
1375 def test_readlines_content_length(self):
1376 extradata = b"extradata"
1377 expected = b"Hello123\r\n"
1378 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1379 resp = client.HTTPResponse(sock, method="GET")
1380 resp.begin()
1381 self.assertEqual(resp.readlines(2000), [expected])
1382 # the file should now have our extradata ready to be read
1383 self.assertEqual(sock.file.read(), extradata) #we read to the end
1384 resp.close()
1385
1386 def test_read1_content_length(self):
1387 extradata = b"extradata"
1388 expected = b"Hello123\r\n"
1389 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1390 resp = client.HTTPResponse(sock, method="GET")
1391 resp.begin()
1392 self.assertEqual(resp.read1(2000), expected)
1393 # the file should now have our extradata ready to be read
1394 self.assertEqual(sock.file.read(), extradata) #we read to the end
1395 resp.close()
1396
1397 def test_readline_bound_content_length(self):
1398 extradata = b"extradata"
1399 expected = b"Hello123\r\n"
1400 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1401 resp = client.HTTPResponse(sock, method="GET")
1402 resp.begin()
1403 self.assertEqual(resp.readline(10), expected)
1404 self.assertEqual(resp.readline(10), b"")
1405 # the file should now have our extradata ready to be read
1406 self.assertEqual(sock.file.read(), extradata) #we read to the end
1407 resp.close()
1408
1409 def test_read1_bound_content_length(self):
1410 extradata = b"extradata"
1411 expected = b"Hello123\r\n"
1412 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1413 resp = client.HTTPResponse(sock, method="GET")
1414 resp.begin()
1415 self.assertEqual(resp.read1(20), expected*2)
1416 self.assertEqual(resp.read(), expected)
1417 # the file should now have our extradata ready to be read
1418 self.assertEqual(sock.file.read(), extradata) #we read to the end
1419 resp.close()
1420
1421 def test_response_fileno(self):
1422 # Make sure fd returned by fileno is valid.
1423 serv = socket.create_server((HOST, 0))
1424 self.addCleanup(serv.close)
1425
1426 result = None
1427 def run_server():
1428 [conn, address] = serv.accept()
1429 with conn, conn.makefile("rb") as reader:
1430 # Read the request header until a blank line
1431 while True:
1432 line = reader.readline()
1433 if not line.rstrip(b"\r\n"):
1434 break
1435 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1436 nonlocal result
1437 result = reader.read()
1438
1439 thread = threading.Thread(target=run_server)
1440 thread.start()
1441 self.addCleanup(thread.join, float(1))
1442 conn = client.HTTPConnection(*serv.getsockname())
1443 conn.request("CONNECT", "dummy:1234")
1444 response = conn.getresponse()
1445 try:
1446 self.assertEqual(response.status, client.OK)
1447 s = socket.socket(fileno=response.fileno())
1448 try:
1449 s.sendall(b"proxied data\n")
1450 finally:
1451 s.detach()
1452 finally:
1453 response.close()
1454 conn.close()
1455 thread.join()
1456 self.assertEqual(result, b"proxied data\n")
1457
1458 def test_large_content_length(self):
1459 serv = socket.create_server((HOST, 0))
1460 self.addCleanup(serv.close)
1461
1462 def run_server():
1463 [conn, address] = serv.accept()
1464 with conn:
1465 while conn.recv(1024):
1466 conn.sendall(
1467 b"HTTP/1.1 200 Ok\r\n"
1468 b"Content-Length: %d\r\n"
1469 b"\r\n" % size)
1470 conn.sendall(b'A' * (size//3))
1471 conn.sendall(b'B' * (size - size//3))
1472
1473 thread = threading.Thread(target=run_server)
1474 thread.start()
1475 self.addCleanup(thread.join, 1.0)
1476
1477 conn = client.HTTPConnection(*serv.getsockname())
1478 try:
1479 for w in range(15, 27):
1480 size = 1 << w
1481 conn.request("GET", "/")
1482 with conn.getresponse() as response:
1483 self.assertEqual(len(response.read()), size)
1484 finally:
1485 conn.close()
1486 thread.join(1.0)
1487
1488 def test_large_content_length_truncated(self):
1489 serv = socket.create_server((HOST, 0))
1490 self.addCleanup(serv.close)
1491
1492 def run_server():
1493 while True:
1494 [conn, address] = serv.accept()
1495 with conn:
1496 conn.recv(1024)
1497 if not size:
1498 break
1499 conn.sendall(
1500 b"HTTP/1.1 200 Ok\r\n"
1501 b"Content-Length: %d\r\n"
1502 b"\r\n"
1503 b"Text" % size)
1504
1505 thread = threading.Thread(target=run_server)
1506 thread.start()
1507 self.addCleanup(thread.join, 1.0)
1508
1509 conn = client.HTTPConnection(*serv.getsockname())
1510 try:
1511 for w in range(18, 65):
1512 size = 1 << w
1513 conn.request("GET", "/")
1514 with conn.getresponse() as response:
1515 self.assertRaises(client.IncompleteRead, response.read)
1516 conn.close()
1517 finally:
1518 conn.close()
1519 size = 0
1520 conn.request("GET", "/")
1521 conn.close()
1522 thread.join(1.0)
1523
1524 def test_putrequest_override_domain_validation(self):
1525 """
1526 It should be possible to override the default validation
1527 behavior in putrequest (bpo-38216).
1528 """
1529 class UnsafeHTTPConnection(client.HTTPConnection):
1530 def _validate_path(self, url):
1531 pass
1532
1533 conn = UnsafeHTTPConnection('example.com')
1534 conn.sock = FakeSocket('')
1535 conn.putrequest('GET', '/\x00')
1536
1537 def test_putrequest_override_host_validation(self):
1538 class UnsafeHTTPConnection(client.HTTPConnection):
1539 def _validate_host(self, url):
1540 pass
1541
1542 conn = UnsafeHTTPConnection('example.com\r\n')
1543 conn.sock = FakeSocket('')
1544 # set skip_host so a ValueError is not raised upon adding the
1545 # invalid URL as the value of the "Host:" header
1546 conn.putrequest('GET', '/', skip_host=1)
1547
1548 def test_putrequest_override_encoding(self):
1549 """
1550 It should be possible to override the default encoding
1551 to transmit bytes in another encoding even if invalid
1552 (bpo-36274).
1553 """
1554 class UnsafeHTTPConnection(client.HTTPConnection):
1555 def _encode_request(self, str_url):
1556 return str_url.encode('utf-8')
1557
1558 conn = UnsafeHTTPConnection('example.com')
1559 conn.sock = FakeSocket('')
1560 conn.putrequest('GET', '/☃')
1561
1562
1563 class ExtendedReadTest(TestCase, ExtraAssertions):
1564 """
1565 Test peek(), read1(), readline()
1566 """
1567 lines = (
1568 'HTTP/1.1 200 OK\r\n'
1569 '\r\n'
1570 'hello world!\n'
1571 'and now \n'
1572 'for something completely different\n'
1573 'foo'
1574 )
1575 lines_expected = lines[lines.find('hello'):].encode("ascii")
1576 lines_chunked = (
1577 'HTTP/1.1 200 OK\r\n'
1578 'Transfer-Encoding: chunked\r\n\r\n'
1579 'a\r\n'
1580 'hello worl\r\n'
1581 '3\r\n'
1582 'd!\n\r\n'
1583 '9\r\n'
1584 'and now \n\r\n'
1585 '23\r\n'
1586 'for something completely different\n\r\n'
1587 '3\r\n'
1588 'foo\r\n'
1589 '0\r\n' # terminating chunk
1590 '\r\n' # end of trailers
1591 )
1592
1593 def setUp(self):
1594 sock = FakeSocket(self.lines)
1595 resp = client.HTTPResponse(sock, method="GET")
1596 resp.begin()
1597 resp.fp = io.BufferedReader(resp.fp)
1598 self.resp = resp
1599
1600
1601
1602 def test_peek(self):
1603 resp = self.resp
1604 # patch up the buffered peek so that it returns not too much stuff
1605 oldpeek = resp.fp.peek
1606 def mypeek(n=-1):
1607 p = oldpeek(n)
1608 if n >= 0:
1609 return p[:n]
1610 return p[:10]
1611 resp.fp.peek = mypeek
1612
1613 all = []
1614 while True:
1615 # try a short peek
1616 p = resp.peek(3)
1617 if p:
1618 self.assertGreater(len(p), 0)
1619 # then unbounded peek
1620 p2 = resp.peek()
1621 self.assertGreaterEqual(len(p2), len(p))
1622 self.assertStartsWith(p2, p)
1623 next = resp.read(len(p2))
1624 self.assertEqual(next, p2)
1625 else:
1626 next = resp.read()
1627 self.assertFalse(next)
1628 all.append(next)
1629 if not next:
1630 break
1631 self.assertEqual(b"".join(all), self.lines_expected)
1632
1633 def test_readline(self):
1634 resp = self.resp
1635 self._verify_readline(self.resp.readline, self.lines_expected)
1636
1637 def test_readline_without_limit(self):
1638 self._verify_readline(self.resp.readline, self.lines_expected, limit=-1)
1639
1640 def _verify_readline(self, readline, expected, limit=5):
1641 all = []
1642 while True:
1643 # short readlines
1644 line = readline(limit)
1645 if line and line != b"foo":
1646 if len(line) < 5:
1647 self.assertEndsWith(line, b"\n")
1648 all.append(line)
1649 if not line:
1650 break
1651 self.assertEqual(b"".join(all), expected)
1652 self.assertTrue(self.resp.isclosed())
1653
1654 def test_read1(self):
1655 resp = self.resp
1656 def r():
1657 res = resp.read1(4)
1658 self.assertLessEqual(len(res), 4)
1659 return res
1660 readliner = Readliner(r)
1661 self._verify_readline(readliner.readline, self.lines_expected)
1662
1663 def test_read1_unbounded(self):
1664 resp = self.resp
1665 all = []
1666 while True:
1667 data = resp.read1()
1668 if not data:
1669 break
1670 all.append(data)
1671 self.assertEqual(b"".join(all), self.lines_expected)
1672 self.assertTrue(resp.isclosed())
1673
1674 def test_read1_bounded(self):
1675 resp = self.resp
1676 all = []
1677 while True:
1678 data = resp.read1(10)
1679 if not data:
1680 break
1681 self.assertLessEqual(len(data), 10)
1682 all.append(data)
1683 self.assertEqual(b"".join(all), self.lines_expected)
1684 self.assertTrue(resp.isclosed())
1685
1686 def test_read1_0(self):
1687 self.assertEqual(self.resp.read1(0), b"")
1688 self.assertFalse(self.resp.isclosed())
1689
1690 def test_peek_0(self):
1691 p = self.resp.peek(0)
1692 self.assertLessEqual(0, len(p))
1693
1694
1695 class ExtendedReadTestContentLengthKnown(ExtendedReadTest):
1696 _header, _body = ExtendedReadTest.lines.split('\r\n\r\n', 1)
1697 lines = _header + f'\r\nContent-Length: {len(_body)}\r\n\r\n' + _body
1698
1699
1700 class ExtendedReadTestChunked(ExtendedReadTest):
1701 """
1702 Test peek(), read1(), readline() in chunked mode
1703 """
1704 lines = (
1705 'HTTP/1.1 200 OK\r\n'
1706 'Transfer-Encoding: chunked\r\n\r\n'
1707 'a\r\n'
1708 'hello worl\r\n'
1709 '3\r\n'
1710 'd!\n\r\n'
1711 '9\r\n'
1712 'and now \n\r\n'
1713 '23\r\n'
1714 'for something completely different\n\r\n'
1715 '3\r\n'
1716 'foo\r\n'
1717 '0\r\n' # terminating chunk
1718 '\r\n' # end of trailers
1719 )
1720
1721
1722 class Readliner:
1723 """
1724 a simple readline class that uses an arbitrary read function and buffering
1725 """
1726 def __init__(self, readfunc):
1727 self.readfunc = readfunc
1728 self.remainder = b""
1729
1730 def readline(self, limit):
1731 data = []
1732 datalen = 0
1733 read = self.remainder
1734 try:
1735 while True:
1736 idx = read.find(b'\n')
1737 if idx != -1:
1738 break
1739 if datalen + len(read) >= limit:
1740 idx = limit - datalen - 1
1741 # read more data
1742 data.append(read)
1743 read = self.readfunc()
1744 if not read:
1745 idx = 0 #eof condition
1746 break
1747 idx += 1
1748 data.append(read[:idx])
1749 self.remainder = read[idx:]
1750 return b"".join(data)
1751 except:
1752 self.remainder = b"".join(data)
1753 raise
1754
1755
1756 class OfflineTest(TestCase, ExtraAssertions):
1757 def test_all(self):
1758 # Documented objects defined in the module should be in __all__
1759 expected = {"responses"} # Allowlist documented dict() object
1760 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1761 # intentionally omitted for simplicity
1762 denylist = {"HTTPMessage", "parse_headers"}
1763 for name in dir(client):
1764 if name.startswith("_") or name in denylist:
1765 continue
1766 module_object = getattr(client, name)
1767 if getattr(module_object, "__module__", None) == "http.client":
1768 expected.add(name)
1769 self.assertCountEqual(client.__all__, expected)
1770
1771 def test_responses(self):
1772 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
1773
1774 def test_client_constants(self):
1775 # Make sure we don't break backward compatibility with 3.4
1776 expected = [
1777 'CONTINUE',
1778 'SWITCHING_PROTOCOLS',
1779 'PROCESSING',
1780 'OK',
1781 'CREATED',
1782 'ACCEPTED',
1783 'NON_AUTHORITATIVE_INFORMATION',
1784 'NO_CONTENT',
1785 'RESET_CONTENT',
1786 'PARTIAL_CONTENT',
1787 'MULTI_STATUS',
1788 'IM_USED',
1789 'MULTIPLE_CHOICES',
1790 'MOVED_PERMANENTLY',
1791 'FOUND',
1792 'SEE_OTHER',
1793 'NOT_MODIFIED',
1794 'USE_PROXY',
1795 'TEMPORARY_REDIRECT',
1796 'BAD_REQUEST',
1797 'UNAUTHORIZED',
1798 'PAYMENT_REQUIRED',
1799 'FORBIDDEN',
1800 'NOT_FOUND',
1801 'METHOD_NOT_ALLOWED',
1802 'NOT_ACCEPTABLE',
1803 'PROXY_AUTHENTICATION_REQUIRED',
1804 'REQUEST_TIMEOUT',
1805 'CONFLICT',
1806 'GONE',
1807 'LENGTH_REQUIRED',
1808 'PRECONDITION_FAILED',
1809 'CONTENT_TOO_LARGE',
1810 'REQUEST_ENTITY_TOO_LARGE',
1811 'URI_TOO_LONG',
1812 'REQUEST_URI_TOO_LONG',
1813 'UNSUPPORTED_MEDIA_TYPE',
1814 'RANGE_NOT_SATISFIABLE',
1815 'REQUESTED_RANGE_NOT_SATISFIABLE',
1816 'EXPECTATION_FAILED',
1817 'IM_A_TEAPOT',
1818 'MISDIRECTED_REQUEST',
1819 'UNPROCESSABLE_CONTENT',
1820 'UNPROCESSABLE_ENTITY',
1821 'LOCKED',
1822 'FAILED_DEPENDENCY',
1823 'UPGRADE_REQUIRED',
1824 'PRECONDITION_REQUIRED',
1825 'TOO_MANY_REQUESTS',
1826 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1827 'UNAVAILABLE_FOR_LEGAL_REASONS',
1828 'INTERNAL_SERVER_ERROR',
1829 'NOT_IMPLEMENTED',
1830 'BAD_GATEWAY',
1831 'SERVICE_UNAVAILABLE',
1832 'GATEWAY_TIMEOUT',
1833 'HTTP_VERSION_NOT_SUPPORTED',
1834 'INSUFFICIENT_STORAGE',
1835 'NOT_EXTENDED',
1836 'NETWORK_AUTHENTICATION_REQUIRED',
1837 'EARLY_HINTS',
1838 'TOO_EARLY'
1839 ]
1840 for const in expected:
1841 with self.subTest(constant=const):
1842 self.assertHasAttr(client, const)
1843
1844
1845 class SourceAddressTest(TestCase):
1846 def setUp(self):
1847 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1848 self.port = socket_helper.bind_port(self.serv)
1849 self.source_port = socket_helper.find_unused_port()
1850 self.serv.listen()
1851 self.conn = None
1852
1853 def tearDown(self):
1854 if self.conn:
1855 self.conn.close()
1856 self.conn = None
1857 self.serv.close()
1858 self.serv = None
1859
1860 def testHTTPConnectionSourceAddress(self):
1861 self.conn = client.HTTPConnection(HOST, self.port,
1862 source_address=('', self.source_port))
1863 self.conn.connect()
1864 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1865
1866 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1867 'http.client.HTTPSConnection not defined')
1868 def testHTTPSConnectionSourceAddress(self):
1869 self.conn = client.HTTPSConnection(HOST, self.port,
1870 source_address=('', self.source_port))
1871 # We don't test anything here other than the constructor not barfing as
1872 # this code doesn't deal with setting up an active running SSL server
1873 # for an ssl_wrapped connect() to actually return from.
1874
1875
1876 class TimeoutTest(TestCase):
1877 PORT = None
1878
1879 def setUp(self):
1880 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1881 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
1882 self.serv.listen()
1883
1884 def tearDown(self):
1885 self.serv.close()
1886 self.serv = None
1887
1888 def testTimeoutAttribute(self):
1889 # This will prove that the timeout gets through HTTPConnection
1890 # and into the socket.
1891
1892 # default -- use global socket timeout
1893 self.assertIsNone(socket.getdefaulttimeout())
1894 socket.setdefaulttimeout(30)
1895 try:
1896 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
1897 httpConn.connect()
1898 finally:
1899 socket.setdefaulttimeout(None)
1900 self.assertEqual(httpConn.sock.gettimeout(), 30)
1901 httpConn.close()
1902
1903 # no timeout -- do not use global socket default
1904 self.assertIsNone(socket.getdefaulttimeout())
1905 socket.setdefaulttimeout(30)
1906 try:
1907 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
1908 timeout=None)
1909 httpConn.connect()
1910 finally:
1911 socket.setdefaulttimeout(None)
1912 self.assertEqual(httpConn.sock.gettimeout(), None)
1913 httpConn.close()
1914
1915 # a value
1916 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
1917 httpConn.connect()
1918 self.assertEqual(httpConn.sock.gettimeout(), 30)
1919 httpConn.close()
1920
1921
1922 class PersistenceTest(TestCase):
1923
1924 def test_reuse_reconnect(self):
1925 # Should reuse or reconnect depending on header from server
1926 tests = (
1927 ('1.0', '', False),
1928 ('1.0', 'Connection: keep-alive\r\n', True),
1929 ('1.1', '', True),
1930 ('1.1', 'Connection: close\r\n', False),
1931 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1932 ('1.1', 'Connection: cloSE\r\n', False),
1933 )
1934 for version, header, reuse in tests:
1935 with self.subTest(version=version, header=header):
1936 msg = (
1937 'HTTP/{} 200 OK\r\n'
1938 '{}'
1939 'Content-Length: 12\r\n'
1940 '\r\n'
1941 'Dummy body\r\n'
1942 ).format(version, header)
1943 conn = FakeSocketHTTPConnection(msg)
1944 self.assertIsNone(conn.sock)
1945 conn.request('GET', '/open-connection')
1946 with conn.getresponse() as response:
1947 self.assertEqual(conn.sock is None, not reuse)
1948 response.read()
1949 self.assertEqual(conn.sock is None, not reuse)
1950 self.assertEqual(conn.connections, 1)
1951 conn.request('GET', '/subsequent-request')
1952 self.assertEqual(conn.connections, 1 if reuse else 2)
1953
1954 def test_disconnected(self):
1955
1956 def make_reset_reader(text):
1957 """Return BufferedReader that raises ECONNRESET at EOF"""
1958 stream = io.BytesIO(text)
1959 def readinto(buffer):
1960 size = io.BytesIO.readinto(stream, buffer)
1961 if size == 0:
1962 raise ConnectionResetError()
1963 return size
1964 stream.readinto = readinto
1965 return io.BufferedReader(stream)
1966
1967 tests = (
1968 (io.BytesIO, client.RemoteDisconnected),
1969 (make_reset_reader, ConnectionResetError),
1970 )
1971 for stream_factory, exception in tests:
1972 with self.subTest(exception=exception):
1973 conn = FakeSocketHTTPConnection(b'', stream_factory)
1974 conn.request('GET', '/eof-response')
1975 self.assertRaises(exception, conn.getresponse)
1976 self.assertIsNone(conn.sock)
1977 # HTTPConnection.connect() should be automatically invoked
1978 conn.request('GET', '/reconnect')
1979 self.assertEqual(conn.connections, 2)
1980
1981 def test_100_close(self):
1982 conn = FakeSocketHTTPConnection(
1983 b'HTTP/1.1 100 Continue\r\n'
1984 b'\r\n'
1985 # Missing final response
1986 )
1987 conn.request('GET', '/', headers={'Expect': '100-continue'})
1988 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1989 self.assertIsNone(conn.sock)
1990 conn.request('GET', '/reconnect')
1991 self.assertEqual(conn.connections, 2)
1992
1993
1994 class HTTPSTest(TestCase):
1995
1996 def setUp(self):
1997 if not hasattr(client, 'HTTPSConnection'):
1998 self.skipTest('ssl support required')
1999
2000 def make_server(self, certfile):
2001 from test.ssl_servers import make_https_server
2002 return make_https_server(self, certfile=certfile)
2003
2004 def test_attributes(self):
2005 # simple test to check it's storing the timeout
2006 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
2007 self.assertEqual(h.timeout, 30)
2008
2009 def test_networked(self):
2010 # Default settings: requires a valid cert from a trusted CA
2011 import ssl
2012 support.requires('network')
2013 with socket_helper.transient_internet('self-signed.pythontest.net'):
2014 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
2015 with self.assertRaises(ssl.SSLError) as exc_info:
2016 h.request('GET', '/')
2017 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
2018
2019 def test_networked_noverification(self):
2020 # Switch off cert verification
2021 import ssl
2022 support.requires('network')
2023 with socket_helper.transient_internet('self-signed.pythontest.net'):
2024 context = ssl._create_unverified_context()
2025 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
2026 context=context)
2027 h.request('GET', '/')
2028 resp = h.getresponse()
2029 h.close()
2030 self.assertIn('nginx', resp.getheader('server'))
2031 resp.close()
2032
2033 @support.system_must_validate_cert
2034 def test_networked_trusted_by_default_cert(self):
2035 # Default settings: requires a valid cert from a trusted CA
2036 support.requires('network')
2037 with socket_helper.transient_internet('www.python.org'):
2038 h = client.HTTPSConnection('www.python.org', 443)
2039 h.request('GET', '/')
2040 resp = h.getresponse()
2041 content_type = resp.getheader('content-type')
2042 resp.close()
2043 h.close()
2044 self.assertIn('text/html', content_type)
2045
2046 def test_networked_good_cert(self):
2047 # We feed the server's cert as a validating cert
2048 import ssl
2049 support.requires('network')
2050 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
2051 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
2052 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2053 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
2054 self.assertEqual(context.check_hostname, True)
2055 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
2056 try:
2057 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
2058 context=context)
2059 h.request('GET', '/')
2060 resp = h.getresponse()
2061 except ssl.SSLError as ssl_err:
2062 ssl_err_str = str(ssl_err)
2063 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
2064 # modern Linux distros (Debian Buster, etc) default OpenSSL
2065 # configurations it'll fail saying "key too weak" until we
2066 # address https://bugs.python.org/issue36816 to use a proper
2067 # key size on self-signed.pythontest.net.
2068 if re.search(r'(?i)key.too.weak', ssl_err_str):
2069 raise unittest.SkipTest(
2070 f'Got {ssl_err_str} trying to connect '
2071 f'to {selfsigned_pythontestdotnet}. '
2072 'See https://bugs.python.org/issue36816.')
2073 raise
2074 server_string = resp.getheader('server')
2075 resp.close()
2076 h.close()
2077 self.assertIn('nginx', server_string)
2078
2079 @support.requires_resource('walltime')
2080 def test_networked_bad_cert(self):
2081 # We feed a "CA" cert that is unrelated to the server's cert
2082 import ssl
2083 support.requires('network')
2084 with socket_helper.transient_internet('self-signed.pythontest.net'):
2085 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2086 context.load_verify_locations(CERT_localhost)
2087 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
2088 with self.assertRaises(ssl.SSLError) as exc_info:
2089 h.request('GET', '/')
2090 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
2091
2092 def test_local_unknown_cert(self):
2093 # The custom cert isn't known to the default trust bundle
2094 import ssl
2095 server = self.make_server(CERT_localhost)
2096 h = client.HTTPSConnection('localhost', server.port)
2097 with self.assertRaises(ssl.SSLError) as exc_info:
2098 h.request('GET', '/')
2099 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
2100
2101 def test_local_good_hostname(self):
2102 # The (valid) cert validates the HTTPS hostname
2103 import ssl
2104 server = self.make_server(CERT_localhost)
2105 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2106 context.load_verify_locations(CERT_localhost)
2107 h = client.HTTPSConnection('localhost', server.port, context=context)
2108 self.addCleanup(h.close)
2109 h.request('GET', '/nonexistent')
2110 resp = h.getresponse()
2111 self.addCleanup(resp.close)
2112 self.assertEqual(resp.status, 404)
2113
2114 def test_local_bad_hostname(self):
2115 # The (valid) cert doesn't validate the HTTPS hostname
2116 import ssl
2117 server = self.make_server(CERT_fakehostname)
2118 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2119 context.load_verify_locations(CERT_fakehostname)
2120 h = client.HTTPSConnection('localhost', server.port, context=context)
2121 with self.assertRaises(ssl.CertificateError):
2122 h.request('GET', '/')
2123
2124 # Same with explicit context.check_hostname=True
2125 context.check_hostname = True
2126 h = client.HTTPSConnection('localhost', server.port, context=context)
2127 with self.assertRaises(ssl.CertificateError):
2128 h.request('GET', '/')
2129
2130 # With context.check_hostname=False, the mismatching is ignored
2131 context.check_hostname = False
2132 h = client.HTTPSConnection('localhost', server.port, context=context)
2133 h.request('GET', '/nonexistent')
2134 resp = h.getresponse()
2135 resp.close()
2136 h.close()
2137 self.assertEqual(resp.status, 404)
2138
2139 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
2140 'http.client.HTTPSConnection not available')
2141 def test_host_port(self):
2142 # Check invalid host_port
2143
2144 for hp in ("www.python.org:abc", "user:[email protected]"):
2145 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
2146
2147 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
2148 "fe80::207:e9ff:fe9b", 8000),
2149 ("www.python.org:443", "www.python.org", 443),
2150 ("www.python.org:", "www.python.org", 443),
2151 ("www.python.org", "www.python.org", 443),
2152 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
2153 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
2154 443)):
2155 c = client.HTTPSConnection(hp)
2156 self.assertEqual(h, c.host)
2157 self.assertEqual(p, c.port)
2158
2159 def test_tls13_pha(self):
2160 import ssl
2161 if not ssl.HAS_TLSv1_3:
2162 self.skipTest('TLS 1.3 support required')
2163 # just check status of PHA flag
2164 h = client.HTTPSConnection('localhost', 443)
2165 self.assertTrue(h._context.post_handshake_auth)
2166
2167 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
2168 self.assertFalse(context.post_handshake_auth)
2169 h = client.HTTPSConnection('localhost', 443, context=context)
2170 self.assertIs(h._context, context)
2171 self.assertFalse(h._context.post_handshake_auth)
2172
2173 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT, cert_file=CERT_localhost)
2174 context.post_handshake_auth = True
2175 h = client.HTTPSConnection('localhost', 443, context=context)
2176 self.assertTrue(h._context.post_handshake_auth)
2177
2178
2179 class RequestBodyTest(TestCase):
2180 """Test cases where a request includes a message body."""
2181
2182 def setUp(self):
2183 self.conn = client.HTTPConnection('example.com')
2184 self.conn.sock = self.sock = FakeSocket("")
2185 self.conn.sock = self.sock
2186
2187 def get_headers_and_fp(self):
2188 f = io.BytesIO(self.sock.data)
2189 f.readline() # read the request line
2190 message = client.parse_headers(f)
2191 return message, f
2192
2193 def test_list_body(self):
2194 # Note that no content-length is automatically calculated for
2195 # an iterable. The request will fall back to send chunked
2196 # transfer encoding.
2197 cases = (
2198 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
2199 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
2200 )
2201 for body, expected in cases:
2202 with self.subTest(body):
2203 self.conn = client.HTTPConnection('example.com')
2204 self.conn.sock = self.sock = FakeSocket('')
2205
2206 self.conn.request('PUT', '/url', body)
2207 msg, f = self.get_headers_and_fp()
2208 self.assertNotIn('Content-Type', msg)
2209 self.assertNotIn('Content-Length', msg)
2210 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
2211 self.assertEqual(expected, f.read())
2212
2213 def test_manual_content_length(self):
2214 # Set an incorrect content-length so that we can verify that
2215 # it will not be over-ridden by the library.
2216 self.conn.request("PUT", "/url", "body",
2217 {"Content-Length": "42"})
2218 message, f = self.get_headers_and_fp()
2219 self.assertEqual("42", message.get("content-length"))
2220 self.assertEqual(4, len(f.read()))
2221
2222 def test_ascii_body(self):
2223 self.conn.request("PUT", "/url", "body")
2224 message, f = self.get_headers_and_fp()
2225 self.assertEqual("text/plain", message.get_content_type())
2226 self.assertIsNone(message.get_charset())
2227 self.assertEqual("4", message.get("content-length"))
2228 self.assertEqual(b'body', f.read())
2229
2230 def test_latin1_body(self):
2231 self.conn.request("PUT", "/url", "body\xc1")
2232 message, f = self.get_headers_and_fp()
2233 self.assertEqual("text/plain", message.get_content_type())
2234 self.assertIsNone(message.get_charset())
2235 self.assertEqual("5", message.get("content-length"))
2236 self.assertEqual(b'body\xc1', f.read())
2237
2238 def test_bytes_body(self):
2239 self.conn.request("PUT", "/url", b"body\xc1")
2240 message, f = self.get_headers_and_fp()
2241 self.assertEqual("text/plain", message.get_content_type())
2242 self.assertIsNone(message.get_charset())
2243 self.assertEqual("5", message.get("content-length"))
2244 self.assertEqual(b'body\xc1', f.read())
2245
2246 def test_text_file_body(self):
2247 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
2248 with open(os_helper.TESTFN, "w", encoding="utf-8") as f:
2249 f.write("body")
2250 with open(os_helper.TESTFN, encoding="utf-8") as f:
2251 self.conn.request("PUT", "/url", f)
2252 message, f = self.get_headers_and_fp()
2253 self.assertEqual("text/plain", message.get_content_type())
2254 self.assertIsNone(message.get_charset())
2255 # No content-length will be determined for files; the body
2256 # will be sent using chunked transfer encoding instead.
2257 self.assertIsNone(message.get("content-length"))
2258 self.assertEqual("chunked", message.get("transfer-encoding"))
2259 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
2260
2261 def test_binary_file_body(self):
2262 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
2263 with open(os_helper.TESTFN, "wb") as f:
2264 f.write(b"body\xc1")
2265 with open(os_helper.TESTFN, "rb") as f:
2266 self.conn.request("PUT", "/url", f)
2267 message, f = self.get_headers_and_fp()
2268 self.assertEqual("text/plain", message.get_content_type())
2269 self.assertIsNone(message.get_charset())
2270 self.assertEqual("chunked", message.get("Transfer-Encoding"))
2271 self.assertNotIn("Content-Length", message)
2272 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
2273
2274
2275 class HTTPResponseTest(TestCase):
2276
2277 def setUp(self):
2278 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
2279 second-value\r\n\r\nText"
2280 sock = FakeSocket(body)
2281 self.resp = client.HTTPResponse(sock)
2282 self.resp.begin()
2283
2284 def test_getting_header(self):
2285 header = self.resp.getheader('My-Header')
2286 self.assertEqual(header, 'first-value, second-value')
2287
2288 header = self.resp.getheader('My-Header', 'some default')
2289 self.assertEqual(header, 'first-value, second-value')
2290
2291 def test_getting_nonexistent_header_with_string_default(self):
2292 header = self.resp.getheader('No-Such-Header', 'default-value')
2293 self.assertEqual(header, 'default-value')
2294
2295 def test_getting_nonexistent_header_with_iterable_default(self):
2296 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
2297 self.assertEqual(header, 'default, values')
2298
2299 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
2300 self.assertEqual(header, 'default, values')
2301
2302 def test_getting_nonexistent_header_without_default(self):
2303 header = self.resp.getheader('No-Such-Header')
2304 self.assertEqual(header, None)
2305
2306 def test_getting_header_defaultint(self):
2307 header = self.resp.getheader('No-Such-Header',default=42)
2308 self.assertEqual(header, 42)
2309
2310 class TunnelTests(TestCase, ExtraAssertions):
2311 def setUp(self):
2312 response_text = (
2313 'HTTP/1.1 200 OK\r\n\r\n' # Reply to CONNECT
2314 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
2315 'Content-Length: 42\r\n\r\n'
2316 )
2317 self.host = 'proxy.com'
2318 self.port = client.HTTP_PORT
2319 self.conn = client.HTTPConnection(self.host)
2320 self.conn._create_connection = self._create_connection(response_text)
2321
2322 def tearDown(self):
2323 self.conn.close()
2324
2325 def _create_connection(self, response_text):
2326 def create_connection(address, timeout=None, source_address=None):
2327 return FakeSocket(response_text, host=address[0], port=address[1])
2328 return create_connection
2329
2330 def test_set_tunnel_host_port_headers_add_host_missing(self):
2331 tunnel_host = 'destination.com'
2332 tunnel_port = 8888
2333 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2334 tunnel_headers_after = tunnel_headers.copy()
2335 tunnel_headers_after['Host'] = '%s:%d' % (tunnel_host, tunnel_port)
2336 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2337 headers=tunnel_headers)
2338 self.conn.request('HEAD', '/', '')
2339 self.assertEqual(self.conn.sock.host, self.host)
2340 self.assertEqual(self.conn.sock.port, self.port)
2341 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2342 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2343 self.assertEqual(self.conn._tunnel_headers, tunnel_headers_after)
2344
2345 def test_set_tunnel_host_port_headers_set_host_identical(self):
2346 tunnel_host = 'destination.com'
2347 tunnel_port = 8888
2348 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)',
2349 'Host': '%s:%d' % (tunnel_host, tunnel_port)}
2350 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2351 headers=tunnel_headers)
2352 self.conn.request('HEAD', '/', '')
2353 self.assertEqual(self.conn.sock.host, self.host)
2354 self.assertEqual(self.conn.sock.port, self.port)
2355 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2356 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2357 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2358
2359 def test_set_tunnel_host_port_headers_set_host_different(self):
2360 tunnel_host = 'destination.com'
2361 tunnel_port = 8888
2362 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)',
2363 'Host': '%s:%d' % ('example.com', 4200)}
2364 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2365 headers=tunnel_headers)
2366 self.conn.request('HEAD', '/', '')
2367 self.assertEqual(self.conn.sock.host, self.host)
2368 self.assertEqual(self.conn.sock.port, self.port)
2369 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2370 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2371 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2372
2373 def test_disallow_set_tunnel_after_connect(self):
2374 # Once connected, we shouldn't be able to tunnel anymore
2375 self.conn.connect()
2376 self.assertRaises(RuntimeError, self.conn.set_tunnel,
2377 'destination.com')
2378
2379 def test_connect_with_tunnel(self):
2380 d = {
2381 b'host': b'destination.com',
2382 b'port': client.HTTP_PORT,
2383 }
2384 self.conn.set_tunnel(d[b'host'].decode('ascii'))
2385 self.conn.request('HEAD', '/', '')
2386 self.assertEqual(self.conn.sock.host, self.host)
2387 self.assertEqual(self.conn.sock.port, self.port)
2388 self.assertIn(b'CONNECT %(host)s:%(port)d HTTP/1.1\r\n'
2389 b'Host: %(host)s:%(port)d\r\n\r\n' % d,
2390 self.conn.sock.data)
2391 self.assertIn(b'HEAD / HTTP/1.1\r\nHost: %(host)s\r\n' % d,
2392 self.conn.sock.data)
2393
2394 def test_connect_with_tunnel_with_default_port(self):
2395 d = {
2396 b'host': b'destination.com',
2397 b'port': client.HTTP_PORT,
2398 }
2399 self.conn.set_tunnel(d[b'host'].decode('ascii'), port=d[b'port'])
2400 self.conn.request('HEAD', '/', '')
2401 self.assertEqual(self.conn.sock.host, self.host)
2402 self.assertEqual(self.conn.sock.port, self.port)
2403 self.assertIn(b'CONNECT %(host)s:%(port)d HTTP/1.1\r\n'
2404 b'Host: %(host)s:%(port)d\r\n\r\n' % d,
2405 self.conn.sock.data)
2406 self.assertIn(b'HEAD / HTTP/1.1\r\nHost: %(host)s\r\n' % d,
2407 self.conn.sock.data)
2408
2409 def test_connect_with_tunnel_with_nonstandard_port(self):
2410 d = {
2411 b'host': b'destination.com',
2412 b'port': 8888,
2413 }
2414 self.conn.set_tunnel(d[b'host'].decode('ascii'), port=d[b'port'])
2415 self.conn.request('HEAD', '/', '')
2416 self.assertEqual(self.conn.sock.host, self.host)
2417 self.assertEqual(self.conn.sock.port, self.port)
2418 self.assertIn(b'CONNECT %(host)s:%(port)d HTTP/1.1\r\n'
2419 b'Host: %(host)s:%(port)d\r\n\r\n' % d,
2420 self.conn.sock.data)
2421 self.assertIn(b'HEAD / HTTP/1.1\r\nHost: %(host)s:%(port)d\r\n' % d,
2422 self.conn.sock.data)
2423
2424 # This request is not RFC-valid, but it's been possible with the library
2425 # for years, so don't break it unexpectedly... This also tests
2426 # case-insensitivity when injecting Host: headers if they're missing.
2427 def test_connect_with_tunnel_with_different_host_header(self):
2428 d = {
2429 b'host': b'destination.com',
2430 b'tunnel_host_header': b'example.com:9876',
2431 b'port': client.HTTP_PORT,
2432 }
2433 self.conn.set_tunnel(
2434 d[b'host'].decode('ascii'),
2435 headers={'HOST': d[b'tunnel_host_header'].decode('ascii')})
2436 self.conn.request('HEAD', '/', '')
2437 self.assertEqual(self.conn.sock.host, self.host)
2438 self.assertEqual(self.conn.sock.port, self.port)
2439 self.assertIn(b'CONNECT %(host)s:%(port)d HTTP/1.1\r\n'
2440 b'HOST: %(tunnel_host_header)s\r\n\r\n' % d,
2441 self.conn.sock.data)
2442 self.assertIn(b'HEAD / HTTP/1.1\r\nHost: %(host)s\r\n' % d,
2443 self.conn.sock.data)
2444
2445 def test_connect_with_tunnel_different_host(self):
2446 d = {
2447 b'host': b'destination.com',
2448 b'port': client.HTTP_PORT,
2449 }
2450 self.conn.set_tunnel(d[b'host'].decode('ascii'))
2451 self.conn.request('HEAD', '/', '')
2452 self.assertEqual(self.conn.sock.host, self.host)
2453 self.assertEqual(self.conn.sock.port, self.port)
2454 self.assertIn(b'CONNECT %(host)s:%(port)d HTTP/1.1\r\n'
2455 b'Host: %(host)s:%(port)d\r\n\r\n' % d,
2456 self.conn.sock.data)
2457 self.assertIn(b'HEAD / HTTP/1.1\r\nHost: %(host)s\r\n' % d,
2458 self.conn.sock.data)
2459
2460 def test_connect_with_tunnel_idna(self):
2461 dest = '\u03b4\u03c0\u03b8.gr'
2462 dest_port = b'%s:%d' % (dest.encode('idna'), client.HTTP_PORT)
2463 expected = b'CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n' % (
2464 dest_port, dest_port)
2465 self.conn.set_tunnel(dest)
2466 self.conn.request('HEAD', '/', '')
2467 self.assertEqual(self.conn.sock.host, self.host)
2468 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2469 self.assertIn(expected, self.conn.sock.data)
2470
2471 def test_tunnel_connect_single_send_connection_setup(self):
2472 """Regresstion test for https://bugs.python.org/issue43332."""
2473 with mock.patch.object(self.conn, 'send') as mock_send:
2474 self.conn.set_tunnel('destination.com')
2475 self.conn.connect()
2476 self.conn.request('GET', '/')
2477 mock_send.assert_called()
2478 # Likely 2, but this test only cares about the first.
2479 self.assertGreater(
2480 len(mock_send.mock_calls), 1,
2481 msg=f'unexpected number of send calls: {mock_send.mock_calls}')
2482 proxy_setup_data_sent = mock_send.mock_calls[0][1][0]
2483 self.assertIn(b'CONNECT destination.com', proxy_setup_data_sent)
2484 self.assertEndsWith(proxy_setup_data_sent, b'\r\n\r\n',
2485 msg=f'unexpected proxy data sent {proxy_setup_data_sent!r}')
2486
2487 def test_connect_put_request(self):
2488 d = {
2489 b'host': b'destination.com',
2490 b'port': client.HTTP_PORT,
2491 }
2492 self.conn.set_tunnel(d[b'host'].decode('ascii'))
2493 self.conn.request('PUT', '/', '')
2494 self.assertEqual(self.conn.sock.host, self.host)
2495 self.assertEqual(self.conn.sock.port, self.port)
2496 self.assertIn(b'CONNECT %(host)s:%(port)d HTTP/1.1\r\n'
2497 b'Host: %(host)s:%(port)d\r\n\r\n' % d,
2498 self.conn.sock.data)
2499 self.assertIn(b'PUT / HTTP/1.1\r\nHost: %(host)s\r\n' % d,
2500 self.conn.sock.data)
2501
2502 def test_connect_put_request_ipv6(self):
2503 self.conn.set_tunnel('[1:2:3::4]', 1234)
2504 self.conn.request('PUT', '/', '')
2505 self.assertEqual(self.conn.sock.host, self.host)
2506 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2507 self.assertIn(b'CONNECT [1:2:3::4]:1234', self.conn.sock.data)
2508 self.assertIn(b'Host: [1:2:3::4]:1234', self.conn.sock.data)
2509
2510 def test_connect_put_request_ipv6_port(self):
2511 self.conn.set_tunnel('[1:2:3::4]:1234')
2512 self.conn.request('PUT', '/', '')
2513 self.assertEqual(self.conn.sock.host, self.host)
2514 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2515 self.assertIn(b'CONNECT [1:2:3::4]:1234', self.conn.sock.data)
2516 self.assertIn(b'Host: [1:2:3::4]:1234', self.conn.sock.data)
2517
2518 def test_tunnel_debuglog(self):
2519 expected_header = 'X-Dummy: 1'
2520 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2521
2522 self.conn.set_debuglevel(1)
2523 self.conn._create_connection = self._create_connection(response_text)
2524 self.conn.set_tunnel('destination.com')
2525
2526 with support.captured_stdout() as output:
2527 self.conn.request('PUT', '/', '')
2528 lines = output.getvalue().splitlines()
2529 self.assertIn('header: {}'.format(expected_header), lines)
2530
2531 def test_proxy_response_headers(self):
2532 expected_header = ('X-Dummy', '1')
2533 response_text = (
2534 'HTTP/1.0 200 OK\r\n'
2535 '{0}\r\n\r\n'.format(':'.join(expected_header))
2536 )
2537
2538 self.conn._create_connection = self._create_connection(response_text)
2539 self.conn.set_tunnel('destination.com')
2540
2541 self.conn.request('PUT', '/', '')
2542 headers = self.conn.get_proxy_response_headers()
2543 self.assertIn(expected_header, headers.items())
2544
2545 def test_no_proxy_response_headers(self):
2546 expected_header = ('X-Dummy', '1')
2547 response_text = (
2548 'HTTP/1.0 200 OK\r\n'
2549 '{0}\r\n\r\n'.format(':'.join(expected_header))
2550 )
2551
2552 self.conn._create_connection = self._create_connection(response_text)
2553
2554 self.conn.request('PUT', '/', '')
2555 headers = self.conn.get_proxy_response_headers()
2556 self.assertIsNone(headers)
2557
2558 def test_tunnel_leak(self):
2559 sock = None
2560
2561 def _create_connection(address, timeout=None, source_address=None):
2562 nonlocal sock
2563 sock = FakeSocket(
2564 'HTTP/1.1 404 NOT FOUND\r\n\r\n',
2565 host=address[0],
2566 port=address[1],
2567 )
2568 return sock
2569
2570 self.conn._create_connection = _create_connection
2571 self.conn.set_tunnel('destination.com')
2572 exc = None
2573 try:
2574 self.conn.request('HEAD', '/', '')
2575 except OSError as e:
2576 # keeping a reference to exc keeps response alive in the traceback
2577 exc = e
2578 self.assertIsNotNone(exc)
2579 self.assertTrue(sock.file_closed)
2580
2581
2582 if __name__ == '__main__':
2583 unittest.main(verbosity=2)