blob: 5fb45924e508221ebdd84e53758bd716b813ae6c [file] [log] [blame]
Jeremy Hylton636950f2009-03-28 04:34:21 +00001import errno
Angelin BOOZ68526fe2020-09-21 15:11:06 +02002from http import client, HTTPStatus
Jeremy Hylton8fff7922007-08-03 20:56:14 +00003import io
R David Murraybeed8402015-03-22 15:18:23 -04004import itertools
Antoine Pitrou803e6d62010-10-13 10:36:15 +00005import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00006import array
Gregory P. Smith2cc02232019-05-06 17:54:06 -04007import re
Guido van Rossumd8faa362007-04-27 19:54:29 +00008import socket
Antoine Pitrou88c60c92017-09-18 23:50:44 +02009import threading
Pablo Galindoaa542c22019-08-08 23:25:46 +010010import warnings
Jeremy Hylton121d34a2003-07-08 12:36:58 +000011
Gregory P. Smithb4066372010-01-03 03:28:29 +000012import unittest
Gregory P. Smithc25910a2021-03-07 23:35:13 -080013from unittest import mock
Gregory P. Smithb4066372010-01-03 03:28:29 +000014TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000015
Benjamin Petersonee8712c2008-05-20 21:35:26 +000016from test import support
Hai Shi883bc632020-07-06 17:12:49 +080017from test.support import os_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030018from test.support import socket_helper
Hai Shi883bc632020-07-06 17:12:49 +080019from test.support import warnings_helper
20
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000021
Antoine Pitrou803e6d62010-10-13 10:36:15 +000022here = os.path.dirname(__file__)
23# Self-signed cert file for 'localhost'
24CERT_localhost = os.path.join(here, 'keycert.pem')
25# Self-signed cert file for 'fakehostname'
26CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010027# Self-signed cert file for self-signed.pythontest.net
28CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000029
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000030# constants for testing chunked encoding
31chunked_start = (
32 'HTTP/1.1 200 OK\r\n'
33 'Transfer-Encoding: chunked\r\n\r\n'
34 'a\r\n'
35 'hello worl\r\n'
36 '3\r\n'
37 'd! \r\n'
38 '8\r\n'
39 'and now \r\n'
40 '22\r\n'
41 'for something completely different\r\n'
42)
43chunked_expected = b'hello world! and now for something completely different'
44chunk_extension = ";foo=bar"
45last_chunk = "0\r\n"
46last_chunk_extended = "0" + chunk_extension + "\r\n"
47trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
48chunked_end = "\r\n"
49
Serhiy Storchaka16994912020-04-25 10:06:29 +030050HOST = socket_helper.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000051
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000052class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040053 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000054 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000055 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000056 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000057 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000058 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010059 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020060 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040061 self.host = host
62 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000063
Jeremy Hylton2c178252004-08-07 16:28:14 +000064 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010065 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000066 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000067
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000068 def makefile(self, mode, bufsize=None):
69 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000070 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000071 # keep the file around so we can check how much was read from it
72 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020073 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000074 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000075
Serhiy Storchakab491e052014-12-01 13:07:45 +020076 def file_close(self):
77 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000078
Senthil Kumaran9da047b2014-04-14 13:07:56 -040079 def close(self):
80 pass
81
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050082 def setsockopt(self, level, optname, value):
83 pass
84
Jeremy Hylton636950f2009-03-28 04:34:21 +000085class EPipeSocket(FakeSocket):
86
87 def __init__(self, text, pipe_trigger):
88 # When sendall() is called with pipe_trigger, raise EPIPE.
89 FakeSocket.__init__(self, text)
90 self.pipe_trigger = pipe_trigger
91
92 def sendall(self, data):
93 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020094 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000095 self.data += data
96
97 def close(self):
98 pass
99
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300100class NoEOFBytesIO(io.BytesIO):
101 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000102
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000103 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000104 more from the underlying file than it should.
105 """
106 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000107 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000108 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000109 raise AssertionError('caller tried to read past EOF')
110 return data
111
112 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000113 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000114 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000115 raise AssertionError('caller tried to read past EOF')
116 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000117
R David Murraycae7bdb2015-04-05 19:26:29 -0400118class FakeSocketHTTPConnection(client.HTTPConnection):
119 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
120
121 def __init__(self, *args):
122 self.connections = 0
123 super().__init__('example.com')
124 self.fake_socket_args = args
125 self._create_connection = self.create_connection
126
127 def connect(self):
128 """Count the number of times connect() is invoked"""
129 self.connections += 1
130 return super().connect()
131
132 def create_connection(self, *pos, **kw):
133 return FakeSocket(*self.fake_socket_args)
134
Jeremy Hylton2c178252004-08-07 16:28:14 +0000135class HeaderTests(TestCase):
136 def test_auto_headers(self):
137 # Some headers are added automatically, but should not be added by
138 # .request() if they are explicitly set.
139
Jeremy Hylton2c178252004-08-07 16:28:14 +0000140 class HeaderCountingBuffer(list):
141 def __init__(self):
142 self.count = {}
143 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000144 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000145 if len(kv) > 1:
146 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000147 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000148 self.count.setdefault(lcKey, 0)
149 self.count[lcKey] += 1
150 list.append(self, item)
151
152 for explicit_header in True, False:
153 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000154 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000155 conn.sock = FakeSocket('blahblahblah')
156 conn._buffer = HeaderCountingBuffer()
157
158 body = 'spamspamspam'
159 headers = {}
160 if explicit_header:
161 headers[header] = str(len(body))
162 conn.request('POST', '/', body, headers)
163 self.assertEqual(conn._buffer.count[header.lower()], 1)
164
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800165 def test_content_length_0(self):
166
167 class ContentLengthChecker(list):
168 def __init__(self):
169 list.__init__(self)
170 self.content_length = None
171 def append(self, item):
172 kv = item.split(b':', 1)
173 if len(kv) > 1 and kv[0].lower() == b'content-length':
174 self.content_length = kv[1].strip()
175 list.append(self, item)
176
R David Murraybeed8402015-03-22 15:18:23 -0400177 # Here, we're testing that methods expecting a body get a
178 # content-length set to zero if the body is empty (either None or '')
179 bodies = (None, '')
180 methods_with_body = ('PUT', 'POST', 'PATCH')
181 for method, body in itertools.product(methods_with_body, bodies):
182 conn = client.HTTPConnection('example.com')
183 conn.sock = FakeSocket(None)
184 conn._buffer = ContentLengthChecker()
185 conn.request(method, '/', body)
186 self.assertEqual(
187 conn._buffer.content_length, b'0',
188 'Header Content-Length incorrect on {}'.format(method)
189 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800190
R David Murraybeed8402015-03-22 15:18:23 -0400191 # For these methods, we make sure that content-length is not set when
192 # the body is None because it might cause unexpected behaviour on the
193 # server.
194 methods_without_body = (
195 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
196 )
197 for method in methods_without_body:
198 conn = client.HTTPConnection('example.com')
199 conn.sock = FakeSocket(None)
200 conn._buffer = ContentLengthChecker()
201 conn.request(method, '/', None)
202 self.assertEqual(
203 conn._buffer.content_length, None,
204 'Header Content-Length set for empty body on {}'.format(method)
205 )
206
207 # If the body is set to '', that's considered to be "present but
208 # empty" rather than "missing", so content length would be set, even
209 # for methods that don't expect a body.
210 for method in methods_without_body:
211 conn = client.HTTPConnection('example.com')
212 conn.sock = FakeSocket(None)
213 conn._buffer = ContentLengthChecker()
214 conn.request(method, '/', '')
215 self.assertEqual(
216 conn._buffer.content_length, b'0',
217 'Header Content-Length incorrect on {}'.format(method)
218 )
219
220 # If the body is set, make sure Content-Length is set.
221 for method in itertools.chain(methods_without_body, methods_with_body):
222 conn = client.HTTPConnection('example.com')
223 conn.sock = FakeSocket(None)
224 conn._buffer = ContentLengthChecker()
225 conn.request(method, '/', ' ')
226 self.assertEqual(
227 conn._buffer.content_length, b'1',
228 'Header Content-Length incorrect on {}'.format(method)
229 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800230
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000231 def test_putheader(self):
232 conn = client.HTTPConnection('example.com')
233 conn.sock = FakeSocket(None)
234 conn.putrequest('GET','/')
235 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200236 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000237
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200238 conn.putheader('Foo', ' bar ')
239 self.assertIn(b'Foo: bar ', conn._buffer)
240 conn.putheader('Bar', '\tbaz\t')
241 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
242 conn.putheader('Authorization', 'Bearer mytoken')
243 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
244 conn.putheader('IterHeader', 'IterA', 'IterB')
245 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
246 conn.putheader('LatinHeader', b'\xFF')
247 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
248 conn.putheader('Utf8Header', b'\xc3\x80')
249 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
250 conn.putheader('C1-Control', b'next\x85line')
251 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
252 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
253 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
254 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
255 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
256 conn.putheader('Key Space', 'value')
257 self.assertIn(b'Key Space: value', conn._buffer)
258 conn.putheader('KeySpace ', 'value')
259 self.assertIn(b'KeySpace : value', conn._buffer)
260 conn.putheader(b'Nonbreak\xa0Space', 'value')
261 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
262 conn.putheader(b'\xa0NonbreakSpace', 'value')
263 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
264
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000265 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000266 # Default host header on IPv6 transaction should be wrapped by [] if
267 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000268 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
269 b'Accept-Encoding: identity\r\n\r\n'
270 conn = client.HTTPConnection('[2001::]:81')
271 sock = FakeSocket('')
272 conn.sock = sock
273 conn.request('GET', '/foo')
274 self.assertTrue(sock.data.startswith(expected))
275
276 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
277 b'Accept-Encoding: identity\r\n\r\n'
278 conn = client.HTTPConnection('[2001:102A::]')
279 sock = FakeSocket('')
280 conn.sock = sock
281 conn.request('GET', '/foo')
282 self.assertTrue(sock.data.startswith(expected))
283
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500284 def test_malformed_headers_coped_with(self):
285 # Issue 19996
286 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
287 sock = FakeSocket(body)
288 resp = client.HTTPResponse(sock)
289 resp.begin()
290
291 self.assertEqual(resp.getheader('First'), 'val')
292 self.assertEqual(resp.getheader('Second'), 'val')
293
R David Murraydc1650c2016-09-07 17:44:34 -0400294 def test_parse_all_octets(self):
295 # Ensure no valid header field octet breaks the parser
296 body = (
297 b'HTTP/1.1 200 OK\r\n'
298 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
299 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
300 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
301 b'obs-fold: text\r\n'
302 b' folded with space\r\n'
303 b'\tfolded with tab\r\n'
304 b'Content-Length: 0\r\n'
305 b'\r\n'
306 )
307 sock = FakeSocket(body)
308 resp = client.HTTPResponse(sock)
309 resp.begin()
310 self.assertEqual(resp.getheader('Content-Length'), '0')
311 self.assertEqual(resp.msg['Content-Length'], '0')
312 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
313 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
314 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
315 self.assertEqual(resp.getheader('VCHAR'), vchar)
316 self.assertEqual(resp.msg['VCHAR'], vchar)
317 self.assertIsNotNone(resp.getheader('obs-text'))
318 self.assertIn('obs-text', resp.msg)
319 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
320 self.assertTrue(folded.startswith('text'))
321 self.assertIn(' folded with space', folded)
322 self.assertTrue(folded.endswith('folded with tab'))
323
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200324 def test_invalid_headers(self):
325 conn = client.HTTPConnection('example.com')
326 conn.sock = FakeSocket('')
327 conn.putrequest('GET', '/')
328
329 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
330 # longer allowed in header names
331 cases = (
332 (b'Invalid\r\nName', b'ValidValue'),
333 (b'Invalid\rName', b'ValidValue'),
334 (b'Invalid\nName', b'ValidValue'),
335 (b'\r\nInvalidName', b'ValidValue'),
336 (b'\rInvalidName', b'ValidValue'),
337 (b'\nInvalidName', b'ValidValue'),
338 (b' InvalidName', b'ValidValue'),
339 (b'\tInvalidName', b'ValidValue'),
340 (b'Invalid:Name', b'ValidValue'),
341 (b':InvalidName', b'ValidValue'),
342 (b'ValidName', b'Invalid\r\nValue'),
343 (b'ValidName', b'Invalid\rValue'),
344 (b'ValidName', b'Invalid\nValue'),
345 (b'ValidName', b'InvalidValue\r\n'),
346 (b'ValidName', b'InvalidValue\r'),
347 (b'ValidName', b'InvalidValue\n'),
348 )
349 for name, value in cases:
350 with self.subTest((name, value)):
351 with self.assertRaisesRegex(ValueError, 'Invalid header'):
352 conn.putheader(name, value)
353
Marco Strigl936f03e2018-06-19 15:20:58 +0200354 def test_headers_debuglevel(self):
355 body = (
356 b'HTTP/1.1 200 OK\r\n'
357 b'First: val\r\n'
Matt Houglum461c4162019-04-03 21:36:47 -0700358 b'Second: val1\r\n'
359 b'Second: val2\r\n'
Marco Strigl936f03e2018-06-19 15:20:58 +0200360 )
361 sock = FakeSocket(body)
362 resp = client.HTTPResponse(sock, debuglevel=1)
363 with support.captured_stdout() as output:
364 resp.begin()
365 lines = output.getvalue().splitlines()
366 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
367 self.assertEqual(lines[1], "header: First: val")
Matt Houglum461c4162019-04-03 21:36:47 -0700368 self.assertEqual(lines[2], "header: Second: val1")
369 self.assertEqual(lines[3], "header: Second: val2")
Marco Strigl936f03e2018-06-19 15:20:58 +0200370
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000371
AMIR8ca8a2e2020-07-19 00:46:10 +0430372class HttpMethodTests(TestCase):
373 def test_invalid_method_names(self):
374 methods = (
375 'GET\r',
376 'POST\n',
377 'PUT\n\r',
378 'POST\nValue',
379 'POST\nHOST:abc',
380 'GET\nrHost:abc\n',
381 'POST\rRemainder:\r',
382 'GET\rHOST:\n',
383 '\nPUT'
384 )
385
386 for method in methods:
387 with self.assertRaisesRegex(
388 ValueError, "method can't contain control characters"):
389 conn = client.HTTPConnection('example.com')
390 conn.sock = FakeSocket(None)
391 conn.request(method=method, url="/")
392
393
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000394class TransferEncodingTest(TestCase):
395 expected_body = b"It's just a flesh wound"
396
397 def test_endheaders_chunked(self):
398 conn = client.HTTPConnection('example.com')
399 conn.sock = FakeSocket(b'')
400 conn.putrequest('POST', '/')
401 conn.endheaders(self._make_body(), encode_chunked=True)
402
403 _, _, body = self._parse_request(conn.sock.data)
404 body = self._parse_chunked(body)
405 self.assertEqual(body, self.expected_body)
406
407 def test_explicit_headers(self):
408 # explicit chunked
409 conn = client.HTTPConnection('example.com')
410 conn.sock = FakeSocket(b'')
411 # this shouldn't actually be automatically chunk-encoded because the
412 # calling code has explicitly stated that it's taking care of it
413 conn.request(
414 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
415
416 _, headers, body = self._parse_request(conn.sock.data)
417 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
418 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
419 self.assertEqual(body, self.expected_body)
420
421 # explicit chunked, string body
422 conn = client.HTTPConnection('example.com')
423 conn.sock = FakeSocket(b'')
424 conn.request(
425 'POST', '/', self.expected_body.decode('latin-1'),
426 {'Transfer-Encoding': 'chunked'})
427
428 _, headers, body = self._parse_request(conn.sock.data)
429 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
430 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
431 self.assertEqual(body, self.expected_body)
432
433 # User-specified TE, but request() does the chunk encoding
434 conn = client.HTTPConnection('example.com')
435 conn.sock = FakeSocket(b'')
436 conn.request('POST', '/',
437 headers={'Transfer-Encoding': 'gzip, chunked'},
438 encode_chunked=True,
439 body=self._make_body())
440 _, headers, body = self._parse_request(conn.sock.data)
441 self.assertNotIn('content-length', [k.lower() for k in headers])
442 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
443 self.assertEqual(self._parse_chunked(body), self.expected_body)
444
445 def test_request(self):
446 for empty_lines in (False, True,):
447 conn = client.HTTPConnection('example.com')
448 conn.sock = FakeSocket(b'')
449 conn.request(
450 'POST', '/', self._make_body(empty_lines=empty_lines))
451
452 _, headers, body = self._parse_request(conn.sock.data)
453 body = self._parse_chunked(body)
454 self.assertEqual(body, self.expected_body)
455 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
456
457 # Content-Length and Transfer-Encoding SHOULD not be sent in the
458 # same request
459 self.assertNotIn('content-length', [k.lower() for k in headers])
460
Martin Panteref91bb22016-08-27 01:39:26 +0000461 def test_empty_body(self):
462 # Zero-length iterable should be treated like any other iterable
463 conn = client.HTTPConnection('example.com')
464 conn.sock = FakeSocket(b'')
465 conn.request('POST', '/', ())
466 _, headers, body = self._parse_request(conn.sock.data)
467 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
468 self.assertNotIn('content-length', [k.lower() for k in headers])
469 self.assertEqual(body, b"0\r\n\r\n")
470
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000471 def _make_body(self, empty_lines=False):
472 lines = self.expected_body.split(b' ')
473 for idx, line in enumerate(lines):
474 # for testing handling empty lines
475 if empty_lines and idx % 2:
476 yield b''
477 if idx < len(lines) - 1:
478 yield line + b' '
479 else:
480 yield line
481
482 def _parse_request(self, data):
483 lines = data.split(b'\r\n')
484 request = lines[0]
485 headers = {}
486 n = 1
487 while n < len(lines) and len(lines[n]) > 0:
488 key, val = lines[n].split(b':')
489 key = key.decode('latin-1').strip()
490 headers[key] = val.decode('latin-1').strip()
491 n += 1
492
493 return request, headers, b'\r\n'.join(lines[n + 1:])
494
495 def _parse_chunked(self, data):
496 body = []
497 trailers = {}
498 n = 0
499 lines = data.split(b'\r\n')
500 # parse body
501 while True:
502 size, chunk = lines[n:n+2]
503 size = int(size, 16)
504
505 if size == 0:
506 n += 1
507 break
508
509 self.assertEqual(size, len(chunk))
510 body.append(chunk)
511
512 n += 2
513 # we /should/ hit the end chunk, but check against the size of
514 # lines so we're not stuck in an infinite loop should we get
515 # malformed data
516 if n > len(lines):
517 break
518
519 return b''.join(body)
520
521
Thomas Wouters89f507f2006-12-13 04:49:30 +0000522class BasicTest(TestCase):
Angelin BOOZ68526fe2020-09-21 15:11:06 +0200523 def test_dir_with_added_behavior_on_status(self):
524 # see issue40084
525 self.assertTrue({'description', 'name', 'phrase', 'value'} <= set(dir(HTTPStatus(404))))
526
Thomas Wouters89f507f2006-12-13 04:49:30 +0000527 def test_status_lines(self):
528 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000529
Thomas Wouters89f507f2006-12-13 04:49:30 +0000530 body = "HTTP/1.1 200 Ok\r\n\r\nText"
531 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000532 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000533 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200534 self.assertEqual(resp.read(0), b'') # Issue #20007
535 self.assertFalse(resp.isclosed())
536 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000537 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000538 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200539 self.assertFalse(resp.closed)
540 resp.close()
541 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000542
Thomas Wouters89f507f2006-12-13 04:49:30 +0000543 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
544 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000545 resp = client.HTTPResponse(sock)
546 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000547
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000548 def test_bad_status_repr(self):
549 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200550 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000551
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000552 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000553 # if we have Content-Length, HTTPResponse knows when to close itself,
554 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000555 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
556 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000557 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000558 resp.begin()
559 self.assertEqual(resp.read(2), b'Te')
560 self.assertFalse(resp.isclosed())
561 self.assertEqual(resp.read(2), b'xt')
562 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200563 self.assertFalse(resp.closed)
564 resp.close()
565 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000566
Martin Panterce911c32016-03-17 06:42:48 +0000567 def test_mixed_reads(self):
568 # readline() should update the remaining length, so that read() knows
569 # how much data is left and does not raise IncompleteRead
570 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
571 sock = FakeSocket(body)
572 resp = client.HTTPResponse(sock)
573 resp.begin()
574 self.assertEqual(resp.readline(), b'Text\r\n')
575 self.assertFalse(resp.isclosed())
576 self.assertEqual(resp.read(), b'Another')
577 self.assertTrue(resp.isclosed())
578 self.assertFalse(resp.closed)
579 resp.close()
580 self.assertTrue(resp.closed)
581
Antoine Pitrou38d96432011-12-06 22:33:57 +0100582 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000583 # if we have Content-Length, HTTPResponse knows when to close itself,
584 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100585 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
586 sock = FakeSocket(body)
587 resp = client.HTTPResponse(sock)
588 resp.begin()
589 b = bytearray(2)
590 n = resp.readinto(b)
591 self.assertEqual(n, 2)
592 self.assertEqual(bytes(b), b'Te')
593 self.assertFalse(resp.isclosed())
594 n = resp.readinto(b)
595 self.assertEqual(n, 2)
596 self.assertEqual(bytes(b), b'xt')
597 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200598 self.assertFalse(resp.closed)
599 resp.close()
600 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100601
Bruce Merry152f0b82020-06-25 08:30:21 +0200602 def test_partial_reads_past_end(self):
603 # if we have Content-Length, clip reads to the end
604 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
605 sock = FakeSocket(body)
606 resp = client.HTTPResponse(sock)
607 resp.begin()
608 self.assertEqual(resp.read(10), b'Text')
609 self.assertTrue(resp.isclosed())
610 self.assertFalse(resp.closed)
611 resp.close()
612 self.assertTrue(resp.closed)
613
614 def test_partial_readintos_past_end(self):
615 # if we have Content-Length, clip readintos to the end
616 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
617 sock = FakeSocket(body)
618 resp = client.HTTPResponse(sock)
619 resp.begin()
620 b = bytearray(10)
621 n = resp.readinto(b)
622 self.assertEqual(n, 4)
623 self.assertEqual(bytes(b)[:4], b'Text')
624 self.assertTrue(resp.isclosed())
625 self.assertFalse(resp.closed)
626 resp.close()
627 self.assertTrue(resp.closed)
628
Antoine Pitrou084daa22012-12-15 19:11:54 +0100629 def test_partial_reads_no_content_length(self):
630 # when no length is present, the socket should be gracefully closed when
631 # all data was read
632 body = "HTTP/1.1 200 Ok\r\n\r\nText"
633 sock = FakeSocket(body)
634 resp = client.HTTPResponse(sock)
635 resp.begin()
636 self.assertEqual(resp.read(2), b'Te')
637 self.assertFalse(resp.isclosed())
638 self.assertEqual(resp.read(2), b'xt')
639 self.assertEqual(resp.read(1), b'')
640 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200641 self.assertFalse(resp.closed)
642 resp.close()
643 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100644
Antoine Pitroud20e7742012-12-15 19:22:30 +0100645 def test_partial_readintos_no_content_length(self):
646 # when no length is present, the socket should be gracefully closed when
647 # all data was read
648 body = "HTTP/1.1 200 Ok\r\n\r\nText"
649 sock = FakeSocket(body)
650 resp = client.HTTPResponse(sock)
651 resp.begin()
652 b = bytearray(2)
653 n = resp.readinto(b)
654 self.assertEqual(n, 2)
655 self.assertEqual(bytes(b), b'Te')
656 self.assertFalse(resp.isclosed())
657 n = resp.readinto(b)
658 self.assertEqual(n, 2)
659 self.assertEqual(bytes(b), b'xt')
660 n = resp.readinto(b)
661 self.assertEqual(n, 0)
662 self.assertTrue(resp.isclosed())
663
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100664 def test_partial_reads_incomplete_body(self):
665 # if the server shuts down the connection before the whole
666 # content-length is delivered, the socket is gracefully closed
667 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
668 sock = FakeSocket(body)
669 resp = client.HTTPResponse(sock)
670 resp.begin()
671 self.assertEqual(resp.read(2), b'Te')
672 self.assertFalse(resp.isclosed())
673 self.assertEqual(resp.read(2), b'xt')
674 self.assertEqual(resp.read(1), b'')
675 self.assertTrue(resp.isclosed())
676
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100677 def test_partial_readintos_incomplete_body(self):
678 # if the server shuts down the connection before the whole
679 # content-length is delivered, the socket is gracefully closed
680 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
681 sock = FakeSocket(body)
682 resp = client.HTTPResponse(sock)
683 resp.begin()
684 b = bytearray(2)
685 n = resp.readinto(b)
686 self.assertEqual(n, 2)
687 self.assertEqual(bytes(b), b'Te')
688 self.assertFalse(resp.isclosed())
689 n = resp.readinto(b)
690 self.assertEqual(n, 2)
691 self.assertEqual(bytes(b), b'xt')
692 n = resp.readinto(b)
693 self.assertEqual(n, 0)
694 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200695 self.assertFalse(resp.closed)
696 resp.close()
697 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100698
Thomas Wouters89f507f2006-12-13 04:49:30 +0000699 def test_host_port(self):
700 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000701
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200702 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000703 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000704
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000705 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
706 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200708 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200710 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
711 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000712 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000713 self.assertEqual(h, c.host)
714 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000715
Thomas Wouters89f507f2006-12-13 04:49:30 +0000716 def test_response_headers(self):
717 # test response with multiple message headers with the same field name.
718 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000719 'Set-Cookie: Customer="WILE_E_COYOTE"; '
720 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000721 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
722 ' Path="/acme"\r\n'
723 '\r\n'
724 'No body\r\n')
725 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
726 ', '
727 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
728 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000729 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000730 r.begin()
731 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000732 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000733
Thomas Wouters89f507f2006-12-13 04:49:30 +0000734 def test_read_head(self):
735 # Test that the library doesn't attempt to read any data
736 # from a HEAD request. (Tickles SF bug #622042.)
737 sock = FakeSocket(
738 'HTTP/1.1 200 OK\r\n'
739 'Content-Length: 14432\r\n'
740 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300741 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000742 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000743 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000744 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000745 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000746
Antoine Pitrou38d96432011-12-06 22:33:57 +0100747 def test_readinto_head(self):
748 # Test that the library doesn't attempt to read any data
749 # from a HEAD request. (Tickles SF bug #622042.)
750 sock = FakeSocket(
751 'HTTP/1.1 200 OK\r\n'
752 'Content-Length: 14432\r\n'
753 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300754 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100755 resp = client.HTTPResponse(sock, method="HEAD")
756 resp.begin()
757 b = bytearray(5)
758 if resp.readinto(b) != 0:
759 self.fail("Did not expect response from HEAD request")
760 self.assertEqual(bytes(b), b'\x00'*5)
761
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100762 def test_too_many_headers(self):
763 headers = '\r\n'.join('Header%d: foo' % i
764 for i in range(client._MAXHEADERS + 1)) + '\r\n'
765 text = ('HTTP/1.1 200 OK\r\n' + headers)
766 s = FakeSocket(text)
767 r = client.HTTPResponse(s)
768 self.assertRaisesRegex(client.HTTPException,
769 r"got more than \d+ headers", r.begin)
770
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000772 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000773 b'Accept-Encoding: identity\r\n'
774 b'Transfer-Encoding: chunked\r\n'
775 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000776
Brett Cannon77b7de62010-10-29 23:31:11 +0000777 with open(__file__, 'rb') as body:
778 conn = client.HTTPConnection('example.com')
779 sock = FakeSocket(body)
780 conn.sock = sock
781 conn.request('GET', '/foo', body)
782 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
783 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000784
Antoine Pitrouead1d622009-09-29 18:44:53 +0000785 def test_send(self):
786 expected = b'this is a test this is only a test'
787 conn = client.HTTPConnection('example.com')
788 sock = FakeSocket(None)
789 conn.sock = sock
790 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000791 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000792 sock.data = b''
793 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000794 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000795 sock.data = b''
796 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000797 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000798
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300799 def test_send_updating_file(self):
800 def data():
801 yield 'data'
802 yield None
803 yield 'data_two'
804
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000805 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300806 mode = 'r'
807 d = data()
808 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000809 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300810
811 expected = b'data'
812
813 conn = client.HTTPConnection('example.com')
814 sock = FakeSocket("")
815 conn.sock = sock
816 conn.send(UpdatingFile())
817 self.assertEqual(sock.data, expected)
818
819
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000820 def test_send_iter(self):
821 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
822 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
823 b'\r\nonetwothree'
824
825 def body():
826 yield b"one"
827 yield b"two"
828 yield b"three"
829
830 conn = client.HTTPConnection('example.com')
831 sock = FakeSocket("")
832 conn.sock = sock
833 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000834 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000835
Nir Sofferad455cd2017-11-06 23:16:37 +0200836 def test_blocksize_request(self):
837 """Check that request() respects the configured block size."""
838 blocksize = 8 # For easy debugging.
839 conn = client.HTTPConnection('example.com', blocksize=blocksize)
840 sock = FakeSocket(None)
841 conn.sock = sock
842 expected = b"a" * blocksize + b"b"
843 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
844 self.assertEqual(sock.sendall_calls, 3)
845 body = sock.data.split(b"\r\n\r\n", 1)[1]
846 self.assertEqual(body, expected)
847
848 def test_blocksize_send(self):
849 """Check that send() respects the configured block size."""
850 blocksize = 8 # For easy debugging.
851 conn = client.HTTPConnection('example.com', blocksize=blocksize)
852 sock = FakeSocket(None)
853 conn.sock = sock
854 expected = b"a" * blocksize + b"b"
855 conn.send(io.BytesIO(expected))
856 self.assertEqual(sock.sendall_calls, 2)
857 self.assertEqual(sock.data, expected)
858
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800859 def test_send_type_error(self):
860 # See: Issue #12676
861 conn = client.HTTPConnection('example.com')
862 conn.sock = FakeSocket('')
863 with self.assertRaises(TypeError):
864 conn.request('POST', 'test', conn)
865
Christian Heimesa612dc02008-02-24 13:08:18 +0000866 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000867 expected = chunked_expected
868 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000869 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000870 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100871 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000872 resp.close()
873
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100874 # Various read sizes
875 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000876 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100877 resp = client.HTTPResponse(sock, method="GET")
878 resp.begin()
879 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
880 resp.close()
881
Christian Heimesa612dc02008-02-24 13:08:18 +0000882 for x in ('', 'foo\r\n'):
883 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000884 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000885 resp.begin()
886 try:
887 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000888 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100889 self.assertEqual(i.partial, expected)
890 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
891 self.assertEqual(repr(i), expected_message)
892 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000893 else:
894 self.fail('IncompleteRead expected')
895 finally:
896 resp.close()
897
Antoine Pitrou38d96432011-12-06 22:33:57 +0100898 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000899
900 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100901 nexpected = len(expected)
902 b = bytearray(128)
903
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000904 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100905 resp = client.HTTPResponse(sock, method="GET")
906 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100907 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100908 self.assertEqual(b[:nexpected], expected)
909 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100910 resp.close()
911
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100912 # Various read sizes
913 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000914 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100915 resp = client.HTTPResponse(sock, method="GET")
916 resp.begin()
917 m = memoryview(b)
918 i = resp.readinto(m[0:n])
919 i += resp.readinto(m[i:n + i])
920 i += resp.readinto(m[i:])
921 self.assertEqual(b[:nexpected], expected)
922 self.assertEqual(i, nexpected)
923 resp.close()
924
Antoine Pitrou38d96432011-12-06 22:33:57 +0100925 for x in ('', 'foo\r\n'):
926 sock = FakeSocket(chunked_start + x)
927 resp = client.HTTPResponse(sock, method="GET")
928 resp.begin()
929 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100930 n = resp.readinto(b)
931 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100932 self.assertEqual(i.partial, expected)
933 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
934 self.assertEqual(repr(i), expected_message)
935 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100936 else:
937 self.fail('IncompleteRead expected')
938 finally:
939 resp.close()
940
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000941 def test_chunked_head(self):
942 chunked_start = (
943 'HTTP/1.1 200 OK\r\n'
944 'Transfer-Encoding: chunked\r\n\r\n'
945 'a\r\n'
946 'hello world\r\n'
947 '1\r\n'
948 'd\r\n'
949 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000950 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000951 resp = client.HTTPResponse(sock, method="HEAD")
952 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000953 self.assertEqual(resp.read(), b'')
954 self.assertEqual(resp.status, 200)
955 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000956 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200957 self.assertFalse(resp.closed)
958 resp.close()
959 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000960
Antoine Pitrou38d96432011-12-06 22:33:57 +0100961 def test_readinto_chunked_head(self):
962 chunked_start = (
963 'HTTP/1.1 200 OK\r\n'
964 'Transfer-Encoding: chunked\r\n\r\n'
965 'a\r\n'
966 'hello world\r\n'
967 '1\r\n'
968 'd\r\n'
969 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000970 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100971 resp = client.HTTPResponse(sock, method="HEAD")
972 resp.begin()
973 b = bytearray(5)
974 n = resp.readinto(b)
975 self.assertEqual(n, 0)
976 self.assertEqual(bytes(b), b'\x00'*5)
977 self.assertEqual(resp.status, 200)
978 self.assertEqual(resp.reason, 'OK')
979 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200980 self.assertFalse(resp.closed)
981 resp.close()
982 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100983
Christian Heimesa612dc02008-02-24 13:08:18 +0000984 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000985 sock = FakeSocket(
986 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000987 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000988 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000989 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100990 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000991
Benjamin Peterson6accb982009-03-02 22:50:25 +0000992 def test_incomplete_read(self):
993 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000994 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000995 resp.begin()
996 try:
997 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000998 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000999 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +00001000 self.assertEqual(repr(i),
1001 "IncompleteRead(7 bytes read, 3 more expected)")
1002 self.assertEqual(str(i),
1003 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +01001004 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +00001005 else:
1006 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +00001007
Jeremy Hylton636950f2009-03-28 04:34:21 +00001008 def test_epipe(self):
1009 sock = EPipeSocket(
1010 "HTTP/1.0 401 Authorization Required\r\n"
1011 "Content-type: text/html\r\n"
1012 "WWW-Authenticate: Basic realm=\"example\"\r\n",
1013 b"Content-Length")
1014 conn = client.HTTPConnection("example.com")
1015 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +02001016 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +00001017 lambda: conn.request("PUT", "/url", "body"))
1018 resp = conn.getresponse()
1019 self.assertEqual(401, resp.status)
1020 self.assertEqual("Basic realm=\"example\"",
1021 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +00001022
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001023 # Test lines overflowing the max line size (_MAXLINE in http.client)
1024
1025 def test_overflowing_status_line(self):
1026 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
1027 resp = client.HTTPResponse(FakeSocket(body))
1028 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
1029
1030 def test_overflowing_header_line(self):
1031 body = (
1032 'HTTP/1.1 200 OK\r\n'
1033 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1034 )
1035 resp = client.HTTPResponse(FakeSocket(body))
1036 self.assertRaises(client.LineTooLong, resp.begin)
1037
1038 def test_overflowing_chunked_line(self):
1039 body = (
1040 'HTTP/1.1 200 OK\r\n'
1041 'Transfer-Encoding: chunked\r\n\r\n'
1042 + '0' * 65536 + 'a\r\n'
1043 'hello world\r\n'
1044 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001045 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001046 )
1047 resp = client.HTTPResponse(FakeSocket(body))
1048 resp.begin()
1049 self.assertRaises(client.LineTooLong, resp.read)
1050
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001051 def test_early_eof(self):
1052 # Test httpresponse with no \r\n termination,
1053 body = "HTTP/1.1 200 Ok"
1054 sock = FakeSocket(body)
1055 resp = client.HTTPResponse(sock)
1056 resp.begin()
1057 self.assertEqual(resp.read(), b'')
1058 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001059 self.assertFalse(resp.closed)
1060 resp.close()
1061 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001062
Serhiy Storchakab491e052014-12-01 13:07:45 +02001063 def test_error_leak(self):
1064 # Test that the socket is not leaked if getresponse() fails
1065 conn = client.HTTPConnection('example.com')
1066 response = None
1067 class Response(client.HTTPResponse):
1068 def __init__(self, *pos, **kw):
1069 nonlocal response
1070 response = self # Avoid garbage collector closing the socket
1071 client.HTTPResponse.__init__(self, *pos, **kw)
1072 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001073 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001074 conn.request('GET', '/')
1075 self.assertRaises(client.BadStatusLine, conn.getresponse)
1076 self.assertTrue(response.closed)
1077 self.assertTrue(conn.sock.file_closed)
1078
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001079 def test_chunked_extension(self):
1080 extra = '3;foo=bar\r\n' + 'abc\r\n'
1081 expected = chunked_expected + b'abc'
1082
1083 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1084 resp = client.HTTPResponse(sock, method="GET")
1085 resp.begin()
1086 self.assertEqual(resp.read(), expected)
1087 resp.close()
1088
1089 def test_chunked_missing_end(self):
1090 """some servers may serve up a short chunked encoding stream"""
1091 expected = chunked_expected
1092 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1093 resp = client.HTTPResponse(sock, method="GET")
1094 resp.begin()
1095 self.assertEqual(resp.read(), expected)
1096 resp.close()
1097
1098 def test_chunked_trailers(self):
1099 """See that trailers are read and ignored"""
1100 expected = chunked_expected
1101 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1102 resp = client.HTTPResponse(sock, method="GET")
1103 resp.begin()
1104 self.assertEqual(resp.read(), expected)
1105 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001106 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001107 resp.close()
1108
1109 def test_chunked_sync(self):
1110 """Check that we don't read past the end of the chunked-encoding stream"""
1111 expected = chunked_expected
1112 extradata = "extradata"
1113 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1114 resp = client.HTTPResponse(sock, method="GET")
1115 resp.begin()
1116 self.assertEqual(resp.read(), expected)
1117 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001118 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001119 resp.close()
1120
1121 def test_content_length_sync(self):
1122 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001123 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001124 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001125 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001126 resp = client.HTTPResponse(sock, method="GET")
1127 resp.begin()
1128 self.assertEqual(resp.read(), expected)
1129 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001130 self.assertEqual(sock.file.read(), extradata) #we read to the end
1131 resp.close()
1132
1133 def test_readlines_content_length(self):
1134 extradata = b"extradata"
1135 expected = b"Hello123\r\n"
1136 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1137 resp = client.HTTPResponse(sock, method="GET")
1138 resp.begin()
1139 self.assertEqual(resp.readlines(2000), [expected])
1140 # the file should now have our extradata ready to be read
1141 self.assertEqual(sock.file.read(), extradata) #we read to the end
1142 resp.close()
1143
1144 def test_read1_content_length(self):
1145 extradata = b"extradata"
1146 expected = b"Hello123\r\n"
1147 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1148 resp = client.HTTPResponse(sock, method="GET")
1149 resp.begin()
1150 self.assertEqual(resp.read1(2000), expected)
1151 # the file should now have our extradata ready to be read
1152 self.assertEqual(sock.file.read(), extradata) #we read to the end
1153 resp.close()
1154
1155 def test_readline_bound_content_length(self):
1156 extradata = b"extradata"
1157 expected = b"Hello123\r\n"
1158 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1159 resp = client.HTTPResponse(sock, method="GET")
1160 resp.begin()
1161 self.assertEqual(resp.readline(10), expected)
1162 self.assertEqual(resp.readline(10), b"")
1163 # the file should now have our extradata ready to be read
1164 self.assertEqual(sock.file.read(), extradata) #we read to the end
1165 resp.close()
1166
1167 def test_read1_bound_content_length(self):
1168 extradata = b"extradata"
1169 expected = b"Hello123\r\n"
1170 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1171 resp = client.HTTPResponse(sock, method="GET")
1172 resp.begin()
1173 self.assertEqual(resp.read1(20), expected*2)
1174 self.assertEqual(resp.read(), expected)
1175 # the file should now have our extradata ready to be read
1176 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001177 resp.close()
1178
Martin Panterd979b2c2016-04-09 14:03:17 +00001179 def test_response_fileno(self):
1180 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001181 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001182 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001183
1184 result = None
1185 def run_server():
1186 [conn, address] = serv.accept()
1187 with conn, conn.makefile("rb") as reader:
1188 # Read the request header until a blank line
1189 while True:
1190 line = reader.readline()
1191 if not line.rstrip(b"\r\n"):
1192 break
1193 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1194 nonlocal result
1195 result = reader.read()
1196
1197 thread = threading.Thread(target=run_server)
1198 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001199 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001200 conn = client.HTTPConnection(*serv.getsockname())
1201 conn.request("CONNECT", "dummy:1234")
1202 response = conn.getresponse()
1203 try:
1204 self.assertEqual(response.status, client.OK)
1205 s = socket.socket(fileno=response.fileno())
1206 try:
1207 s.sendall(b"proxied data\n")
1208 finally:
1209 s.detach()
1210 finally:
1211 response.close()
1212 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001213 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001214 self.assertEqual(result, b"proxied data\n")
1215
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001216 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001217 """
1218 It should be possible to override the default validation
1219 behavior in putrequest (bpo-38216).
1220 """
1221 class UnsafeHTTPConnection(client.HTTPConnection):
1222 def _validate_path(self, url):
1223 pass
1224
1225 conn = UnsafeHTTPConnection('example.com')
1226 conn.sock = FakeSocket('')
1227 conn.putrequest('GET', '/\x00')
1228
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001229 def test_putrequest_override_host_validation(self):
1230 class UnsafeHTTPConnection(client.HTTPConnection):
1231 def _validate_host(self, url):
1232 pass
1233
1234 conn = UnsafeHTTPConnection('example.com\r\n')
1235 conn.sock = FakeSocket('')
1236 # set skip_host so a ValueError is not raised upon adding the
1237 # invalid URL as the value of the "Host:" header
1238 conn.putrequest('GET', '/', skip_host=1)
1239
Jason R. Coombs7774d782019-09-28 08:32:01 -04001240 def test_putrequest_override_encoding(self):
1241 """
1242 It should be possible to override the default encoding
1243 to transmit bytes in another encoding even if invalid
1244 (bpo-36274).
1245 """
1246 class UnsafeHTTPConnection(client.HTTPConnection):
1247 def _encode_request(self, str_url):
1248 return str_url.encode('utf-8')
1249
1250 conn = UnsafeHTTPConnection('example.com')
1251 conn.sock = FakeSocket('')
1252 conn.putrequest('GET', '/☃')
1253
1254
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001255class ExtendedReadTest(TestCase):
1256 """
1257 Test peek(), read1(), readline()
1258 """
1259 lines = (
1260 'HTTP/1.1 200 OK\r\n'
1261 '\r\n'
1262 'hello world!\n'
1263 'and now \n'
1264 'for something completely different\n'
1265 'foo'
1266 )
1267 lines_expected = lines[lines.find('hello'):].encode("ascii")
1268 lines_chunked = (
1269 'HTTP/1.1 200 OK\r\n'
1270 'Transfer-Encoding: chunked\r\n\r\n'
1271 'a\r\n'
1272 'hello worl\r\n'
1273 '3\r\n'
1274 'd!\n\r\n'
1275 '9\r\n'
1276 'and now \n\r\n'
1277 '23\r\n'
1278 'for something completely different\n\r\n'
1279 '3\r\n'
1280 'foo\r\n'
1281 '0\r\n' # terminating chunk
1282 '\r\n' # end of trailers
1283 )
1284
1285 def setUp(self):
1286 sock = FakeSocket(self.lines)
1287 resp = client.HTTPResponse(sock, method="GET")
1288 resp.begin()
1289 resp.fp = io.BufferedReader(resp.fp)
1290 self.resp = resp
1291
1292
1293
1294 def test_peek(self):
1295 resp = self.resp
1296 # patch up the buffered peek so that it returns not too much stuff
1297 oldpeek = resp.fp.peek
1298 def mypeek(n=-1):
1299 p = oldpeek(n)
1300 if n >= 0:
1301 return p[:n]
1302 return p[:10]
1303 resp.fp.peek = mypeek
1304
1305 all = []
1306 while True:
1307 # try a short peek
1308 p = resp.peek(3)
1309 if p:
1310 self.assertGreater(len(p), 0)
1311 # then unbounded peek
1312 p2 = resp.peek()
1313 self.assertGreaterEqual(len(p2), len(p))
1314 self.assertTrue(p2.startswith(p))
1315 next = resp.read(len(p2))
1316 self.assertEqual(next, p2)
1317 else:
1318 next = resp.read()
1319 self.assertFalse(next)
1320 all.append(next)
1321 if not next:
1322 break
1323 self.assertEqual(b"".join(all), self.lines_expected)
1324
1325 def test_readline(self):
1326 resp = self.resp
1327 self._verify_readline(self.resp.readline, self.lines_expected)
1328
1329 def _verify_readline(self, readline, expected):
1330 all = []
1331 while True:
1332 # short readlines
1333 line = readline(5)
1334 if line and line != b"foo":
1335 if len(line) < 5:
1336 self.assertTrue(line.endswith(b"\n"))
1337 all.append(line)
1338 if not line:
1339 break
1340 self.assertEqual(b"".join(all), expected)
1341
1342 def test_read1(self):
1343 resp = self.resp
1344 def r():
1345 res = resp.read1(4)
1346 self.assertLessEqual(len(res), 4)
1347 return res
1348 readliner = Readliner(r)
1349 self._verify_readline(readliner.readline, self.lines_expected)
1350
1351 def test_read1_unbounded(self):
1352 resp = self.resp
1353 all = []
1354 while True:
1355 data = resp.read1()
1356 if not data:
1357 break
1358 all.append(data)
1359 self.assertEqual(b"".join(all), self.lines_expected)
1360
1361 def test_read1_bounded(self):
1362 resp = self.resp
1363 all = []
1364 while True:
1365 data = resp.read1(10)
1366 if not data:
1367 break
1368 self.assertLessEqual(len(data), 10)
1369 all.append(data)
1370 self.assertEqual(b"".join(all), self.lines_expected)
1371
1372 def test_read1_0(self):
1373 self.assertEqual(self.resp.read1(0), b"")
1374
1375 def test_peek_0(self):
1376 p = self.resp.peek(0)
1377 self.assertLessEqual(0, len(p))
1378
Jason R. Coombs7774d782019-09-28 08:32:01 -04001379
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001380class ExtendedReadTestChunked(ExtendedReadTest):
1381 """
1382 Test peek(), read1(), readline() in chunked mode
1383 """
1384 lines = (
1385 'HTTP/1.1 200 OK\r\n'
1386 'Transfer-Encoding: chunked\r\n\r\n'
1387 'a\r\n'
1388 'hello worl\r\n'
1389 '3\r\n'
1390 'd!\n\r\n'
1391 '9\r\n'
1392 'and now \n\r\n'
1393 '23\r\n'
1394 'for something completely different\n\r\n'
1395 '3\r\n'
1396 'foo\r\n'
1397 '0\r\n' # terminating chunk
1398 '\r\n' # end of trailers
1399 )
1400
1401
1402class Readliner:
1403 """
1404 a simple readline class that uses an arbitrary read function and buffering
1405 """
1406 def __init__(self, readfunc):
1407 self.readfunc = readfunc
1408 self.remainder = b""
1409
1410 def readline(self, limit):
1411 data = []
1412 datalen = 0
1413 read = self.remainder
1414 try:
1415 while True:
1416 idx = read.find(b'\n')
1417 if idx != -1:
1418 break
1419 if datalen + len(read) >= limit:
1420 idx = limit - datalen - 1
1421 # read more data
1422 data.append(read)
1423 read = self.readfunc()
1424 if not read:
1425 idx = 0 #eof condition
1426 break
1427 idx += 1
1428 data.append(read[:idx])
1429 self.remainder = read[idx:]
1430 return b"".join(data)
1431 except:
1432 self.remainder = b"".join(data)
1433 raise
1434
Berker Peksagbabc6882015-02-20 09:39:38 +02001435
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001436class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001437 def test_all(self):
1438 # Documented objects defined in the module should be in __all__
1439 expected = {"responses"} # White-list documented dict() object
1440 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1441 # intentionally omitted for simplicity
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001442 denylist = {"HTTPMessage", "parse_headers"}
Berker Peksagbabc6882015-02-20 09:39:38 +02001443 for name in dir(client):
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001444 if name.startswith("_") or name in denylist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001445 continue
1446 module_object = getattr(client, name)
1447 if getattr(module_object, "__module__", None) == "http.client":
1448 expected.add(name)
1449 self.assertCountEqual(client.__all__, expected)
1450
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001451 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001452 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001453
Berker Peksagabbf0f42015-02-20 14:57:31 +02001454 def test_client_constants(self):
1455 # Make sure we don't break backward compatibility with 3.4
1456 expected = [
1457 'CONTINUE',
1458 'SWITCHING_PROTOCOLS',
1459 'PROCESSING',
1460 'OK',
1461 'CREATED',
1462 'ACCEPTED',
1463 'NON_AUTHORITATIVE_INFORMATION',
1464 'NO_CONTENT',
1465 'RESET_CONTENT',
1466 'PARTIAL_CONTENT',
1467 'MULTI_STATUS',
1468 'IM_USED',
1469 'MULTIPLE_CHOICES',
1470 'MOVED_PERMANENTLY',
1471 'FOUND',
1472 'SEE_OTHER',
1473 'NOT_MODIFIED',
1474 'USE_PROXY',
1475 'TEMPORARY_REDIRECT',
1476 'BAD_REQUEST',
1477 'UNAUTHORIZED',
1478 'PAYMENT_REQUIRED',
1479 'FORBIDDEN',
1480 'NOT_FOUND',
1481 'METHOD_NOT_ALLOWED',
1482 'NOT_ACCEPTABLE',
1483 'PROXY_AUTHENTICATION_REQUIRED',
1484 'REQUEST_TIMEOUT',
1485 'CONFLICT',
1486 'GONE',
1487 'LENGTH_REQUIRED',
1488 'PRECONDITION_FAILED',
1489 'REQUEST_ENTITY_TOO_LARGE',
1490 'REQUEST_URI_TOO_LONG',
1491 'UNSUPPORTED_MEDIA_TYPE',
1492 'REQUESTED_RANGE_NOT_SATISFIABLE',
1493 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001494 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001495 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001496 'UNPROCESSABLE_ENTITY',
1497 'LOCKED',
1498 'FAILED_DEPENDENCY',
1499 'UPGRADE_REQUIRED',
1500 'PRECONDITION_REQUIRED',
1501 'TOO_MANY_REQUESTS',
1502 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001503 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001504 'INTERNAL_SERVER_ERROR',
1505 'NOT_IMPLEMENTED',
1506 'BAD_GATEWAY',
1507 'SERVICE_UNAVAILABLE',
1508 'GATEWAY_TIMEOUT',
1509 'HTTP_VERSION_NOT_SUPPORTED',
1510 'INSUFFICIENT_STORAGE',
1511 'NOT_EXTENDED',
1512 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001513 'EARLY_HINTS',
1514 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001515 ]
1516 for const in expected:
1517 with self.subTest(constant=const):
1518 self.assertTrue(hasattr(client, const))
1519
Gregory P. Smithb4066372010-01-03 03:28:29 +00001520
1521class SourceAddressTest(TestCase):
1522 def setUp(self):
1523 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001524 self.port = socket_helper.bind_port(self.serv)
1525 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001526 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001527 self.conn = None
1528
1529 def tearDown(self):
1530 if self.conn:
1531 self.conn.close()
1532 self.conn = None
1533 self.serv.close()
1534 self.serv = None
1535
1536 def testHTTPConnectionSourceAddress(self):
1537 self.conn = client.HTTPConnection(HOST, self.port,
1538 source_address=('', self.source_port))
1539 self.conn.connect()
1540 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1541
1542 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1543 'http.client.HTTPSConnection not defined')
1544 def testHTTPSConnectionSourceAddress(self):
1545 self.conn = client.HTTPSConnection(HOST, self.port,
1546 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001547 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001548 # this code doesn't deal with setting up an active running SSL server
1549 # for an ssl_wrapped connect() to actually return from.
1550
1551
Guido van Rossumd8faa362007-04-27 19:54:29 +00001552class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001553 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001554
1555 def setUp(self):
1556 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001557 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001558 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001559
1560 def tearDown(self):
1561 self.serv.close()
1562 self.serv = None
1563
1564 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001565 # This will prove that the timeout gets through HTTPConnection
1566 # and into the socket.
1567
Georg Brandlf78e02b2008-06-10 17:40:04 +00001568 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001569 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001570 socket.setdefaulttimeout(30)
1571 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001572 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001573 httpConn.connect()
1574 finally:
1575 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001576 self.assertEqual(httpConn.sock.gettimeout(), 30)
1577 httpConn.close()
1578
Georg Brandlf78e02b2008-06-10 17:40:04 +00001579 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001580 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001581 socket.setdefaulttimeout(30)
1582 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001583 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001584 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001585 httpConn.connect()
1586 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001587 socket.setdefaulttimeout(None)
1588 self.assertEqual(httpConn.sock.gettimeout(), None)
1589 httpConn.close()
1590
1591 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001592 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001593 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001594 self.assertEqual(httpConn.sock.gettimeout(), 30)
1595 httpConn.close()
1596
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001597
R David Murraycae7bdb2015-04-05 19:26:29 -04001598class PersistenceTest(TestCase):
1599
1600 def test_reuse_reconnect(self):
1601 # Should reuse or reconnect depending on header from server
1602 tests = (
1603 ('1.0', '', False),
1604 ('1.0', 'Connection: keep-alive\r\n', True),
1605 ('1.1', '', True),
1606 ('1.1', 'Connection: close\r\n', False),
1607 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1608 ('1.1', 'Connection: cloSE\r\n', False),
1609 )
1610 for version, header, reuse in tests:
1611 with self.subTest(version=version, header=header):
1612 msg = (
1613 'HTTP/{} 200 OK\r\n'
1614 '{}'
1615 'Content-Length: 12\r\n'
1616 '\r\n'
1617 'Dummy body\r\n'
1618 ).format(version, header)
1619 conn = FakeSocketHTTPConnection(msg)
1620 self.assertIsNone(conn.sock)
1621 conn.request('GET', '/open-connection')
1622 with conn.getresponse() as response:
1623 self.assertEqual(conn.sock is None, not reuse)
1624 response.read()
1625 self.assertEqual(conn.sock is None, not reuse)
1626 self.assertEqual(conn.connections, 1)
1627 conn.request('GET', '/subsequent-request')
1628 self.assertEqual(conn.connections, 1 if reuse else 2)
1629
1630 def test_disconnected(self):
1631
1632 def make_reset_reader(text):
1633 """Return BufferedReader that raises ECONNRESET at EOF"""
1634 stream = io.BytesIO(text)
1635 def readinto(buffer):
1636 size = io.BytesIO.readinto(stream, buffer)
1637 if size == 0:
1638 raise ConnectionResetError()
1639 return size
1640 stream.readinto = readinto
1641 return io.BufferedReader(stream)
1642
1643 tests = (
1644 (io.BytesIO, client.RemoteDisconnected),
1645 (make_reset_reader, ConnectionResetError),
1646 )
1647 for stream_factory, exception in tests:
1648 with self.subTest(exception=exception):
1649 conn = FakeSocketHTTPConnection(b'', stream_factory)
1650 conn.request('GET', '/eof-response')
1651 self.assertRaises(exception, conn.getresponse)
1652 self.assertIsNone(conn.sock)
1653 # HTTPConnection.connect() should be automatically invoked
1654 conn.request('GET', '/reconnect')
1655 self.assertEqual(conn.connections, 2)
1656
1657 def test_100_close(self):
1658 conn = FakeSocketHTTPConnection(
1659 b'HTTP/1.1 100 Continue\r\n'
1660 b'\r\n'
1661 # Missing final response
1662 )
1663 conn.request('GET', '/', headers={'Expect': '100-continue'})
1664 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1665 self.assertIsNone(conn.sock)
1666 conn.request('GET', '/reconnect')
1667 self.assertEqual(conn.connections, 2)
1668
1669
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001670class HTTPSTest(TestCase):
1671
1672 def setUp(self):
1673 if not hasattr(client, 'HTTPSConnection'):
1674 self.skipTest('ssl support required')
1675
1676 def make_server(self, certfile):
1677 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001678 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001679
1680 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001681 # simple test to check it's storing the timeout
1682 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1683 self.assertEqual(h.timeout, 30)
1684
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001685 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001686 # Default settings: requires a valid cert from a trusted CA
1687 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001688 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001689 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001690 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1691 with self.assertRaises(ssl.SSLError) as exc_info:
1692 h.request('GET', '/')
1693 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1694
1695 def test_networked_noverification(self):
1696 # Switch off cert verification
1697 import ssl
1698 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001699 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001700 context = ssl._create_unverified_context()
1701 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1702 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001703 h.request('GET', '/')
1704 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001705 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001706 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001707 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001708
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001709 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001710 def test_networked_trusted_by_default_cert(self):
1711 # Default settings: requires a valid cert from a trusted CA
1712 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001713 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001714 h = client.HTTPSConnection('www.python.org', 443)
1715 h.request('GET', '/')
1716 resp = h.getresponse()
1717 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001718 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001719 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001720 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001721
1722 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001723 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001724 import ssl
1725 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001726 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001727 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001728 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1729 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1730 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001731 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001732 try:
1733 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1734 context=context)
1735 h.request('GET', '/')
1736 resp = h.getresponse()
1737 except ssl.SSLError as ssl_err:
1738 ssl_err_str = str(ssl_err)
1739 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1740 # modern Linux distros (Debian Buster, etc) default OpenSSL
1741 # configurations it'll fail saying "key too weak" until we
1742 # address https://bugs.python.org/issue36816 to use a proper
1743 # key size on self-signed.pythontest.net.
1744 if re.search(r'(?i)key.too.weak', ssl_err_str):
1745 raise unittest.SkipTest(
1746 f'Got {ssl_err_str} trying to connect '
1747 f'to {selfsigned_pythontestdotnet}. '
1748 'See https://bugs.python.org/issue36816.')
1749 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001750 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001751 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001752 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001753 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001754
1755 def test_networked_bad_cert(self):
1756 # We feed a "CA" cert that is unrelated to the server's cert
1757 import ssl
1758 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001759 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001760 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001761 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001762 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1763 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001764 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001765 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1766
1767 def test_local_unknown_cert(self):
1768 # The custom cert isn't known to the default trust bundle
1769 import ssl
1770 server = self.make_server(CERT_localhost)
1771 h = client.HTTPSConnection('localhost', server.port)
1772 with self.assertRaises(ssl.SSLError) as exc_info:
1773 h.request('GET', '/')
1774 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001775
1776 def test_local_good_hostname(self):
1777 # The (valid) cert validates the HTTP hostname
1778 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001779 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001780 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001781 context.load_verify_locations(CERT_localhost)
1782 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001783 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001784 h.request('GET', '/nonexistent')
1785 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001786 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001787 self.assertEqual(resp.status, 404)
1788
1789 def test_local_bad_hostname(self):
1790 # The (valid) cert doesn't validate the HTTP hostname
1791 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001792 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001793 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001794 context.load_verify_locations(CERT_fakehostname)
1795 h = client.HTTPSConnection('localhost', server.port, context=context)
1796 with self.assertRaises(ssl.CertificateError):
1797 h.request('GET', '/')
1798 # Same with explicit check_hostname=True
Hai Shi883bc632020-07-06 17:12:49 +08001799 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001800 h = client.HTTPSConnection('localhost', server.port,
1801 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001802 with self.assertRaises(ssl.CertificateError):
1803 h.request('GET', '/')
1804 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001805 context.check_hostname = False
Hai Shi883bc632020-07-06 17:12:49 +08001806 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001807 h = client.HTTPSConnection('localhost', server.port,
1808 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001809 h.request('GET', '/nonexistent')
1810 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001811 resp.close()
1812 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001813 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001814 # The context's check_hostname setting is used if one isn't passed to
1815 # HTTPSConnection.
1816 context.check_hostname = False
1817 h = client.HTTPSConnection('localhost', server.port, context=context)
1818 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001819 resp = h.getresponse()
1820 self.assertEqual(resp.status, 404)
1821 resp.close()
1822 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001823 # Passing check_hostname to HTTPSConnection should override the
1824 # context's setting.
Hai Shi883bc632020-07-06 17:12:49 +08001825 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001826 h = client.HTTPSConnection('localhost', server.port,
1827 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001828 with self.assertRaises(ssl.CertificateError):
1829 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001830
Petri Lehtinene119c402011-10-26 21:29:15 +03001831 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1832 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001833 def test_host_port(self):
1834 # Check invalid host_port
1835
1836 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1837 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1838
1839 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1840 "fe80::207:e9ff:fe9b", 8000),
1841 ("www.python.org:443", "www.python.org", 443),
1842 ("www.python.org:", "www.python.org", 443),
1843 ("www.python.org", "www.python.org", 443),
1844 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1845 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1846 443)):
1847 c = client.HTTPSConnection(hp)
1848 self.assertEqual(h, c.host)
1849 self.assertEqual(p, c.port)
1850
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001851 def test_tls13_pha(self):
1852 import ssl
1853 if not ssl.HAS_TLSv1_3:
1854 self.skipTest('TLS 1.3 support required')
1855 # just check status of PHA flag
1856 h = client.HTTPSConnection('localhost', 443)
1857 self.assertTrue(h._context.post_handshake_auth)
1858
1859 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1860 self.assertFalse(context.post_handshake_auth)
1861 h = client.HTTPSConnection('localhost', 443, context=context)
1862 self.assertIs(h._context, context)
1863 self.assertFalse(h._context.post_handshake_auth)
1864
Pablo Galindoaa542c22019-08-08 23:25:46 +01001865 with warnings.catch_warnings():
1866 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1867 DeprecationWarning)
1868 h = client.HTTPSConnection('localhost', 443, context=context,
1869 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001870 self.assertTrue(h._context.post_handshake_auth)
1871
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001872
Jeremy Hylton236654b2009-03-27 20:24:34 +00001873class RequestBodyTest(TestCase):
1874 """Test cases where a request includes a message body."""
1875
1876 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001877 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001878 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001879 self.conn.sock = self.sock
1880
1881 def get_headers_and_fp(self):
1882 f = io.BytesIO(self.sock.data)
1883 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001884 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001885 return message, f
1886
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001887 def test_list_body(self):
1888 # Note that no content-length is automatically calculated for
1889 # an iterable. The request will fall back to send chunked
1890 # transfer encoding.
1891 cases = (
1892 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1893 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1894 )
1895 for body, expected in cases:
1896 with self.subTest(body):
1897 self.conn = client.HTTPConnection('example.com')
1898 self.conn.sock = self.sock = FakeSocket('')
1899
1900 self.conn.request('PUT', '/url', body)
1901 msg, f = self.get_headers_and_fp()
1902 self.assertNotIn('Content-Type', msg)
1903 self.assertNotIn('Content-Length', msg)
1904 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1905 self.assertEqual(expected, f.read())
1906
Jeremy Hylton236654b2009-03-27 20:24:34 +00001907 def test_manual_content_length(self):
1908 # Set an incorrect content-length so that we can verify that
1909 # it will not be over-ridden by the library.
1910 self.conn.request("PUT", "/url", "body",
1911 {"Content-Length": "42"})
1912 message, f = self.get_headers_and_fp()
1913 self.assertEqual("42", message.get("content-length"))
1914 self.assertEqual(4, len(f.read()))
1915
1916 def test_ascii_body(self):
1917 self.conn.request("PUT", "/url", "body")
1918 message, f = self.get_headers_and_fp()
1919 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001920 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001921 self.assertEqual("4", message.get("content-length"))
1922 self.assertEqual(b'body', f.read())
1923
1924 def test_latin1_body(self):
1925 self.conn.request("PUT", "/url", "body\xc1")
1926 message, f = self.get_headers_and_fp()
1927 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001928 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001929 self.assertEqual("5", message.get("content-length"))
1930 self.assertEqual(b'body\xc1', f.read())
1931
1932 def test_bytes_body(self):
1933 self.conn.request("PUT", "/url", b"body\xc1")
1934 message, f = self.get_headers_and_fp()
1935 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001936 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001937 self.assertEqual("5", message.get("content-length"))
1938 self.assertEqual(b'body\xc1', f.read())
1939
Martin Panteref91bb22016-08-27 01:39:26 +00001940 def test_text_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001941 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1942 with open(os_helper.TESTFN, "w") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001943 f.write("body")
Hai Shi883bc632020-07-06 17:12:49 +08001944 with open(os_helper.TESTFN) as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001945 self.conn.request("PUT", "/url", f)
1946 message, f = self.get_headers_and_fp()
1947 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001948 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001949 # No content-length will be determined for files; the body
1950 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001951 self.assertIsNone(message.get("content-length"))
1952 self.assertEqual("chunked", message.get("transfer-encoding"))
1953 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001954
1955 def test_binary_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001956 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1957 with open(os_helper.TESTFN, "wb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001958 f.write(b"body\xc1")
Hai Shi883bc632020-07-06 17:12:49 +08001959 with open(os_helper.TESTFN, "rb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001960 self.conn.request("PUT", "/url", f)
1961 message, f = self.get_headers_and_fp()
1962 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001963 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001964 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1965 self.assertNotIn("Content-Length", message)
1966 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001967
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001968
1969class HTTPResponseTest(TestCase):
1970
1971 def setUp(self):
1972 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1973 second-value\r\n\r\nText"
1974 sock = FakeSocket(body)
1975 self.resp = client.HTTPResponse(sock)
1976 self.resp.begin()
1977
1978 def test_getting_header(self):
1979 header = self.resp.getheader('My-Header')
1980 self.assertEqual(header, 'first-value, second-value')
1981
1982 header = self.resp.getheader('My-Header', 'some default')
1983 self.assertEqual(header, 'first-value, second-value')
1984
1985 def test_getting_nonexistent_header_with_string_default(self):
1986 header = self.resp.getheader('No-Such-Header', 'default-value')
1987 self.assertEqual(header, 'default-value')
1988
1989 def test_getting_nonexistent_header_with_iterable_default(self):
1990 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1991 self.assertEqual(header, 'default, values')
1992
1993 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1994 self.assertEqual(header, 'default, values')
1995
1996 def test_getting_nonexistent_header_without_default(self):
1997 header = self.resp.getheader('No-Such-Header')
1998 self.assertEqual(header, None)
1999
2000 def test_getting_header_defaultint(self):
2001 header = self.resp.getheader('No-Such-Header',default=42)
2002 self.assertEqual(header, 42)
2003
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002004class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002005 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002006 response_text = (
2007 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
2008 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
2009 'Content-Length: 42\r\n\r\n'
2010 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002011 self.host = 'proxy.com'
2012 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02002013 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002014
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002015 def tearDown(self):
2016 self.conn.close()
2017
Berker Peksagab53ab02015-02-03 12:22:11 +02002018 def _create_connection(self, response_text):
2019 def create_connection(address, timeout=None, source_address=None):
2020 return FakeSocket(response_text, host=address[0], port=address[1])
2021 return create_connection
2022
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002023 def test_set_tunnel_host_port_headers(self):
2024 tunnel_host = 'destination.com'
2025 tunnel_port = 8888
2026 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2027 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2028 headers=tunnel_headers)
2029 self.conn.request('HEAD', '/', '')
2030 self.assertEqual(self.conn.sock.host, self.host)
2031 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2032 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2033 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2034 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2035
2036 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002037 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002038 self.conn.connect()
2039 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002040 'destination.com')
2041
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002042 def test_connect_with_tunnel(self):
2043 self.conn.set_tunnel('destination.com')
2044 self.conn.request('HEAD', '/', '')
2045 self.assertEqual(self.conn.sock.host, self.host)
2046 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2047 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002048 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002049 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2050 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002051
2052 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002053 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002054
Gregory P. Smithc25910a2021-03-07 23:35:13 -08002055 def test_tunnel_connect_single_send_connection_setup(self):
2056 """Regresstion test for https://bugs.python.org/issue43332."""
2057 with mock.patch.object(self.conn, 'send') as mock_send:
2058 self.conn.set_tunnel('destination.com')
2059 self.conn.connect()
2060 self.conn.request('GET', '/')
2061 mock_send.assert_called()
2062 # Likely 2, but this test only cares about the first.
2063 self.assertGreater(
2064 len(mock_send.mock_calls), 1,
2065 msg=f'unexpected number of send calls: {mock_send.mock_calls}')
2066 proxy_setup_data_sent = mock_send.mock_calls[0][1][0]
2067 self.assertIn(b'CONNECT destination.com', proxy_setup_data_sent)
2068 self.assertTrue(
2069 proxy_setup_data_sent.endswith(b'\r\n\r\n'),
2070 msg=f'unexpected proxy data sent {proxy_setup_data_sent!r}')
2071
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002072 def test_connect_put_request(self):
2073 self.conn.set_tunnel('destination.com')
2074 self.conn.request('PUT', '/', '')
2075 self.assertEqual(self.conn.sock.host, self.host)
2076 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2077 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2078 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2079
Berker Peksagab53ab02015-02-03 12:22:11 +02002080 def test_tunnel_debuglog(self):
2081 expected_header = 'X-Dummy: 1'
2082 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2083
2084 self.conn.set_debuglevel(1)
2085 self.conn._create_connection = self._create_connection(response_text)
2086 self.conn.set_tunnel('destination.com')
2087
2088 with support.captured_stdout() as output:
2089 self.conn.request('PUT', '/', '')
2090 lines = output.getvalue().splitlines()
2091 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002092
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002093
Thomas Wouters89f507f2006-12-13 04:49:30 +00002094if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002095 unittest.main(verbosity=2)