blob: 4abff60230b5462908c325786b066d476beed161 [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
13TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000014
Benjamin Petersonee8712c2008-05-20 21:35:26 +000015from test import support
Hai Shi883bc632020-07-06 17:12:49 +080016from test.support import os_helper
Serhiy Storchaka16994912020-04-25 10:06:29 +030017from test.support import socket_helper
Hai Shi883bc632020-07-06 17:12:49 +080018from test.support import warnings_helper
19
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000020
Antoine Pitrou803e6d62010-10-13 10:36:15 +000021here = os.path.dirname(__file__)
22# Self-signed cert file for 'localhost'
23CERT_localhost = os.path.join(here, 'keycert.pem')
24# Self-signed cert file for 'fakehostname'
25CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010026# Self-signed cert file for self-signed.pythontest.net
27CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000028
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000029# constants for testing chunked encoding
30chunked_start = (
31 'HTTP/1.1 200 OK\r\n'
32 'Transfer-Encoding: chunked\r\n\r\n'
33 'a\r\n'
34 'hello worl\r\n'
35 '3\r\n'
36 'd! \r\n'
37 '8\r\n'
38 'and now \r\n'
39 '22\r\n'
40 'for something completely different\r\n'
41)
42chunked_expected = b'hello world! and now for something completely different'
43chunk_extension = ";foo=bar"
44last_chunk = "0\r\n"
45last_chunk_extended = "0" + chunk_extension + "\r\n"
46trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
47chunked_end = "\r\n"
48
Serhiy Storchaka16994912020-04-25 10:06:29 +030049HOST = socket_helper.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000050
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000051class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040052 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000053 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000054 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000055 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000056 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000057 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010058 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020059 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040060 self.host = host
61 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000062
Jeremy Hylton2c178252004-08-07 16:28:14 +000063 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010064 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000065 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000066
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000067 def makefile(self, mode, bufsize=None):
68 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000069 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000070 # keep the file around so we can check how much was read from it
71 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020072 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000073 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000074
Serhiy Storchakab491e052014-12-01 13:07:45 +020075 def file_close(self):
76 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000077
Senthil Kumaran9da047b2014-04-14 13:07:56 -040078 def close(self):
79 pass
80
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050081 def setsockopt(self, level, optname, value):
82 pass
83
Jeremy Hylton636950f2009-03-28 04:34:21 +000084class EPipeSocket(FakeSocket):
85
86 def __init__(self, text, pipe_trigger):
87 # When sendall() is called with pipe_trigger, raise EPIPE.
88 FakeSocket.__init__(self, text)
89 self.pipe_trigger = pipe_trigger
90
91 def sendall(self, data):
92 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020093 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000094 self.data += data
95
96 def close(self):
97 pass
98
Serhiy Storchaka50254c52013-08-29 11:35:43 +030099class NoEOFBytesIO(io.BytesIO):
100 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000101
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000102 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000103 more from the underlying file than it should.
104 """
105 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000106 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000107 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000108 raise AssertionError('caller tried to read past EOF')
109 return data
110
111 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000112 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000113 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000114 raise AssertionError('caller tried to read past EOF')
115 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000116
R David Murraycae7bdb2015-04-05 19:26:29 -0400117class FakeSocketHTTPConnection(client.HTTPConnection):
118 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
119
120 def __init__(self, *args):
121 self.connections = 0
122 super().__init__('example.com')
123 self.fake_socket_args = args
124 self._create_connection = self.create_connection
125
126 def connect(self):
127 """Count the number of times connect() is invoked"""
128 self.connections += 1
129 return super().connect()
130
131 def create_connection(self, *pos, **kw):
132 return FakeSocket(*self.fake_socket_args)
133
Jeremy Hylton2c178252004-08-07 16:28:14 +0000134class HeaderTests(TestCase):
135 def test_auto_headers(self):
136 # Some headers are added automatically, but should not be added by
137 # .request() if they are explicitly set.
138
Jeremy Hylton2c178252004-08-07 16:28:14 +0000139 class HeaderCountingBuffer(list):
140 def __init__(self):
141 self.count = {}
142 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000143 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000144 if len(kv) > 1:
145 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000146 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000147 self.count.setdefault(lcKey, 0)
148 self.count[lcKey] += 1
149 list.append(self, item)
150
151 for explicit_header in True, False:
152 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000153 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000154 conn.sock = FakeSocket('blahblahblah')
155 conn._buffer = HeaderCountingBuffer()
156
157 body = 'spamspamspam'
158 headers = {}
159 if explicit_header:
160 headers[header] = str(len(body))
161 conn.request('POST', '/', body, headers)
162 self.assertEqual(conn._buffer.count[header.lower()], 1)
163
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800164 def test_content_length_0(self):
165
166 class ContentLengthChecker(list):
167 def __init__(self):
168 list.__init__(self)
169 self.content_length = None
170 def append(self, item):
171 kv = item.split(b':', 1)
172 if len(kv) > 1 and kv[0].lower() == b'content-length':
173 self.content_length = kv[1].strip()
174 list.append(self, item)
175
R David Murraybeed8402015-03-22 15:18:23 -0400176 # Here, we're testing that methods expecting a body get a
177 # content-length set to zero if the body is empty (either None or '')
178 bodies = (None, '')
179 methods_with_body = ('PUT', 'POST', 'PATCH')
180 for method, body in itertools.product(methods_with_body, bodies):
181 conn = client.HTTPConnection('example.com')
182 conn.sock = FakeSocket(None)
183 conn._buffer = ContentLengthChecker()
184 conn.request(method, '/', body)
185 self.assertEqual(
186 conn._buffer.content_length, b'0',
187 'Header Content-Length incorrect on {}'.format(method)
188 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800189
R David Murraybeed8402015-03-22 15:18:23 -0400190 # For these methods, we make sure that content-length is not set when
191 # the body is None because it might cause unexpected behaviour on the
192 # server.
193 methods_without_body = (
194 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
195 )
196 for method in methods_without_body:
197 conn = client.HTTPConnection('example.com')
198 conn.sock = FakeSocket(None)
199 conn._buffer = ContentLengthChecker()
200 conn.request(method, '/', None)
201 self.assertEqual(
202 conn._buffer.content_length, None,
203 'Header Content-Length set for empty body on {}'.format(method)
204 )
205
206 # If the body is set to '', that's considered to be "present but
207 # empty" rather than "missing", so content length would be set, even
208 # for methods that don't expect a body.
209 for method in methods_without_body:
210 conn = client.HTTPConnection('example.com')
211 conn.sock = FakeSocket(None)
212 conn._buffer = ContentLengthChecker()
213 conn.request(method, '/', '')
214 self.assertEqual(
215 conn._buffer.content_length, b'0',
216 'Header Content-Length incorrect on {}'.format(method)
217 )
218
219 # If the body is set, make sure Content-Length is set.
220 for method in itertools.chain(methods_without_body, methods_with_body):
221 conn = client.HTTPConnection('example.com')
222 conn.sock = FakeSocket(None)
223 conn._buffer = ContentLengthChecker()
224 conn.request(method, '/', ' ')
225 self.assertEqual(
226 conn._buffer.content_length, b'1',
227 'Header Content-Length incorrect on {}'.format(method)
228 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800229
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000230 def test_putheader(self):
231 conn = client.HTTPConnection('example.com')
232 conn.sock = FakeSocket(None)
233 conn.putrequest('GET','/')
234 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200235 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000236
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200237 conn.putheader('Foo', ' bar ')
238 self.assertIn(b'Foo: bar ', conn._buffer)
239 conn.putheader('Bar', '\tbaz\t')
240 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
241 conn.putheader('Authorization', 'Bearer mytoken')
242 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
243 conn.putheader('IterHeader', 'IterA', 'IterB')
244 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
245 conn.putheader('LatinHeader', b'\xFF')
246 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
247 conn.putheader('Utf8Header', b'\xc3\x80')
248 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
249 conn.putheader('C1-Control', b'next\x85line')
250 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
251 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
252 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
253 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
254 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
255 conn.putheader('Key Space', 'value')
256 self.assertIn(b'Key Space: value', conn._buffer)
257 conn.putheader('KeySpace ', 'value')
258 self.assertIn(b'KeySpace : value', conn._buffer)
259 conn.putheader(b'Nonbreak\xa0Space', 'value')
260 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
261 conn.putheader(b'\xa0NonbreakSpace', 'value')
262 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
263
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000264 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000265 # Default host header on IPv6 transaction should be wrapped by [] if
266 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000267 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
268 b'Accept-Encoding: identity\r\n\r\n'
269 conn = client.HTTPConnection('[2001::]:81')
270 sock = FakeSocket('')
271 conn.sock = sock
272 conn.request('GET', '/foo')
273 self.assertTrue(sock.data.startswith(expected))
274
275 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
276 b'Accept-Encoding: identity\r\n\r\n'
277 conn = client.HTTPConnection('[2001:102A::]')
278 sock = FakeSocket('')
279 conn.sock = sock
280 conn.request('GET', '/foo')
281 self.assertTrue(sock.data.startswith(expected))
282
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500283 def test_malformed_headers_coped_with(self):
284 # Issue 19996
285 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
286 sock = FakeSocket(body)
287 resp = client.HTTPResponse(sock)
288 resp.begin()
289
290 self.assertEqual(resp.getheader('First'), 'val')
291 self.assertEqual(resp.getheader('Second'), 'val')
292
R David Murraydc1650c2016-09-07 17:44:34 -0400293 def test_parse_all_octets(self):
294 # Ensure no valid header field octet breaks the parser
295 body = (
296 b'HTTP/1.1 200 OK\r\n'
297 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
298 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
299 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
300 b'obs-fold: text\r\n'
301 b' folded with space\r\n'
302 b'\tfolded with tab\r\n'
303 b'Content-Length: 0\r\n'
304 b'\r\n'
305 )
306 sock = FakeSocket(body)
307 resp = client.HTTPResponse(sock)
308 resp.begin()
309 self.assertEqual(resp.getheader('Content-Length'), '0')
310 self.assertEqual(resp.msg['Content-Length'], '0')
311 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
312 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
313 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
314 self.assertEqual(resp.getheader('VCHAR'), vchar)
315 self.assertEqual(resp.msg['VCHAR'], vchar)
316 self.assertIsNotNone(resp.getheader('obs-text'))
317 self.assertIn('obs-text', resp.msg)
318 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
319 self.assertTrue(folded.startswith('text'))
320 self.assertIn(' folded with space', folded)
321 self.assertTrue(folded.endswith('folded with tab'))
322
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200323 def test_invalid_headers(self):
324 conn = client.HTTPConnection('example.com')
325 conn.sock = FakeSocket('')
326 conn.putrequest('GET', '/')
327
328 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
329 # longer allowed in header names
330 cases = (
331 (b'Invalid\r\nName', b'ValidValue'),
332 (b'Invalid\rName', b'ValidValue'),
333 (b'Invalid\nName', b'ValidValue'),
334 (b'\r\nInvalidName', b'ValidValue'),
335 (b'\rInvalidName', b'ValidValue'),
336 (b'\nInvalidName', b'ValidValue'),
337 (b' InvalidName', b'ValidValue'),
338 (b'\tInvalidName', b'ValidValue'),
339 (b'Invalid:Name', b'ValidValue'),
340 (b':InvalidName', b'ValidValue'),
341 (b'ValidName', b'Invalid\r\nValue'),
342 (b'ValidName', b'Invalid\rValue'),
343 (b'ValidName', b'Invalid\nValue'),
344 (b'ValidName', b'InvalidValue\r\n'),
345 (b'ValidName', b'InvalidValue\r'),
346 (b'ValidName', b'InvalidValue\n'),
347 )
348 for name, value in cases:
349 with self.subTest((name, value)):
350 with self.assertRaisesRegex(ValueError, 'Invalid header'):
351 conn.putheader(name, value)
352
Marco Strigl936f03e2018-06-19 15:20:58 +0200353 def test_headers_debuglevel(self):
354 body = (
355 b'HTTP/1.1 200 OK\r\n'
356 b'First: val\r\n'
Matt Houglum461c4162019-04-03 21:36:47 -0700357 b'Second: val1\r\n'
358 b'Second: val2\r\n'
Marco Strigl936f03e2018-06-19 15:20:58 +0200359 )
360 sock = FakeSocket(body)
361 resp = client.HTTPResponse(sock, debuglevel=1)
362 with support.captured_stdout() as output:
363 resp.begin()
364 lines = output.getvalue().splitlines()
365 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
366 self.assertEqual(lines[1], "header: First: val")
Matt Houglum461c4162019-04-03 21:36:47 -0700367 self.assertEqual(lines[2], "header: Second: val1")
368 self.assertEqual(lines[3], "header: Second: val2")
Marco Strigl936f03e2018-06-19 15:20:58 +0200369
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000370
AMIR8ca8a2e2020-07-19 00:46:10 +0430371class HttpMethodTests(TestCase):
372 def test_invalid_method_names(self):
373 methods = (
374 'GET\r',
375 'POST\n',
376 'PUT\n\r',
377 'POST\nValue',
378 'POST\nHOST:abc',
379 'GET\nrHost:abc\n',
380 'POST\rRemainder:\r',
381 'GET\rHOST:\n',
382 '\nPUT'
383 )
384
385 for method in methods:
386 with self.assertRaisesRegex(
387 ValueError, "method can't contain control characters"):
388 conn = client.HTTPConnection('example.com')
389 conn.sock = FakeSocket(None)
390 conn.request(method=method, url="/")
391
392
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000393class TransferEncodingTest(TestCase):
394 expected_body = b"It's just a flesh wound"
395
396 def test_endheaders_chunked(self):
397 conn = client.HTTPConnection('example.com')
398 conn.sock = FakeSocket(b'')
399 conn.putrequest('POST', '/')
400 conn.endheaders(self._make_body(), encode_chunked=True)
401
402 _, _, body = self._parse_request(conn.sock.data)
403 body = self._parse_chunked(body)
404 self.assertEqual(body, self.expected_body)
405
406 def test_explicit_headers(self):
407 # explicit chunked
408 conn = client.HTTPConnection('example.com')
409 conn.sock = FakeSocket(b'')
410 # this shouldn't actually be automatically chunk-encoded because the
411 # calling code has explicitly stated that it's taking care of it
412 conn.request(
413 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
414
415 _, headers, body = self._parse_request(conn.sock.data)
416 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
417 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
418 self.assertEqual(body, self.expected_body)
419
420 # explicit chunked, string body
421 conn = client.HTTPConnection('example.com')
422 conn.sock = FakeSocket(b'')
423 conn.request(
424 'POST', '/', self.expected_body.decode('latin-1'),
425 {'Transfer-Encoding': 'chunked'})
426
427 _, headers, body = self._parse_request(conn.sock.data)
428 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
429 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
430 self.assertEqual(body, self.expected_body)
431
432 # User-specified TE, but request() does the chunk encoding
433 conn = client.HTTPConnection('example.com')
434 conn.sock = FakeSocket(b'')
435 conn.request('POST', '/',
436 headers={'Transfer-Encoding': 'gzip, chunked'},
437 encode_chunked=True,
438 body=self._make_body())
439 _, headers, body = self._parse_request(conn.sock.data)
440 self.assertNotIn('content-length', [k.lower() for k in headers])
441 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
442 self.assertEqual(self._parse_chunked(body), self.expected_body)
443
444 def test_request(self):
445 for empty_lines in (False, True,):
446 conn = client.HTTPConnection('example.com')
447 conn.sock = FakeSocket(b'')
448 conn.request(
449 'POST', '/', self._make_body(empty_lines=empty_lines))
450
451 _, headers, body = self._parse_request(conn.sock.data)
452 body = self._parse_chunked(body)
453 self.assertEqual(body, self.expected_body)
454 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
455
456 # Content-Length and Transfer-Encoding SHOULD not be sent in the
457 # same request
458 self.assertNotIn('content-length', [k.lower() for k in headers])
459
Martin Panteref91bb22016-08-27 01:39:26 +0000460 def test_empty_body(self):
461 # Zero-length iterable should be treated like any other iterable
462 conn = client.HTTPConnection('example.com')
463 conn.sock = FakeSocket(b'')
464 conn.request('POST', '/', ())
465 _, headers, body = self._parse_request(conn.sock.data)
466 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
467 self.assertNotIn('content-length', [k.lower() for k in headers])
468 self.assertEqual(body, b"0\r\n\r\n")
469
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000470 def _make_body(self, empty_lines=False):
471 lines = self.expected_body.split(b' ')
472 for idx, line in enumerate(lines):
473 # for testing handling empty lines
474 if empty_lines and idx % 2:
475 yield b''
476 if idx < len(lines) - 1:
477 yield line + b' '
478 else:
479 yield line
480
481 def _parse_request(self, data):
482 lines = data.split(b'\r\n')
483 request = lines[0]
484 headers = {}
485 n = 1
486 while n < len(lines) and len(lines[n]) > 0:
487 key, val = lines[n].split(b':')
488 key = key.decode('latin-1').strip()
489 headers[key] = val.decode('latin-1').strip()
490 n += 1
491
492 return request, headers, b'\r\n'.join(lines[n + 1:])
493
494 def _parse_chunked(self, data):
495 body = []
496 trailers = {}
497 n = 0
498 lines = data.split(b'\r\n')
499 # parse body
500 while True:
501 size, chunk = lines[n:n+2]
502 size = int(size, 16)
503
504 if size == 0:
505 n += 1
506 break
507
508 self.assertEqual(size, len(chunk))
509 body.append(chunk)
510
511 n += 2
512 # we /should/ hit the end chunk, but check against the size of
513 # lines so we're not stuck in an infinite loop should we get
514 # malformed data
515 if n > len(lines):
516 break
517
518 return b''.join(body)
519
520
Thomas Wouters89f507f2006-12-13 04:49:30 +0000521class BasicTest(TestCase):
Angelin BOOZ68526fe2020-09-21 15:11:06 +0200522 def test_dir_with_added_behavior_on_status(self):
523 # see issue40084
524 self.assertTrue({'description', 'name', 'phrase', 'value'} <= set(dir(HTTPStatus(404))))
525
Thomas Wouters89f507f2006-12-13 04:49:30 +0000526 def test_status_lines(self):
527 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000528
Thomas Wouters89f507f2006-12-13 04:49:30 +0000529 body = "HTTP/1.1 200 Ok\r\n\r\nText"
530 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000531 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000532 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200533 self.assertEqual(resp.read(0), b'') # Issue #20007
534 self.assertFalse(resp.isclosed())
535 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000536 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000537 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200538 self.assertFalse(resp.closed)
539 resp.close()
540 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000541
Thomas Wouters89f507f2006-12-13 04:49:30 +0000542 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
543 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000544 resp = client.HTTPResponse(sock)
545 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000546
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000547 def test_bad_status_repr(self):
548 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200549 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000550
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000551 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000552 # if we have Content-Length, HTTPResponse knows when to close itself,
553 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000554 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
555 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000556 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000557 resp.begin()
558 self.assertEqual(resp.read(2), b'Te')
559 self.assertFalse(resp.isclosed())
560 self.assertEqual(resp.read(2), b'xt')
561 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200562 self.assertFalse(resp.closed)
563 resp.close()
564 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000565
Martin Panterce911c32016-03-17 06:42:48 +0000566 def test_mixed_reads(self):
567 # readline() should update the remaining length, so that read() knows
568 # how much data is left and does not raise IncompleteRead
569 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
570 sock = FakeSocket(body)
571 resp = client.HTTPResponse(sock)
572 resp.begin()
573 self.assertEqual(resp.readline(), b'Text\r\n')
574 self.assertFalse(resp.isclosed())
575 self.assertEqual(resp.read(), b'Another')
576 self.assertTrue(resp.isclosed())
577 self.assertFalse(resp.closed)
578 resp.close()
579 self.assertTrue(resp.closed)
580
Antoine Pitrou38d96432011-12-06 22:33:57 +0100581 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000582 # if we have Content-Length, HTTPResponse knows when to close itself,
583 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100584 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
585 sock = FakeSocket(body)
586 resp = client.HTTPResponse(sock)
587 resp.begin()
588 b = bytearray(2)
589 n = resp.readinto(b)
590 self.assertEqual(n, 2)
591 self.assertEqual(bytes(b), b'Te')
592 self.assertFalse(resp.isclosed())
593 n = resp.readinto(b)
594 self.assertEqual(n, 2)
595 self.assertEqual(bytes(b), b'xt')
596 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200597 self.assertFalse(resp.closed)
598 resp.close()
599 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100600
Bruce Merry152f0b82020-06-25 08:30:21 +0200601 def test_partial_reads_past_end(self):
602 # if we have Content-Length, clip reads to the end
603 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
604 sock = FakeSocket(body)
605 resp = client.HTTPResponse(sock)
606 resp.begin()
607 self.assertEqual(resp.read(10), b'Text')
608 self.assertTrue(resp.isclosed())
609 self.assertFalse(resp.closed)
610 resp.close()
611 self.assertTrue(resp.closed)
612
613 def test_partial_readintos_past_end(self):
614 # if we have Content-Length, clip readintos to the end
615 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
616 sock = FakeSocket(body)
617 resp = client.HTTPResponse(sock)
618 resp.begin()
619 b = bytearray(10)
620 n = resp.readinto(b)
621 self.assertEqual(n, 4)
622 self.assertEqual(bytes(b)[:4], b'Text')
623 self.assertTrue(resp.isclosed())
624 self.assertFalse(resp.closed)
625 resp.close()
626 self.assertTrue(resp.closed)
627
Antoine Pitrou084daa22012-12-15 19:11:54 +0100628 def test_partial_reads_no_content_length(self):
629 # when no length is present, the socket should be gracefully closed when
630 # all data was read
631 body = "HTTP/1.1 200 Ok\r\n\r\nText"
632 sock = FakeSocket(body)
633 resp = client.HTTPResponse(sock)
634 resp.begin()
635 self.assertEqual(resp.read(2), b'Te')
636 self.assertFalse(resp.isclosed())
637 self.assertEqual(resp.read(2), b'xt')
638 self.assertEqual(resp.read(1), b'')
639 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200640 self.assertFalse(resp.closed)
641 resp.close()
642 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100643
Antoine Pitroud20e7742012-12-15 19:22:30 +0100644 def test_partial_readintos_no_content_length(self):
645 # when no length is present, the socket should be gracefully closed when
646 # all data was read
647 body = "HTTP/1.1 200 Ok\r\n\r\nText"
648 sock = FakeSocket(body)
649 resp = client.HTTPResponse(sock)
650 resp.begin()
651 b = bytearray(2)
652 n = resp.readinto(b)
653 self.assertEqual(n, 2)
654 self.assertEqual(bytes(b), b'Te')
655 self.assertFalse(resp.isclosed())
656 n = resp.readinto(b)
657 self.assertEqual(n, 2)
658 self.assertEqual(bytes(b), b'xt')
659 n = resp.readinto(b)
660 self.assertEqual(n, 0)
661 self.assertTrue(resp.isclosed())
662
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100663 def test_partial_reads_incomplete_body(self):
664 # if the server shuts down the connection before the whole
665 # content-length is delivered, the socket is gracefully closed
666 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
667 sock = FakeSocket(body)
668 resp = client.HTTPResponse(sock)
669 resp.begin()
670 self.assertEqual(resp.read(2), b'Te')
671 self.assertFalse(resp.isclosed())
672 self.assertEqual(resp.read(2), b'xt')
673 self.assertEqual(resp.read(1), b'')
674 self.assertTrue(resp.isclosed())
675
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100676 def test_partial_readintos_incomplete_body(self):
677 # if the server shuts down the connection before the whole
678 # content-length is delivered, the socket is gracefully closed
679 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
680 sock = FakeSocket(body)
681 resp = client.HTTPResponse(sock)
682 resp.begin()
683 b = bytearray(2)
684 n = resp.readinto(b)
685 self.assertEqual(n, 2)
686 self.assertEqual(bytes(b), b'Te')
687 self.assertFalse(resp.isclosed())
688 n = resp.readinto(b)
689 self.assertEqual(n, 2)
690 self.assertEqual(bytes(b), b'xt')
691 n = resp.readinto(b)
692 self.assertEqual(n, 0)
693 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200694 self.assertFalse(resp.closed)
695 resp.close()
696 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100697
Thomas Wouters89f507f2006-12-13 04:49:30 +0000698 def test_host_port(self):
699 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000700
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200701 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000702 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000703
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000704 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
705 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000706 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200707 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000708 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200709 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
710 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000711 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000712 self.assertEqual(h, c.host)
713 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000714
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 def test_response_headers(self):
716 # test response with multiple message headers with the same field name.
717 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000718 'Set-Cookie: Customer="WILE_E_COYOTE"; '
719 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000720 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
721 ' Path="/acme"\r\n'
722 '\r\n'
723 'No body\r\n')
724 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
725 ', '
726 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
727 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000728 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729 r.begin()
730 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000731 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000732
Thomas Wouters89f507f2006-12-13 04:49:30 +0000733 def test_read_head(self):
734 # Test that the library doesn't attempt to read any data
735 # from a HEAD request. (Tickles SF bug #622042.)
736 sock = FakeSocket(
737 'HTTP/1.1 200 OK\r\n'
738 'Content-Length: 14432\r\n'
739 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300740 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000741 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000742 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000743 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000745
Antoine Pitrou38d96432011-12-06 22:33:57 +0100746 def test_readinto_head(self):
747 # Test that the library doesn't attempt to read any data
748 # from a HEAD request. (Tickles SF bug #622042.)
749 sock = FakeSocket(
750 'HTTP/1.1 200 OK\r\n'
751 'Content-Length: 14432\r\n'
752 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300753 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100754 resp = client.HTTPResponse(sock, method="HEAD")
755 resp.begin()
756 b = bytearray(5)
757 if resp.readinto(b) != 0:
758 self.fail("Did not expect response from HEAD request")
759 self.assertEqual(bytes(b), b'\x00'*5)
760
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100761 def test_too_many_headers(self):
762 headers = '\r\n'.join('Header%d: foo' % i
763 for i in range(client._MAXHEADERS + 1)) + '\r\n'
764 text = ('HTTP/1.1 200 OK\r\n' + headers)
765 s = FakeSocket(text)
766 r = client.HTTPResponse(s)
767 self.assertRaisesRegex(client.HTTPException,
768 r"got more than \d+ headers", r.begin)
769
Thomas Wouters89f507f2006-12-13 04:49:30 +0000770 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000771 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000772 b'Accept-Encoding: identity\r\n'
773 b'Transfer-Encoding: chunked\r\n'
774 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000775
Brett Cannon77b7de62010-10-29 23:31:11 +0000776 with open(__file__, 'rb') as body:
777 conn = client.HTTPConnection('example.com')
778 sock = FakeSocket(body)
779 conn.sock = sock
780 conn.request('GET', '/foo', body)
781 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
782 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000783
Antoine Pitrouead1d622009-09-29 18:44:53 +0000784 def test_send(self):
785 expected = b'this is a test this is only a test'
786 conn = client.HTTPConnection('example.com')
787 sock = FakeSocket(None)
788 conn.sock = sock
789 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000790 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000791 sock.data = b''
792 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000793 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000794 sock.data = b''
795 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000796 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000797
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300798 def test_send_updating_file(self):
799 def data():
800 yield 'data'
801 yield None
802 yield 'data_two'
803
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000804 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300805 mode = 'r'
806 d = data()
807 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000808 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300809
810 expected = b'data'
811
812 conn = client.HTTPConnection('example.com')
813 sock = FakeSocket("")
814 conn.sock = sock
815 conn.send(UpdatingFile())
816 self.assertEqual(sock.data, expected)
817
818
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000819 def test_send_iter(self):
820 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
821 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
822 b'\r\nonetwothree'
823
824 def body():
825 yield b"one"
826 yield b"two"
827 yield b"three"
828
829 conn = client.HTTPConnection('example.com')
830 sock = FakeSocket("")
831 conn.sock = sock
832 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000833 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000834
Nir Sofferad455cd2017-11-06 23:16:37 +0200835 def test_blocksize_request(self):
836 """Check that request() respects the configured block size."""
837 blocksize = 8 # For easy debugging.
838 conn = client.HTTPConnection('example.com', blocksize=blocksize)
839 sock = FakeSocket(None)
840 conn.sock = sock
841 expected = b"a" * blocksize + b"b"
842 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
843 self.assertEqual(sock.sendall_calls, 3)
844 body = sock.data.split(b"\r\n\r\n", 1)[1]
845 self.assertEqual(body, expected)
846
847 def test_blocksize_send(self):
848 """Check that send() respects the configured block size."""
849 blocksize = 8 # For easy debugging.
850 conn = client.HTTPConnection('example.com', blocksize=blocksize)
851 sock = FakeSocket(None)
852 conn.sock = sock
853 expected = b"a" * blocksize + b"b"
854 conn.send(io.BytesIO(expected))
855 self.assertEqual(sock.sendall_calls, 2)
856 self.assertEqual(sock.data, expected)
857
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800858 def test_send_type_error(self):
859 # See: Issue #12676
860 conn = client.HTTPConnection('example.com')
861 conn.sock = FakeSocket('')
862 with self.assertRaises(TypeError):
863 conn.request('POST', 'test', conn)
864
Christian Heimesa612dc02008-02-24 13:08:18 +0000865 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000866 expected = chunked_expected
867 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000868 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000869 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100870 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000871 resp.close()
872
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100873 # Various read sizes
874 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000875 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100876 resp = client.HTTPResponse(sock, method="GET")
877 resp.begin()
878 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
879 resp.close()
880
Christian Heimesa612dc02008-02-24 13:08:18 +0000881 for x in ('', 'foo\r\n'):
882 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000883 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000884 resp.begin()
885 try:
886 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000887 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100888 self.assertEqual(i.partial, expected)
889 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
890 self.assertEqual(repr(i), expected_message)
891 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000892 else:
893 self.fail('IncompleteRead expected')
894 finally:
895 resp.close()
896
Antoine Pitrou38d96432011-12-06 22:33:57 +0100897 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000898
899 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100900 nexpected = len(expected)
901 b = bytearray(128)
902
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000903 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100904 resp = client.HTTPResponse(sock, method="GET")
905 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100906 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100907 self.assertEqual(b[:nexpected], expected)
908 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100909 resp.close()
910
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100911 # Various read sizes
912 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000913 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100914 resp = client.HTTPResponse(sock, method="GET")
915 resp.begin()
916 m = memoryview(b)
917 i = resp.readinto(m[0:n])
918 i += resp.readinto(m[i:n + i])
919 i += resp.readinto(m[i:])
920 self.assertEqual(b[:nexpected], expected)
921 self.assertEqual(i, nexpected)
922 resp.close()
923
Antoine Pitrou38d96432011-12-06 22:33:57 +0100924 for x in ('', 'foo\r\n'):
925 sock = FakeSocket(chunked_start + x)
926 resp = client.HTTPResponse(sock, method="GET")
927 resp.begin()
928 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100929 n = resp.readinto(b)
930 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100931 self.assertEqual(i.partial, expected)
932 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
933 self.assertEqual(repr(i), expected_message)
934 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100935 else:
936 self.fail('IncompleteRead expected')
937 finally:
938 resp.close()
939
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000940 def test_chunked_head(self):
941 chunked_start = (
942 'HTTP/1.1 200 OK\r\n'
943 'Transfer-Encoding: chunked\r\n\r\n'
944 'a\r\n'
945 'hello world\r\n'
946 '1\r\n'
947 'd\r\n'
948 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000949 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000950 resp = client.HTTPResponse(sock, method="HEAD")
951 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000952 self.assertEqual(resp.read(), b'')
953 self.assertEqual(resp.status, 200)
954 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000955 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200956 self.assertFalse(resp.closed)
957 resp.close()
958 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000959
Antoine Pitrou38d96432011-12-06 22:33:57 +0100960 def test_readinto_chunked_head(self):
961 chunked_start = (
962 'HTTP/1.1 200 OK\r\n'
963 'Transfer-Encoding: chunked\r\n\r\n'
964 'a\r\n'
965 'hello world\r\n'
966 '1\r\n'
967 'd\r\n'
968 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000969 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100970 resp = client.HTTPResponse(sock, method="HEAD")
971 resp.begin()
972 b = bytearray(5)
973 n = resp.readinto(b)
974 self.assertEqual(n, 0)
975 self.assertEqual(bytes(b), b'\x00'*5)
976 self.assertEqual(resp.status, 200)
977 self.assertEqual(resp.reason, 'OK')
978 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200979 self.assertFalse(resp.closed)
980 resp.close()
981 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100982
Christian Heimesa612dc02008-02-24 13:08:18 +0000983 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000984 sock = FakeSocket(
985 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000986 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000987 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000988 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100989 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000990
Benjamin Peterson6accb982009-03-02 22:50:25 +0000991 def test_incomplete_read(self):
992 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000993 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000994 resp.begin()
995 try:
996 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000997 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000998 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000999 self.assertEqual(repr(i),
1000 "IncompleteRead(7 bytes read, 3 more expected)")
1001 self.assertEqual(str(i),
1002 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +01001003 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +00001004 else:
1005 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +00001006
Jeremy Hylton636950f2009-03-28 04:34:21 +00001007 def test_epipe(self):
1008 sock = EPipeSocket(
1009 "HTTP/1.0 401 Authorization Required\r\n"
1010 "Content-type: text/html\r\n"
1011 "WWW-Authenticate: Basic realm=\"example\"\r\n",
1012 b"Content-Length")
1013 conn = client.HTTPConnection("example.com")
1014 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +02001015 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +00001016 lambda: conn.request("PUT", "/url", "body"))
1017 resp = conn.getresponse()
1018 self.assertEqual(401, resp.status)
1019 self.assertEqual("Basic realm=\"example\"",
1020 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +00001021
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001022 # Test lines overflowing the max line size (_MAXLINE in http.client)
1023
1024 def test_overflowing_status_line(self):
1025 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
1026 resp = client.HTTPResponse(FakeSocket(body))
1027 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
1028
1029 def test_overflowing_header_line(self):
1030 body = (
1031 'HTTP/1.1 200 OK\r\n'
1032 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1033 )
1034 resp = client.HTTPResponse(FakeSocket(body))
1035 self.assertRaises(client.LineTooLong, resp.begin)
1036
1037 def test_overflowing_chunked_line(self):
1038 body = (
1039 'HTTP/1.1 200 OK\r\n'
1040 'Transfer-Encoding: chunked\r\n\r\n'
1041 + '0' * 65536 + 'a\r\n'
1042 'hello world\r\n'
1043 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001044 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001045 )
1046 resp = client.HTTPResponse(FakeSocket(body))
1047 resp.begin()
1048 self.assertRaises(client.LineTooLong, resp.read)
1049
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001050 def test_early_eof(self):
1051 # Test httpresponse with no \r\n termination,
1052 body = "HTTP/1.1 200 Ok"
1053 sock = FakeSocket(body)
1054 resp = client.HTTPResponse(sock)
1055 resp.begin()
1056 self.assertEqual(resp.read(), b'')
1057 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001058 self.assertFalse(resp.closed)
1059 resp.close()
1060 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001061
Serhiy Storchakab491e052014-12-01 13:07:45 +02001062 def test_error_leak(self):
1063 # Test that the socket is not leaked if getresponse() fails
1064 conn = client.HTTPConnection('example.com')
1065 response = None
1066 class Response(client.HTTPResponse):
1067 def __init__(self, *pos, **kw):
1068 nonlocal response
1069 response = self # Avoid garbage collector closing the socket
1070 client.HTTPResponse.__init__(self, *pos, **kw)
1071 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001072 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001073 conn.request('GET', '/')
1074 self.assertRaises(client.BadStatusLine, conn.getresponse)
1075 self.assertTrue(response.closed)
1076 self.assertTrue(conn.sock.file_closed)
1077
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001078 def test_chunked_extension(self):
1079 extra = '3;foo=bar\r\n' + 'abc\r\n'
1080 expected = chunked_expected + b'abc'
1081
1082 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1083 resp = client.HTTPResponse(sock, method="GET")
1084 resp.begin()
1085 self.assertEqual(resp.read(), expected)
1086 resp.close()
1087
1088 def test_chunked_missing_end(self):
1089 """some servers may serve up a short chunked encoding stream"""
1090 expected = chunked_expected
1091 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1092 resp = client.HTTPResponse(sock, method="GET")
1093 resp.begin()
1094 self.assertEqual(resp.read(), expected)
1095 resp.close()
1096
1097 def test_chunked_trailers(self):
1098 """See that trailers are read and ignored"""
1099 expected = chunked_expected
1100 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1101 resp = client.HTTPResponse(sock, method="GET")
1102 resp.begin()
1103 self.assertEqual(resp.read(), expected)
1104 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001105 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001106 resp.close()
1107
1108 def test_chunked_sync(self):
1109 """Check that we don't read past the end of the chunked-encoding stream"""
1110 expected = chunked_expected
1111 extradata = "extradata"
1112 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1113 resp = client.HTTPResponse(sock, method="GET")
1114 resp.begin()
1115 self.assertEqual(resp.read(), expected)
1116 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001117 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001118 resp.close()
1119
1120 def test_content_length_sync(self):
1121 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001122 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001123 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001124 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 +00001125 resp = client.HTTPResponse(sock, method="GET")
1126 resp.begin()
1127 self.assertEqual(resp.read(), expected)
1128 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001129 self.assertEqual(sock.file.read(), extradata) #we read to the end
1130 resp.close()
1131
1132 def test_readlines_content_length(self):
1133 extradata = b"extradata"
1134 expected = b"Hello123\r\n"
1135 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1136 resp = client.HTTPResponse(sock, method="GET")
1137 resp.begin()
1138 self.assertEqual(resp.readlines(2000), [expected])
1139 # the file should now have our extradata ready to be read
1140 self.assertEqual(sock.file.read(), extradata) #we read to the end
1141 resp.close()
1142
1143 def test_read1_content_length(self):
1144 extradata = b"extradata"
1145 expected = b"Hello123\r\n"
1146 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1147 resp = client.HTTPResponse(sock, method="GET")
1148 resp.begin()
1149 self.assertEqual(resp.read1(2000), expected)
1150 # the file should now have our extradata ready to be read
1151 self.assertEqual(sock.file.read(), extradata) #we read to the end
1152 resp.close()
1153
1154 def test_readline_bound_content_length(self):
1155 extradata = b"extradata"
1156 expected = b"Hello123\r\n"
1157 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1158 resp = client.HTTPResponse(sock, method="GET")
1159 resp.begin()
1160 self.assertEqual(resp.readline(10), expected)
1161 self.assertEqual(resp.readline(10), b"")
1162 # the file should now have our extradata ready to be read
1163 self.assertEqual(sock.file.read(), extradata) #we read to the end
1164 resp.close()
1165
1166 def test_read1_bound_content_length(self):
1167 extradata = b"extradata"
1168 expected = b"Hello123\r\n"
1169 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1170 resp = client.HTTPResponse(sock, method="GET")
1171 resp.begin()
1172 self.assertEqual(resp.read1(20), expected*2)
1173 self.assertEqual(resp.read(), expected)
1174 # the file should now have our extradata ready to be read
1175 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001176 resp.close()
1177
Martin Panterd979b2c2016-04-09 14:03:17 +00001178 def test_response_fileno(self):
1179 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001180 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001181 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001182
1183 result = None
1184 def run_server():
1185 [conn, address] = serv.accept()
1186 with conn, conn.makefile("rb") as reader:
1187 # Read the request header until a blank line
1188 while True:
1189 line = reader.readline()
1190 if not line.rstrip(b"\r\n"):
1191 break
1192 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1193 nonlocal result
1194 result = reader.read()
1195
1196 thread = threading.Thread(target=run_server)
1197 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001198 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001199 conn = client.HTTPConnection(*serv.getsockname())
1200 conn.request("CONNECT", "dummy:1234")
1201 response = conn.getresponse()
1202 try:
1203 self.assertEqual(response.status, client.OK)
1204 s = socket.socket(fileno=response.fileno())
1205 try:
1206 s.sendall(b"proxied data\n")
1207 finally:
1208 s.detach()
1209 finally:
1210 response.close()
1211 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001212 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001213 self.assertEqual(result, b"proxied data\n")
1214
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001215 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001216 """
1217 It should be possible to override the default validation
1218 behavior in putrequest (bpo-38216).
1219 """
1220 class UnsafeHTTPConnection(client.HTTPConnection):
1221 def _validate_path(self, url):
1222 pass
1223
1224 conn = UnsafeHTTPConnection('example.com')
1225 conn.sock = FakeSocket('')
1226 conn.putrequest('GET', '/\x00')
1227
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001228 def test_putrequest_override_host_validation(self):
1229 class UnsafeHTTPConnection(client.HTTPConnection):
1230 def _validate_host(self, url):
1231 pass
1232
1233 conn = UnsafeHTTPConnection('example.com\r\n')
1234 conn.sock = FakeSocket('')
1235 # set skip_host so a ValueError is not raised upon adding the
1236 # invalid URL as the value of the "Host:" header
1237 conn.putrequest('GET', '/', skip_host=1)
1238
Jason R. Coombs7774d782019-09-28 08:32:01 -04001239 def test_putrequest_override_encoding(self):
1240 """
1241 It should be possible to override the default encoding
1242 to transmit bytes in another encoding even if invalid
1243 (bpo-36274).
1244 """
1245 class UnsafeHTTPConnection(client.HTTPConnection):
1246 def _encode_request(self, str_url):
1247 return str_url.encode('utf-8')
1248
1249 conn = UnsafeHTTPConnection('example.com')
1250 conn.sock = FakeSocket('')
1251 conn.putrequest('GET', '/☃')
1252
1253
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001254class ExtendedReadTest(TestCase):
1255 """
1256 Test peek(), read1(), readline()
1257 """
1258 lines = (
1259 'HTTP/1.1 200 OK\r\n'
1260 '\r\n'
1261 'hello world!\n'
1262 'and now \n'
1263 'for something completely different\n'
1264 'foo'
1265 )
1266 lines_expected = lines[lines.find('hello'):].encode("ascii")
1267 lines_chunked = (
1268 'HTTP/1.1 200 OK\r\n'
1269 'Transfer-Encoding: chunked\r\n\r\n'
1270 'a\r\n'
1271 'hello worl\r\n'
1272 '3\r\n'
1273 'd!\n\r\n'
1274 '9\r\n'
1275 'and now \n\r\n'
1276 '23\r\n'
1277 'for something completely different\n\r\n'
1278 '3\r\n'
1279 'foo\r\n'
1280 '0\r\n' # terminating chunk
1281 '\r\n' # end of trailers
1282 )
1283
1284 def setUp(self):
1285 sock = FakeSocket(self.lines)
1286 resp = client.HTTPResponse(sock, method="GET")
1287 resp.begin()
1288 resp.fp = io.BufferedReader(resp.fp)
1289 self.resp = resp
1290
1291
1292
1293 def test_peek(self):
1294 resp = self.resp
1295 # patch up the buffered peek so that it returns not too much stuff
1296 oldpeek = resp.fp.peek
1297 def mypeek(n=-1):
1298 p = oldpeek(n)
1299 if n >= 0:
1300 return p[:n]
1301 return p[:10]
1302 resp.fp.peek = mypeek
1303
1304 all = []
1305 while True:
1306 # try a short peek
1307 p = resp.peek(3)
1308 if p:
1309 self.assertGreater(len(p), 0)
1310 # then unbounded peek
1311 p2 = resp.peek()
1312 self.assertGreaterEqual(len(p2), len(p))
1313 self.assertTrue(p2.startswith(p))
1314 next = resp.read(len(p2))
1315 self.assertEqual(next, p2)
1316 else:
1317 next = resp.read()
1318 self.assertFalse(next)
1319 all.append(next)
1320 if not next:
1321 break
1322 self.assertEqual(b"".join(all), self.lines_expected)
1323
1324 def test_readline(self):
1325 resp = self.resp
1326 self._verify_readline(self.resp.readline, self.lines_expected)
1327
1328 def _verify_readline(self, readline, expected):
1329 all = []
1330 while True:
1331 # short readlines
1332 line = readline(5)
1333 if line and line != b"foo":
1334 if len(line) < 5:
1335 self.assertTrue(line.endswith(b"\n"))
1336 all.append(line)
1337 if not line:
1338 break
1339 self.assertEqual(b"".join(all), expected)
1340
1341 def test_read1(self):
1342 resp = self.resp
1343 def r():
1344 res = resp.read1(4)
1345 self.assertLessEqual(len(res), 4)
1346 return res
1347 readliner = Readliner(r)
1348 self._verify_readline(readliner.readline, self.lines_expected)
1349
1350 def test_read1_unbounded(self):
1351 resp = self.resp
1352 all = []
1353 while True:
1354 data = resp.read1()
1355 if not data:
1356 break
1357 all.append(data)
1358 self.assertEqual(b"".join(all), self.lines_expected)
1359
1360 def test_read1_bounded(self):
1361 resp = self.resp
1362 all = []
1363 while True:
1364 data = resp.read1(10)
1365 if not data:
1366 break
1367 self.assertLessEqual(len(data), 10)
1368 all.append(data)
1369 self.assertEqual(b"".join(all), self.lines_expected)
1370
1371 def test_read1_0(self):
1372 self.assertEqual(self.resp.read1(0), b"")
1373
1374 def test_peek_0(self):
1375 p = self.resp.peek(0)
1376 self.assertLessEqual(0, len(p))
1377
Jason R. Coombs7774d782019-09-28 08:32:01 -04001378
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001379class ExtendedReadTestChunked(ExtendedReadTest):
1380 """
1381 Test peek(), read1(), readline() in chunked mode
1382 """
1383 lines = (
1384 'HTTP/1.1 200 OK\r\n'
1385 'Transfer-Encoding: chunked\r\n\r\n'
1386 'a\r\n'
1387 'hello worl\r\n'
1388 '3\r\n'
1389 'd!\n\r\n'
1390 '9\r\n'
1391 'and now \n\r\n'
1392 '23\r\n'
1393 'for something completely different\n\r\n'
1394 '3\r\n'
1395 'foo\r\n'
1396 '0\r\n' # terminating chunk
1397 '\r\n' # end of trailers
1398 )
1399
1400
1401class Readliner:
1402 """
1403 a simple readline class that uses an arbitrary read function and buffering
1404 """
1405 def __init__(self, readfunc):
1406 self.readfunc = readfunc
1407 self.remainder = b""
1408
1409 def readline(self, limit):
1410 data = []
1411 datalen = 0
1412 read = self.remainder
1413 try:
1414 while True:
1415 idx = read.find(b'\n')
1416 if idx != -1:
1417 break
1418 if datalen + len(read) >= limit:
1419 idx = limit - datalen - 1
1420 # read more data
1421 data.append(read)
1422 read = self.readfunc()
1423 if not read:
1424 idx = 0 #eof condition
1425 break
1426 idx += 1
1427 data.append(read[:idx])
1428 self.remainder = read[idx:]
1429 return b"".join(data)
1430 except:
1431 self.remainder = b"".join(data)
1432 raise
1433
Berker Peksagbabc6882015-02-20 09:39:38 +02001434
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001435class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001436 def test_all(self):
1437 # Documented objects defined in the module should be in __all__
1438 expected = {"responses"} # White-list documented dict() object
1439 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1440 # intentionally omitted for simplicity
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001441 denylist = {"HTTPMessage", "parse_headers"}
Berker Peksagbabc6882015-02-20 09:39:38 +02001442 for name in dir(client):
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001443 if name.startswith("_") or name in denylist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001444 continue
1445 module_object = getattr(client, name)
1446 if getattr(module_object, "__module__", None) == "http.client":
1447 expected.add(name)
1448 self.assertCountEqual(client.__all__, expected)
1449
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001450 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001451 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001452
Berker Peksagabbf0f42015-02-20 14:57:31 +02001453 def test_client_constants(self):
1454 # Make sure we don't break backward compatibility with 3.4
1455 expected = [
1456 'CONTINUE',
1457 'SWITCHING_PROTOCOLS',
1458 'PROCESSING',
1459 'OK',
1460 'CREATED',
1461 'ACCEPTED',
1462 'NON_AUTHORITATIVE_INFORMATION',
1463 'NO_CONTENT',
1464 'RESET_CONTENT',
1465 'PARTIAL_CONTENT',
1466 'MULTI_STATUS',
1467 'IM_USED',
1468 'MULTIPLE_CHOICES',
1469 'MOVED_PERMANENTLY',
1470 'FOUND',
1471 'SEE_OTHER',
1472 'NOT_MODIFIED',
1473 'USE_PROXY',
1474 'TEMPORARY_REDIRECT',
1475 'BAD_REQUEST',
1476 'UNAUTHORIZED',
1477 'PAYMENT_REQUIRED',
1478 'FORBIDDEN',
1479 'NOT_FOUND',
1480 'METHOD_NOT_ALLOWED',
1481 'NOT_ACCEPTABLE',
1482 'PROXY_AUTHENTICATION_REQUIRED',
1483 'REQUEST_TIMEOUT',
1484 'CONFLICT',
1485 'GONE',
1486 'LENGTH_REQUIRED',
1487 'PRECONDITION_FAILED',
1488 'REQUEST_ENTITY_TOO_LARGE',
1489 'REQUEST_URI_TOO_LONG',
1490 'UNSUPPORTED_MEDIA_TYPE',
1491 'REQUESTED_RANGE_NOT_SATISFIABLE',
1492 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001493 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001494 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001495 'UNPROCESSABLE_ENTITY',
1496 'LOCKED',
1497 'FAILED_DEPENDENCY',
1498 'UPGRADE_REQUIRED',
1499 'PRECONDITION_REQUIRED',
1500 'TOO_MANY_REQUESTS',
1501 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001502 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001503 'INTERNAL_SERVER_ERROR',
1504 'NOT_IMPLEMENTED',
1505 'BAD_GATEWAY',
1506 'SERVICE_UNAVAILABLE',
1507 'GATEWAY_TIMEOUT',
1508 'HTTP_VERSION_NOT_SUPPORTED',
1509 'INSUFFICIENT_STORAGE',
1510 'NOT_EXTENDED',
1511 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001512 'EARLY_HINTS',
1513 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001514 ]
1515 for const in expected:
1516 with self.subTest(constant=const):
1517 self.assertTrue(hasattr(client, const))
1518
Gregory P. Smithb4066372010-01-03 03:28:29 +00001519
1520class SourceAddressTest(TestCase):
1521 def setUp(self):
1522 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001523 self.port = socket_helper.bind_port(self.serv)
1524 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001525 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001526 self.conn = None
1527
1528 def tearDown(self):
1529 if self.conn:
1530 self.conn.close()
1531 self.conn = None
1532 self.serv.close()
1533 self.serv = None
1534
1535 def testHTTPConnectionSourceAddress(self):
1536 self.conn = client.HTTPConnection(HOST, self.port,
1537 source_address=('', self.source_port))
1538 self.conn.connect()
1539 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1540
1541 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1542 'http.client.HTTPSConnection not defined')
1543 def testHTTPSConnectionSourceAddress(self):
1544 self.conn = client.HTTPSConnection(HOST, self.port,
1545 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001546 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001547 # this code doesn't deal with setting up an active running SSL server
1548 # for an ssl_wrapped connect() to actually return from.
1549
1550
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001552 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001553
1554 def setUp(self):
1555 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001556 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001557 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001558
1559 def tearDown(self):
1560 self.serv.close()
1561 self.serv = None
1562
1563 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001564 # This will prove that the timeout gets through HTTPConnection
1565 # and into the socket.
1566
Georg Brandlf78e02b2008-06-10 17:40:04 +00001567 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001568 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001569 socket.setdefaulttimeout(30)
1570 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001571 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001572 httpConn.connect()
1573 finally:
1574 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001575 self.assertEqual(httpConn.sock.gettimeout(), 30)
1576 httpConn.close()
1577
Georg Brandlf78e02b2008-06-10 17:40:04 +00001578 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001579 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580 socket.setdefaulttimeout(30)
1581 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001582 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001583 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001584 httpConn.connect()
1585 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001586 socket.setdefaulttimeout(None)
1587 self.assertEqual(httpConn.sock.gettimeout(), None)
1588 httpConn.close()
1589
1590 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001591 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001592 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001593 self.assertEqual(httpConn.sock.gettimeout(), 30)
1594 httpConn.close()
1595
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001596
R David Murraycae7bdb2015-04-05 19:26:29 -04001597class PersistenceTest(TestCase):
1598
1599 def test_reuse_reconnect(self):
1600 # Should reuse or reconnect depending on header from server
1601 tests = (
1602 ('1.0', '', False),
1603 ('1.0', 'Connection: keep-alive\r\n', True),
1604 ('1.1', '', True),
1605 ('1.1', 'Connection: close\r\n', False),
1606 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1607 ('1.1', 'Connection: cloSE\r\n', False),
1608 )
1609 for version, header, reuse in tests:
1610 with self.subTest(version=version, header=header):
1611 msg = (
1612 'HTTP/{} 200 OK\r\n'
1613 '{}'
1614 'Content-Length: 12\r\n'
1615 '\r\n'
1616 'Dummy body\r\n'
1617 ).format(version, header)
1618 conn = FakeSocketHTTPConnection(msg)
1619 self.assertIsNone(conn.sock)
1620 conn.request('GET', '/open-connection')
1621 with conn.getresponse() as response:
1622 self.assertEqual(conn.sock is None, not reuse)
1623 response.read()
1624 self.assertEqual(conn.sock is None, not reuse)
1625 self.assertEqual(conn.connections, 1)
1626 conn.request('GET', '/subsequent-request')
1627 self.assertEqual(conn.connections, 1 if reuse else 2)
1628
1629 def test_disconnected(self):
1630
1631 def make_reset_reader(text):
1632 """Return BufferedReader that raises ECONNRESET at EOF"""
1633 stream = io.BytesIO(text)
1634 def readinto(buffer):
1635 size = io.BytesIO.readinto(stream, buffer)
1636 if size == 0:
1637 raise ConnectionResetError()
1638 return size
1639 stream.readinto = readinto
1640 return io.BufferedReader(stream)
1641
1642 tests = (
1643 (io.BytesIO, client.RemoteDisconnected),
1644 (make_reset_reader, ConnectionResetError),
1645 )
1646 for stream_factory, exception in tests:
1647 with self.subTest(exception=exception):
1648 conn = FakeSocketHTTPConnection(b'', stream_factory)
1649 conn.request('GET', '/eof-response')
1650 self.assertRaises(exception, conn.getresponse)
1651 self.assertIsNone(conn.sock)
1652 # HTTPConnection.connect() should be automatically invoked
1653 conn.request('GET', '/reconnect')
1654 self.assertEqual(conn.connections, 2)
1655
1656 def test_100_close(self):
1657 conn = FakeSocketHTTPConnection(
1658 b'HTTP/1.1 100 Continue\r\n'
1659 b'\r\n'
1660 # Missing final response
1661 )
1662 conn.request('GET', '/', headers={'Expect': '100-continue'})
1663 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1664 self.assertIsNone(conn.sock)
1665 conn.request('GET', '/reconnect')
1666 self.assertEqual(conn.connections, 2)
1667
1668
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001669class HTTPSTest(TestCase):
1670
1671 def setUp(self):
1672 if not hasattr(client, 'HTTPSConnection'):
1673 self.skipTest('ssl support required')
1674
1675 def make_server(self, certfile):
1676 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001677 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001678
1679 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001680 # simple test to check it's storing the timeout
1681 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1682 self.assertEqual(h.timeout, 30)
1683
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001684 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001685 # Default settings: requires a valid cert from a trusted CA
1686 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001687 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001688 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001689 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1690 with self.assertRaises(ssl.SSLError) as exc_info:
1691 h.request('GET', '/')
1692 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1693
1694 def test_networked_noverification(self):
1695 # Switch off cert verification
1696 import ssl
1697 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001698 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001699 context = ssl._create_unverified_context()
1700 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1701 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001702 h.request('GET', '/')
1703 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001704 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001705 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001706 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001707
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001708 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001709 def test_networked_trusted_by_default_cert(self):
1710 # Default settings: requires a valid cert from a trusted CA
1711 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001712 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001713 h = client.HTTPSConnection('www.python.org', 443)
1714 h.request('GET', '/')
1715 resp = h.getresponse()
1716 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001717 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001718 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001719 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001720
1721 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001722 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001723 import ssl
1724 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001725 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001726 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001727 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1728 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1729 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001730 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001731 try:
1732 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1733 context=context)
1734 h.request('GET', '/')
1735 resp = h.getresponse()
1736 except ssl.SSLError as ssl_err:
1737 ssl_err_str = str(ssl_err)
1738 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1739 # modern Linux distros (Debian Buster, etc) default OpenSSL
1740 # configurations it'll fail saying "key too weak" until we
1741 # address https://bugs.python.org/issue36816 to use a proper
1742 # key size on self-signed.pythontest.net.
1743 if re.search(r'(?i)key.too.weak', ssl_err_str):
1744 raise unittest.SkipTest(
1745 f'Got {ssl_err_str} trying to connect '
1746 f'to {selfsigned_pythontestdotnet}. '
1747 'See https://bugs.python.org/issue36816.')
1748 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001749 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001750 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001751 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001752 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001753
1754 def test_networked_bad_cert(self):
1755 # We feed a "CA" cert that is unrelated to the server's cert
1756 import ssl
1757 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001758 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001759 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001760 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001761 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1762 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001763 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001764 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1765
1766 def test_local_unknown_cert(self):
1767 # The custom cert isn't known to the default trust bundle
1768 import ssl
1769 server = self.make_server(CERT_localhost)
1770 h = client.HTTPSConnection('localhost', server.port)
1771 with self.assertRaises(ssl.SSLError) as exc_info:
1772 h.request('GET', '/')
1773 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001774
1775 def test_local_good_hostname(self):
1776 # The (valid) cert validates the HTTP hostname
1777 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001778 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001779 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001780 context.load_verify_locations(CERT_localhost)
1781 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001782 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001783 h.request('GET', '/nonexistent')
1784 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001785 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001786 self.assertEqual(resp.status, 404)
1787
1788 def test_local_bad_hostname(self):
1789 # The (valid) cert doesn't validate the HTTP hostname
1790 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001791 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001792 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001793 context.load_verify_locations(CERT_fakehostname)
1794 h = client.HTTPSConnection('localhost', server.port, context=context)
1795 with self.assertRaises(ssl.CertificateError):
1796 h.request('GET', '/')
1797 # Same with explicit check_hostname=True
Hai Shi883bc632020-07-06 17:12:49 +08001798 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001799 h = client.HTTPSConnection('localhost', server.port,
1800 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001801 with self.assertRaises(ssl.CertificateError):
1802 h.request('GET', '/')
1803 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001804 context.check_hostname = False
Hai Shi883bc632020-07-06 17:12:49 +08001805 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001806 h = client.HTTPSConnection('localhost', server.port,
1807 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001808 h.request('GET', '/nonexistent')
1809 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001810 resp.close()
1811 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001812 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001813 # The context's check_hostname setting is used if one isn't passed to
1814 # HTTPSConnection.
1815 context.check_hostname = False
1816 h = client.HTTPSConnection('localhost', server.port, context=context)
1817 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001818 resp = h.getresponse()
1819 self.assertEqual(resp.status, 404)
1820 resp.close()
1821 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001822 # Passing check_hostname to HTTPSConnection should override the
1823 # context's setting.
Hai Shi883bc632020-07-06 17:12:49 +08001824 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001825 h = client.HTTPSConnection('localhost', server.port,
1826 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001827 with self.assertRaises(ssl.CertificateError):
1828 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001829
Petri Lehtinene119c402011-10-26 21:29:15 +03001830 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1831 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001832 def test_host_port(self):
1833 # Check invalid host_port
1834
1835 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1836 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1837
1838 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1839 "fe80::207:e9ff:fe9b", 8000),
1840 ("www.python.org:443", "www.python.org", 443),
1841 ("www.python.org:", "www.python.org", 443),
1842 ("www.python.org", "www.python.org", 443),
1843 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1844 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1845 443)):
1846 c = client.HTTPSConnection(hp)
1847 self.assertEqual(h, c.host)
1848 self.assertEqual(p, c.port)
1849
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001850 def test_tls13_pha(self):
1851 import ssl
1852 if not ssl.HAS_TLSv1_3:
1853 self.skipTest('TLS 1.3 support required')
1854 # just check status of PHA flag
1855 h = client.HTTPSConnection('localhost', 443)
1856 self.assertTrue(h._context.post_handshake_auth)
1857
1858 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1859 self.assertFalse(context.post_handshake_auth)
1860 h = client.HTTPSConnection('localhost', 443, context=context)
1861 self.assertIs(h._context, context)
1862 self.assertFalse(h._context.post_handshake_auth)
1863
Pablo Galindoaa542c22019-08-08 23:25:46 +01001864 with warnings.catch_warnings():
1865 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1866 DeprecationWarning)
1867 h = client.HTTPSConnection('localhost', 443, context=context,
1868 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001869 self.assertTrue(h._context.post_handshake_auth)
1870
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001871
Jeremy Hylton236654b2009-03-27 20:24:34 +00001872class RequestBodyTest(TestCase):
1873 """Test cases where a request includes a message body."""
1874
1875 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001876 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001877 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001878 self.conn.sock = self.sock
1879
1880 def get_headers_and_fp(self):
1881 f = io.BytesIO(self.sock.data)
1882 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001883 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001884 return message, f
1885
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001886 def test_list_body(self):
1887 # Note that no content-length is automatically calculated for
1888 # an iterable. The request will fall back to send chunked
1889 # transfer encoding.
1890 cases = (
1891 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1892 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1893 )
1894 for body, expected in cases:
1895 with self.subTest(body):
1896 self.conn = client.HTTPConnection('example.com')
1897 self.conn.sock = self.sock = FakeSocket('')
1898
1899 self.conn.request('PUT', '/url', body)
1900 msg, f = self.get_headers_and_fp()
1901 self.assertNotIn('Content-Type', msg)
1902 self.assertNotIn('Content-Length', msg)
1903 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1904 self.assertEqual(expected, f.read())
1905
Jeremy Hylton236654b2009-03-27 20:24:34 +00001906 def test_manual_content_length(self):
1907 # Set an incorrect content-length so that we can verify that
1908 # it will not be over-ridden by the library.
1909 self.conn.request("PUT", "/url", "body",
1910 {"Content-Length": "42"})
1911 message, f = self.get_headers_and_fp()
1912 self.assertEqual("42", message.get("content-length"))
1913 self.assertEqual(4, len(f.read()))
1914
1915 def test_ascii_body(self):
1916 self.conn.request("PUT", "/url", "body")
1917 message, f = self.get_headers_and_fp()
1918 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001919 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001920 self.assertEqual("4", message.get("content-length"))
1921 self.assertEqual(b'body', f.read())
1922
1923 def test_latin1_body(self):
1924 self.conn.request("PUT", "/url", "body\xc1")
1925 message, f = self.get_headers_and_fp()
1926 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001927 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001928 self.assertEqual("5", message.get("content-length"))
1929 self.assertEqual(b'body\xc1', f.read())
1930
1931 def test_bytes_body(self):
1932 self.conn.request("PUT", "/url", b"body\xc1")
1933 message, f = self.get_headers_and_fp()
1934 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001935 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001936 self.assertEqual("5", message.get("content-length"))
1937 self.assertEqual(b'body\xc1', f.read())
1938
Martin Panteref91bb22016-08-27 01:39:26 +00001939 def test_text_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001940 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1941 with open(os_helper.TESTFN, "w") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001942 f.write("body")
Hai Shi883bc632020-07-06 17:12:49 +08001943 with open(os_helper.TESTFN) as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001944 self.conn.request("PUT", "/url", f)
1945 message, f = self.get_headers_and_fp()
1946 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001947 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001948 # No content-length will be determined for files; the body
1949 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001950 self.assertIsNone(message.get("content-length"))
1951 self.assertEqual("chunked", message.get("transfer-encoding"))
1952 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001953
1954 def test_binary_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001955 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1956 with open(os_helper.TESTFN, "wb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001957 f.write(b"body\xc1")
Hai Shi883bc632020-07-06 17:12:49 +08001958 with open(os_helper.TESTFN, "rb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001959 self.conn.request("PUT", "/url", f)
1960 message, f = self.get_headers_and_fp()
1961 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001962 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001963 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1964 self.assertNotIn("Content-Length", message)
1965 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001966
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001967
1968class HTTPResponseTest(TestCase):
1969
1970 def setUp(self):
1971 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1972 second-value\r\n\r\nText"
1973 sock = FakeSocket(body)
1974 self.resp = client.HTTPResponse(sock)
1975 self.resp.begin()
1976
1977 def test_getting_header(self):
1978 header = self.resp.getheader('My-Header')
1979 self.assertEqual(header, 'first-value, second-value')
1980
1981 header = self.resp.getheader('My-Header', 'some default')
1982 self.assertEqual(header, 'first-value, second-value')
1983
1984 def test_getting_nonexistent_header_with_string_default(self):
1985 header = self.resp.getheader('No-Such-Header', 'default-value')
1986 self.assertEqual(header, 'default-value')
1987
1988 def test_getting_nonexistent_header_with_iterable_default(self):
1989 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1990 self.assertEqual(header, 'default, values')
1991
1992 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1993 self.assertEqual(header, 'default, values')
1994
1995 def test_getting_nonexistent_header_without_default(self):
1996 header = self.resp.getheader('No-Such-Header')
1997 self.assertEqual(header, None)
1998
1999 def test_getting_header_defaultint(self):
2000 header = self.resp.getheader('No-Such-Header',default=42)
2001 self.assertEqual(header, 42)
2002
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002003class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002004 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002005 response_text = (
2006 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
2007 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
2008 'Content-Length: 42\r\n\r\n'
2009 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002010 self.host = 'proxy.com'
2011 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02002012 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002013
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002014 def tearDown(self):
2015 self.conn.close()
2016
Berker Peksagab53ab02015-02-03 12:22:11 +02002017 def _create_connection(self, response_text):
2018 def create_connection(address, timeout=None, source_address=None):
2019 return FakeSocket(response_text, host=address[0], port=address[1])
2020 return create_connection
2021
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002022 def test_set_tunnel_host_port_headers(self):
2023 tunnel_host = 'destination.com'
2024 tunnel_port = 8888
2025 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2026 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2027 headers=tunnel_headers)
2028 self.conn.request('HEAD', '/', '')
2029 self.assertEqual(self.conn.sock.host, self.host)
2030 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2031 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2032 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2033 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2034
2035 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002036 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002037 self.conn.connect()
2038 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002039 'destination.com')
2040
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002041 def test_connect_with_tunnel(self):
2042 self.conn.set_tunnel('destination.com')
2043 self.conn.request('HEAD', '/', '')
2044 self.assertEqual(self.conn.sock.host, self.host)
2045 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2046 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002047 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002048 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2049 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002050
2051 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002052 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002053
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002054 def test_connect_put_request(self):
2055 self.conn.set_tunnel('destination.com')
2056 self.conn.request('PUT', '/', '')
2057 self.assertEqual(self.conn.sock.host, self.host)
2058 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2059 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2060 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2061
Berker Peksagab53ab02015-02-03 12:22:11 +02002062 def test_tunnel_debuglog(self):
2063 expected_header = 'X-Dummy: 1'
2064 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2065
2066 self.conn.set_debuglevel(1)
2067 self.conn._create_connection = self._create_connection(response_text)
2068 self.conn.set_tunnel('destination.com')
2069
2070 with support.captured_stdout() as output:
2071 self.conn.request('PUT', '/', '')
2072 lines = output.getvalue().splitlines()
2073 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002074
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002075
Thomas Wouters89f507f2006-12-13 04:49:30 +00002076if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002077 unittest.main(verbosity=2)