Debian Codegraph @

lib-python/3/test/test_httplib.py

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