blob: a3f268be97921c38735bea6b4a57db97ef1a9026 [file] [log] [blame]
Jeremy Hylton636950f2009-03-28 04:34:21 +00001import errno
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002from http import client
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):
522 def test_status_lines(self):
523 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000524
Thomas Wouters89f507f2006-12-13 04:49:30 +0000525 body = "HTTP/1.1 200 Ok\r\n\r\nText"
526 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000527 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000528 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200529 self.assertEqual(resp.read(0), b'') # Issue #20007
530 self.assertFalse(resp.isclosed())
531 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000532 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000533 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200534 self.assertFalse(resp.closed)
535 resp.close()
536 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000537
Thomas Wouters89f507f2006-12-13 04:49:30 +0000538 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
539 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000540 resp = client.HTTPResponse(sock)
541 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000542
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000543 def test_bad_status_repr(self):
544 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200545 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000546
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000547 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000548 # if we have Content-Length, HTTPResponse knows when to close itself,
549 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000550 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
551 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000552 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000553 resp.begin()
554 self.assertEqual(resp.read(2), b'Te')
555 self.assertFalse(resp.isclosed())
556 self.assertEqual(resp.read(2), b'xt')
557 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200558 self.assertFalse(resp.closed)
559 resp.close()
560 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000561
Martin Panterce911c32016-03-17 06:42:48 +0000562 def test_mixed_reads(self):
563 # readline() should update the remaining length, so that read() knows
564 # how much data is left and does not raise IncompleteRead
565 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
566 sock = FakeSocket(body)
567 resp = client.HTTPResponse(sock)
568 resp.begin()
569 self.assertEqual(resp.readline(), b'Text\r\n')
570 self.assertFalse(resp.isclosed())
571 self.assertEqual(resp.read(), b'Another')
572 self.assertTrue(resp.isclosed())
573 self.assertFalse(resp.closed)
574 resp.close()
575 self.assertTrue(resp.closed)
576
Antoine Pitrou38d96432011-12-06 22:33:57 +0100577 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000578 # if we have Content-Length, HTTPResponse knows when to close itself,
579 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100580 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
581 sock = FakeSocket(body)
582 resp = client.HTTPResponse(sock)
583 resp.begin()
584 b = bytearray(2)
585 n = resp.readinto(b)
586 self.assertEqual(n, 2)
587 self.assertEqual(bytes(b), b'Te')
588 self.assertFalse(resp.isclosed())
589 n = resp.readinto(b)
590 self.assertEqual(n, 2)
591 self.assertEqual(bytes(b), b'xt')
592 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200593 self.assertFalse(resp.closed)
594 resp.close()
595 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100596
Bruce Merry152f0b82020-06-25 08:30:21 +0200597 def test_partial_reads_past_end(self):
598 # if we have Content-Length, clip reads to the end
599 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
600 sock = FakeSocket(body)
601 resp = client.HTTPResponse(sock)
602 resp.begin()
603 self.assertEqual(resp.read(10), b'Text')
604 self.assertTrue(resp.isclosed())
605 self.assertFalse(resp.closed)
606 resp.close()
607 self.assertTrue(resp.closed)
608
609 def test_partial_readintos_past_end(self):
610 # if we have Content-Length, clip readintos to the end
611 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
612 sock = FakeSocket(body)
613 resp = client.HTTPResponse(sock)
614 resp.begin()
615 b = bytearray(10)
616 n = resp.readinto(b)
617 self.assertEqual(n, 4)
618 self.assertEqual(bytes(b)[:4], b'Text')
619 self.assertTrue(resp.isclosed())
620 self.assertFalse(resp.closed)
621 resp.close()
622 self.assertTrue(resp.closed)
623
Antoine Pitrou084daa22012-12-15 19:11:54 +0100624 def test_partial_reads_no_content_length(self):
625 # when no length is present, the socket should be gracefully closed when
626 # all data was read
627 body = "HTTP/1.1 200 Ok\r\n\r\nText"
628 sock = FakeSocket(body)
629 resp = client.HTTPResponse(sock)
630 resp.begin()
631 self.assertEqual(resp.read(2), b'Te')
632 self.assertFalse(resp.isclosed())
633 self.assertEqual(resp.read(2), b'xt')
634 self.assertEqual(resp.read(1), b'')
635 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200636 self.assertFalse(resp.closed)
637 resp.close()
638 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100639
Antoine Pitroud20e7742012-12-15 19:22:30 +0100640 def test_partial_readintos_no_content_length(self):
641 # when no length is present, the socket should be gracefully closed when
642 # all data was read
643 body = "HTTP/1.1 200 Ok\r\n\r\nText"
644 sock = FakeSocket(body)
645 resp = client.HTTPResponse(sock)
646 resp.begin()
647 b = bytearray(2)
648 n = resp.readinto(b)
649 self.assertEqual(n, 2)
650 self.assertEqual(bytes(b), b'Te')
651 self.assertFalse(resp.isclosed())
652 n = resp.readinto(b)
653 self.assertEqual(n, 2)
654 self.assertEqual(bytes(b), b'xt')
655 n = resp.readinto(b)
656 self.assertEqual(n, 0)
657 self.assertTrue(resp.isclosed())
658
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100659 def test_partial_reads_incomplete_body(self):
660 # if the server shuts down the connection before the whole
661 # content-length is delivered, the socket is gracefully closed
662 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
663 sock = FakeSocket(body)
664 resp = client.HTTPResponse(sock)
665 resp.begin()
666 self.assertEqual(resp.read(2), b'Te')
667 self.assertFalse(resp.isclosed())
668 self.assertEqual(resp.read(2), b'xt')
669 self.assertEqual(resp.read(1), b'')
670 self.assertTrue(resp.isclosed())
671
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100672 def test_partial_readintos_incomplete_body(self):
673 # if the server shuts down the connection before the whole
674 # content-length is delivered, the socket is gracefully closed
675 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
676 sock = FakeSocket(body)
677 resp = client.HTTPResponse(sock)
678 resp.begin()
679 b = bytearray(2)
680 n = resp.readinto(b)
681 self.assertEqual(n, 2)
682 self.assertEqual(bytes(b), b'Te')
683 self.assertFalse(resp.isclosed())
684 n = resp.readinto(b)
685 self.assertEqual(n, 2)
686 self.assertEqual(bytes(b), b'xt')
687 n = resp.readinto(b)
688 self.assertEqual(n, 0)
689 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200690 self.assertFalse(resp.closed)
691 resp.close()
692 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100693
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 def test_host_port(self):
695 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000696
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200697 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000698 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000699
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000700 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
701 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000702 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200703 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000704 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200705 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
706 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000707 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000708 self.assertEqual(h, c.host)
709 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000710
Thomas Wouters89f507f2006-12-13 04:49:30 +0000711 def test_response_headers(self):
712 # test response with multiple message headers with the same field name.
713 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000714 'Set-Cookie: Customer="WILE_E_COYOTE"; '
715 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000716 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
717 ' Path="/acme"\r\n'
718 '\r\n'
719 'No body\r\n')
720 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
721 ', '
722 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
723 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000724 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000725 r.begin()
726 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000727 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000728
Thomas Wouters89f507f2006-12-13 04:49:30 +0000729 def test_read_head(self):
730 # Test that the library doesn't attempt to read any data
731 # from a HEAD request. (Tickles SF bug #622042.)
732 sock = FakeSocket(
733 'HTTP/1.1 200 OK\r\n'
734 'Content-Length: 14432\r\n'
735 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300736 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000737 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000738 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000739 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000741
Antoine Pitrou38d96432011-12-06 22:33:57 +0100742 def test_readinto_head(self):
743 # Test that the library doesn't attempt to read any data
744 # from a HEAD request. (Tickles SF bug #622042.)
745 sock = FakeSocket(
746 'HTTP/1.1 200 OK\r\n'
747 'Content-Length: 14432\r\n'
748 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300749 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100750 resp = client.HTTPResponse(sock, method="HEAD")
751 resp.begin()
752 b = bytearray(5)
753 if resp.readinto(b) != 0:
754 self.fail("Did not expect response from HEAD request")
755 self.assertEqual(bytes(b), b'\x00'*5)
756
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100757 def test_too_many_headers(self):
758 headers = '\r\n'.join('Header%d: foo' % i
759 for i in range(client._MAXHEADERS + 1)) + '\r\n'
760 text = ('HTTP/1.1 200 OK\r\n' + headers)
761 s = FakeSocket(text)
762 r = client.HTTPResponse(s)
763 self.assertRaisesRegex(client.HTTPException,
764 r"got more than \d+ headers", r.begin)
765
Thomas Wouters89f507f2006-12-13 04:49:30 +0000766 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000767 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000768 b'Accept-Encoding: identity\r\n'
769 b'Transfer-Encoding: chunked\r\n'
770 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000771
Brett Cannon77b7de62010-10-29 23:31:11 +0000772 with open(__file__, 'rb') as body:
773 conn = client.HTTPConnection('example.com')
774 sock = FakeSocket(body)
775 conn.sock = sock
776 conn.request('GET', '/foo', body)
777 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
778 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000779
Antoine Pitrouead1d622009-09-29 18:44:53 +0000780 def test_send(self):
781 expected = b'this is a test this is only a test'
782 conn = client.HTTPConnection('example.com')
783 sock = FakeSocket(None)
784 conn.sock = sock
785 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000786 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000787 sock.data = b''
788 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000789 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000790 sock.data = b''
791 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000792 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000793
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300794 def test_send_updating_file(self):
795 def data():
796 yield 'data'
797 yield None
798 yield 'data_two'
799
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000800 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300801 mode = 'r'
802 d = data()
803 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000804 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300805
806 expected = b'data'
807
808 conn = client.HTTPConnection('example.com')
809 sock = FakeSocket("")
810 conn.sock = sock
811 conn.send(UpdatingFile())
812 self.assertEqual(sock.data, expected)
813
814
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000815 def test_send_iter(self):
816 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
817 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
818 b'\r\nonetwothree'
819
820 def body():
821 yield b"one"
822 yield b"two"
823 yield b"three"
824
825 conn = client.HTTPConnection('example.com')
826 sock = FakeSocket("")
827 conn.sock = sock
828 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000829 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000830
Nir Sofferad455cd2017-11-06 23:16:37 +0200831 def test_blocksize_request(self):
832 """Check that request() respects the configured block size."""
833 blocksize = 8 # For easy debugging.
834 conn = client.HTTPConnection('example.com', blocksize=blocksize)
835 sock = FakeSocket(None)
836 conn.sock = sock
837 expected = b"a" * blocksize + b"b"
838 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
839 self.assertEqual(sock.sendall_calls, 3)
840 body = sock.data.split(b"\r\n\r\n", 1)[1]
841 self.assertEqual(body, expected)
842
843 def test_blocksize_send(self):
844 """Check that send() respects the configured block size."""
845 blocksize = 8 # For easy debugging.
846 conn = client.HTTPConnection('example.com', blocksize=blocksize)
847 sock = FakeSocket(None)
848 conn.sock = sock
849 expected = b"a" * blocksize + b"b"
850 conn.send(io.BytesIO(expected))
851 self.assertEqual(sock.sendall_calls, 2)
852 self.assertEqual(sock.data, expected)
853
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800854 def test_send_type_error(self):
855 # See: Issue #12676
856 conn = client.HTTPConnection('example.com')
857 conn.sock = FakeSocket('')
858 with self.assertRaises(TypeError):
859 conn.request('POST', 'test', conn)
860
Christian Heimesa612dc02008-02-24 13:08:18 +0000861 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000862 expected = chunked_expected
863 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000864 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000865 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100866 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000867 resp.close()
868
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100869 # Various read sizes
870 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000871 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100872 resp = client.HTTPResponse(sock, method="GET")
873 resp.begin()
874 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
875 resp.close()
876
Christian Heimesa612dc02008-02-24 13:08:18 +0000877 for x in ('', 'foo\r\n'):
878 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000879 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000880 resp.begin()
881 try:
882 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000883 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100884 self.assertEqual(i.partial, expected)
885 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
886 self.assertEqual(repr(i), expected_message)
887 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000888 else:
889 self.fail('IncompleteRead expected')
890 finally:
891 resp.close()
892
Antoine Pitrou38d96432011-12-06 22:33:57 +0100893 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000894
895 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100896 nexpected = len(expected)
897 b = bytearray(128)
898
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000899 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100900 resp = client.HTTPResponse(sock, method="GET")
901 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100902 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100903 self.assertEqual(b[:nexpected], expected)
904 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100905 resp.close()
906
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100907 # Various read sizes
908 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000909 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100910 resp = client.HTTPResponse(sock, method="GET")
911 resp.begin()
912 m = memoryview(b)
913 i = resp.readinto(m[0:n])
914 i += resp.readinto(m[i:n + i])
915 i += resp.readinto(m[i:])
916 self.assertEqual(b[:nexpected], expected)
917 self.assertEqual(i, nexpected)
918 resp.close()
919
Antoine Pitrou38d96432011-12-06 22:33:57 +0100920 for x in ('', 'foo\r\n'):
921 sock = FakeSocket(chunked_start + x)
922 resp = client.HTTPResponse(sock, method="GET")
923 resp.begin()
924 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100925 n = resp.readinto(b)
926 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100927 self.assertEqual(i.partial, expected)
928 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
929 self.assertEqual(repr(i), expected_message)
930 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100931 else:
932 self.fail('IncompleteRead expected')
933 finally:
934 resp.close()
935
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000936 def test_chunked_head(self):
937 chunked_start = (
938 'HTTP/1.1 200 OK\r\n'
939 'Transfer-Encoding: chunked\r\n\r\n'
940 'a\r\n'
941 'hello world\r\n'
942 '1\r\n'
943 'd\r\n'
944 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000945 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000946 resp = client.HTTPResponse(sock, method="HEAD")
947 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000948 self.assertEqual(resp.read(), b'')
949 self.assertEqual(resp.status, 200)
950 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000951 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200952 self.assertFalse(resp.closed)
953 resp.close()
954 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000955
Antoine Pitrou38d96432011-12-06 22:33:57 +0100956 def test_readinto_chunked_head(self):
957 chunked_start = (
958 'HTTP/1.1 200 OK\r\n'
959 'Transfer-Encoding: chunked\r\n\r\n'
960 'a\r\n'
961 'hello world\r\n'
962 '1\r\n'
963 'd\r\n'
964 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000965 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100966 resp = client.HTTPResponse(sock, method="HEAD")
967 resp.begin()
968 b = bytearray(5)
969 n = resp.readinto(b)
970 self.assertEqual(n, 0)
971 self.assertEqual(bytes(b), b'\x00'*5)
972 self.assertEqual(resp.status, 200)
973 self.assertEqual(resp.reason, 'OK')
974 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200975 self.assertFalse(resp.closed)
976 resp.close()
977 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100978
Christian Heimesa612dc02008-02-24 13:08:18 +0000979 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000980 sock = FakeSocket(
981 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000982 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000983 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000984 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100985 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000986
Benjamin Peterson6accb982009-03-02 22:50:25 +0000987 def test_incomplete_read(self):
988 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000989 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000990 resp.begin()
991 try:
992 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000993 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000994 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000995 self.assertEqual(repr(i),
996 "IncompleteRead(7 bytes read, 3 more expected)")
997 self.assertEqual(str(i),
998 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100999 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +00001000 else:
1001 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +00001002
Jeremy Hylton636950f2009-03-28 04:34:21 +00001003 def test_epipe(self):
1004 sock = EPipeSocket(
1005 "HTTP/1.0 401 Authorization Required\r\n"
1006 "Content-type: text/html\r\n"
1007 "WWW-Authenticate: Basic realm=\"example\"\r\n",
1008 b"Content-Length")
1009 conn = client.HTTPConnection("example.com")
1010 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +02001011 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +00001012 lambda: conn.request("PUT", "/url", "body"))
1013 resp = conn.getresponse()
1014 self.assertEqual(401, resp.status)
1015 self.assertEqual("Basic realm=\"example\"",
1016 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +00001017
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001018 # Test lines overflowing the max line size (_MAXLINE in http.client)
1019
1020 def test_overflowing_status_line(self):
1021 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
1022 resp = client.HTTPResponse(FakeSocket(body))
1023 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
1024
1025 def test_overflowing_header_line(self):
1026 body = (
1027 'HTTP/1.1 200 OK\r\n'
1028 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1029 )
1030 resp = client.HTTPResponse(FakeSocket(body))
1031 self.assertRaises(client.LineTooLong, resp.begin)
1032
1033 def test_overflowing_chunked_line(self):
1034 body = (
1035 'HTTP/1.1 200 OK\r\n'
1036 'Transfer-Encoding: chunked\r\n\r\n'
1037 + '0' * 65536 + 'a\r\n'
1038 'hello world\r\n'
1039 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001040 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001041 )
1042 resp = client.HTTPResponse(FakeSocket(body))
1043 resp.begin()
1044 self.assertRaises(client.LineTooLong, resp.read)
1045
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001046 def test_early_eof(self):
1047 # Test httpresponse with no \r\n termination,
1048 body = "HTTP/1.1 200 Ok"
1049 sock = FakeSocket(body)
1050 resp = client.HTTPResponse(sock)
1051 resp.begin()
1052 self.assertEqual(resp.read(), b'')
1053 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001054 self.assertFalse(resp.closed)
1055 resp.close()
1056 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001057
Serhiy Storchakab491e052014-12-01 13:07:45 +02001058 def test_error_leak(self):
1059 # Test that the socket is not leaked if getresponse() fails
1060 conn = client.HTTPConnection('example.com')
1061 response = None
1062 class Response(client.HTTPResponse):
1063 def __init__(self, *pos, **kw):
1064 nonlocal response
1065 response = self # Avoid garbage collector closing the socket
1066 client.HTTPResponse.__init__(self, *pos, **kw)
1067 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001068 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001069 conn.request('GET', '/')
1070 self.assertRaises(client.BadStatusLine, conn.getresponse)
1071 self.assertTrue(response.closed)
1072 self.assertTrue(conn.sock.file_closed)
1073
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001074 def test_chunked_extension(self):
1075 extra = '3;foo=bar\r\n' + 'abc\r\n'
1076 expected = chunked_expected + b'abc'
1077
1078 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1079 resp = client.HTTPResponse(sock, method="GET")
1080 resp.begin()
1081 self.assertEqual(resp.read(), expected)
1082 resp.close()
1083
1084 def test_chunked_missing_end(self):
1085 """some servers may serve up a short chunked encoding stream"""
1086 expected = chunked_expected
1087 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1088 resp = client.HTTPResponse(sock, method="GET")
1089 resp.begin()
1090 self.assertEqual(resp.read(), expected)
1091 resp.close()
1092
1093 def test_chunked_trailers(self):
1094 """See that trailers are read and ignored"""
1095 expected = chunked_expected
1096 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1097 resp = client.HTTPResponse(sock, method="GET")
1098 resp.begin()
1099 self.assertEqual(resp.read(), expected)
1100 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001101 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001102 resp.close()
1103
1104 def test_chunked_sync(self):
1105 """Check that we don't read past the end of the chunked-encoding stream"""
1106 expected = chunked_expected
1107 extradata = "extradata"
1108 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1109 resp = client.HTTPResponse(sock, method="GET")
1110 resp.begin()
1111 self.assertEqual(resp.read(), expected)
1112 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001113 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001114 resp.close()
1115
1116 def test_content_length_sync(self):
1117 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001118 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001119 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001120 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 +00001121 resp = client.HTTPResponse(sock, method="GET")
1122 resp.begin()
1123 self.assertEqual(resp.read(), expected)
1124 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001125 self.assertEqual(sock.file.read(), extradata) #we read to the end
1126 resp.close()
1127
1128 def test_readlines_content_length(self):
1129 extradata = b"extradata"
1130 expected = b"Hello123\r\n"
1131 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1132 resp = client.HTTPResponse(sock, method="GET")
1133 resp.begin()
1134 self.assertEqual(resp.readlines(2000), [expected])
1135 # the file should now have our extradata ready to be read
1136 self.assertEqual(sock.file.read(), extradata) #we read to the end
1137 resp.close()
1138
1139 def test_read1_content_length(self):
1140 extradata = b"extradata"
1141 expected = b"Hello123\r\n"
1142 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1143 resp = client.HTTPResponse(sock, method="GET")
1144 resp.begin()
1145 self.assertEqual(resp.read1(2000), expected)
1146 # the file should now have our extradata ready to be read
1147 self.assertEqual(sock.file.read(), extradata) #we read to the end
1148 resp.close()
1149
1150 def test_readline_bound_content_length(self):
1151 extradata = b"extradata"
1152 expected = b"Hello123\r\n"
1153 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1154 resp = client.HTTPResponse(sock, method="GET")
1155 resp.begin()
1156 self.assertEqual(resp.readline(10), expected)
1157 self.assertEqual(resp.readline(10), b"")
1158 # the file should now have our extradata ready to be read
1159 self.assertEqual(sock.file.read(), extradata) #we read to the end
1160 resp.close()
1161
1162 def test_read1_bound_content_length(self):
1163 extradata = b"extradata"
1164 expected = b"Hello123\r\n"
1165 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1166 resp = client.HTTPResponse(sock, method="GET")
1167 resp.begin()
1168 self.assertEqual(resp.read1(20), expected*2)
1169 self.assertEqual(resp.read(), expected)
1170 # the file should now have our extradata ready to be read
1171 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001172 resp.close()
1173
Martin Panterd979b2c2016-04-09 14:03:17 +00001174 def test_response_fileno(self):
1175 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001176 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001177 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001178
1179 result = None
1180 def run_server():
1181 [conn, address] = serv.accept()
1182 with conn, conn.makefile("rb") as reader:
1183 # Read the request header until a blank line
1184 while True:
1185 line = reader.readline()
1186 if not line.rstrip(b"\r\n"):
1187 break
1188 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1189 nonlocal result
1190 result = reader.read()
1191
1192 thread = threading.Thread(target=run_server)
1193 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001194 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001195 conn = client.HTTPConnection(*serv.getsockname())
1196 conn.request("CONNECT", "dummy:1234")
1197 response = conn.getresponse()
1198 try:
1199 self.assertEqual(response.status, client.OK)
1200 s = socket.socket(fileno=response.fileno())
1201 try:
1202 s.sendall(b"proxied data\n")
1203 finally:
1204 s.detach()
1205 finally:
1206 response.close()
1207 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001208 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001209 self.assertEqual(result, b"proxied data\n")
1210
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001211 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001212 """
1213 It should be possible to override the default validation
1214 behavior in putrequest (bpo-38216).
1215 """
1216 class UnsafeHTTPConnection(client.HTTPConnection):
1217 def _validate_path(self, url):
1218 pass
1219
1220 conn = UnsafeHTTPConnection('example.com')
1221 conn.sock = FakeSocket('')
1222 conn.putrequest('GET', '/\x00')
1223
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001224 def test_putrequest_override_host_validation(self):
1225 class UnsafeHTTPConnection(client.HTTPConnection):
1226 def _validate_host(self, url):
1227 pass
1228
1229 conn = UnsafeHTTPConnection('example.com\r\n')
1230 conn.sock = FakeSocket('')
1231 # set skip_host so a ValueError is not raised upon adding the
1232 # invalid URL as the value of the "Host:" header
1233 conn.putrequest('GET', '/', skip_host=1)
1234
Jason R. Coombs7774d782019-09-28 08:32:01 -04001235 def test_putrequest_override_encoding(self):
1236 """
1237 It should be possible to override the default encoding
1238 to transmit bytes in another encoding even if invalid
1239 (bpo-36274).
1240 """
1241 class UnsafeHTTPConnection(client.HTTPConnection):
1242 def _encode_request(self, str_url):
1243 return str_url.encode('utf-8')
1244
1245 conn = UnsafeHTTPConnection('example.com')
1246 conn.sock = FakeSocket('')
1247 conn.putrequest('GET', '/☃')
1248
1249
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001250class ExtendedReadTest(TestCase):
1251 """
1252 Test peek(), read1(), readline()
1253 """
1254 lines = (
1255 'HTTP/1.1 200 OK\r\n'
1256 '\r\n'
1257 'hello world!\n'
1258 'and now \n'
1259 'for something completely different\n'
1260 'foo'
1261 )
1262 lines_expected = lines[lines.find('hello'):].encode("ascii")
1263 lines_chunked = (
1264 'HTTP/1.1 200 OK\r\n'
1265 'Transfer-Encoding: chunked\r\n\r\n'
1266 'a\r\n'
1267 'hello worl\r\n'
1268 '3\r\n'
1269 'd!\n\r\n'
1270 '9\r\n'
1271 'and now \n\r\n'
1272 '23\r\n'
1273 'for something completely different\n\r\n'
1274 '3\r\n'
1275 'foo\r\n'
1276 '0\r\n' # terminating chunk
1277 '\r\n' # end of trailers
1278 )
1279
1280 def setUp(self):
1281 sock = FakeSocket(self.lines)
1282 resp = client.HTTPResponse(sock, method="GET")
1283 resp.begin()
1284 resp.fp = io.BufferedReader(resp.fp)
1285 self.resp = resp
1286
1287
1288
1289 def test_peek(self):
1290 resp = self.resp
1291 # patch up the buffered peek so that it returns not too much stuff
1292 oldpeek = resp.fp.peek
1293 def mypeek(n=-1):
1294 p = oldpeek(n)
1295 if n >= 0:
1296 return p[:n]
1297 return p[:10]
1298 resp.fp.peek = mypeek
1299
1300 all = []
1301 while True:
1302 # try a short peek
1303 p = resp.peek(3)
1304 if p:
1305 self.assertGreater(len(p), 0)
1306 # then unbounded peek
1307 p2 = resp.peek()
1308 self.assertGreaterEqual(len(p2), len(p))
1309 self.assertTrue(p2.startswith(p))
1310 next = resp.read(len(p2))
1311 self.assertEqual(next, p2)
1312 else:
1313 next = resp.read()
1314 self.assertFalse(next)
1315 all.append(next)
1316 if not next:
1317 break
1318 self.assertEqual(b"".join(all), self.lines_expected)
1319
1320 def test_readline(self):
1321 resp = self.resp
1322 self._verify_readline(self.resp.readline, self.lines_expected)
1323
1324 def _verify_readline(self, readline, expected):
1325 all = []
1326 while True:
1327 # short readlines
1328 line = readline(5)
1329 if line and line != b"foo":
1330 if len(line) < 5:
1331 self.assertTrue(line.endswith(b"\n"))
1332 all.append(line)
1333 if not line:
1334 break
1335 self.assertEqual(b"".join(all), expected)
1336
1337 def test_read1(self):
1338 resp = self.resp
1339 def r():
1340 res = resp.read1(4)
1341 self.assertLessEqual(len(res), 4)
1342 return res
1343 readliner = Readliner(r)
1344 self._verify_readline(readliner.readline, self.lines_expected)
1345
1346 def test_read1_unbounded(self):
1347 resp = self.resp
1348 all = []
1349 while True:
1350 data = resp.read1()
1351 if not data:
1352 break
1353 all.append(data)
1354 self.assertEqual(b"".join(all), self.lines_expected)
1355
1356 def test_read1_bounded(self):
1357 resp = self.resp
1358 all = []
1359 while True:
1360 data = resp.read1(10)
1361 if not data:
1362 break
1363 self.assertLessEqual(len(data), 10)
1364 all.append(data)
1365 self.assertEqual(b"".join(all), self.lines_expected)
1366
1367 def test_read1_0(self):
1368 self.assertEqual(self.resp.read1(0), b"")
1369
1370 def test_peek_0(self):
1371 p = self.resp.peek(0)
1372 self.assertLessEqual(0, len(p))
1373
Jason R. Coombs7774d782019-09-28 08:32:01 -04001374
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001375class ExtendedReadTestChunked(ExtendedReadTest):
1376 """
1377 Test peek(), read1(), readline() in chunked mode
1378 """
1379 lines = (
1380 'HTTP/1.1 200 OK\r\n'
1381 'Transfer-Encoding: chunked\r\n\r\n'
1382 'a\r\n'
1383 'hello worl\r\n'
1384 '3\r\n'
1385 'd!\n\r\n'
1386 '9\r\n'
1387 'and now \n\r\n'
1388 '23\r\n'
1389 'for something completely different\n\r\n'
1390 '3\r\n'
1391 'foo\r\n'
1392 '0\r\n' # terminating chunk
1393 '\r\n' # end of trailers
1394 )
1395
1396
1397class Readliner:
1398 """
1399 a simple readline class that uses an arbitrary read function and buffering
1400 """
1401 def __init__(self, readfunc):
1402 self.readfunc = readfunc
1403 self.remainder = b""
1404
1405 def readline(self, limit):
1406 data = []
1407 datalen = 0
1408 read = self.remainder
1409 try:
1410 while True:
1411 idx = read.find(b'\n')
1412 if idx != -1:
1413 break
1414 if datalen + len(read) >= limit:
1415 idx = limit - datalen - 1
1416 # read more data
1417 data.append(read)
1418 read = self.readfunc()
1419 if not read:
1420 idx = 0 #eof condition
1421 break
1422 idx += 1
1423 data.append(read[:idx])
1424 self.remainder = read[idx:]
1425 return b"".join(data)
1426 except:
1427 self.remainder = b"".join(data)
1428 raise
1429
Berker Peksagbabc6882015-02-20 09:39:38 +02001430
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001431class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001432 def test_all(self):
1433 # Documented objects defined in the module should be in __all__
1434 expected = {"responses"} # White-list documented dict() object
1435 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1436 # intentionally omitted for simplicity
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001437 denylist = {"HTTPMessage", "parse_headers"}
Berker Peksagbabc6882015-02-20 09:39:38 +02001438 for name in dir(client):
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001439 if name.startswith("_") or name in denylist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001440 continue
1441 module_object = getattr(client, name)
1442 if getattr(module_object, "__module__", None) == "http.client":
1443 expected.add(name)
1444 self.assertCountEqual(client.__all__, expected)
1445
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001446 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001447 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001448
Berker Peksagabbf0f42015-02-20 14:57:31 +02001449 def test_client_constants(self):
1450 # Make sure we don't break backward compatibility with 3.4
1451 expected = [
1452 'CONTINUE',
1453 'SWITCHING_PROTOCOLS',
1454 'PROCESSING',
1455 'OK',
1456 'CREATED',
1457 'ACCEPTED',
1458 'NON_AUTHORITATIVE_INFORMATION',
1459 'NO_CONTENT',
1460 'RESET_CONTENT',
1461 'PARTIAL_CONTENT',
1462 'MULTI_STATUS',
1463 'IM_USED',
1464 'MULTIPLE_CHOICES',
1465 'MOVED_PERMANENTLY',
1466 'FOUND',
1467 'SEE_OTHER',
1468 'NOT_MODIFIED',
1469 'USE_PROXY',
1470 'TEMPORARY_REDIRECT',
1471 'BAD_REQUEST',
1472 'UNAUTHORIZED',
1473 'PAYMENT_REQUIRED',
1474 'FORBIDDEN',
1475 'NOT_FOUND',
1476 'METHOD_NOT_ALLOWED',
1477 'NOT_ACCEPTABLE',
1478 'PROXY_AUTHENTICATION_REQUIRED',
1479 'REQUEST_TIMEOUT',
1480 'CONFLICT',
1481 'GONE',
1482 'LENGTH_REQUIRED',
1483 'PRECONDITION_FAILED',
1484 'REQUEST_ENTITY_TOO_LARGE',
1485 'REQUEST_URI_TOO_LONG',
1486 'UNSUPPORTED_MEDIA_TYPE',
1487 'REQUESTED_RANGE_NOT_SATISFIABLE',
1488 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001489 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001490 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001491 'UNPROCESSABLE_ENTITY',
1492 'LOCKED',
1493 'FAILED_DEPENDENCY',
1494 'UPGRADE_REQUIRED',
1495 'PRECONDITION_REQUIRED',
1496 'TOO_MANY_REQUESTS',
1497 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001498 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001499 'INTERNAL_SERVER_ERROR',
1500 'NOT_IMPLEMENTED',
1501 'BAD_GATEWAY',
1502 'SERVICE_UNAVAILABLE',
1503 'GATEWAY_TIMEOUT',
1504 'HTTP_VERSION_NOT_SUPPORTED',
1505 'INSUFFICIENT_STORAGE',
1506 'NOT_EXTENDED',
1507 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001508 'EARLY_HINTS',
1509 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001510 ]
1511 for const in expected:
1512 with self.subTest(constant=const):
1513 self.assertTrue(hasattr(client, const))
1514
Gregory P. Smithb4066372010-01-03 03:28:29 +00001515
1516class SourceAddressTest(TestCase):
1517 def setUp(self):
1518 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001519 self.port = socket_helper.bind_port(self.serv)
1520 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001521 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001522 self.conn = None
1523
1524 def tearDown(self):
1525 if self.conn:
1526 self.conn.close()
1527 self.conn = None
1528 self.serv.close()
1529 self.serv = None
1530
1531 def testHTTPConnectionSourceAddress(self):
1532 self.conn = client.HTTPConnection(HOST, self.port,
1533 source_address=('', self.source_port))
1534 self.conn.connect()
1535 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1536
1537 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1538 'http.client.HTTPSConnection not defined')
1539 def testHTTPSConnectionSourceAddress(self):
1540 self.conn = client.HTTPSConnection(HOST, self.port,
1541 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001542 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001543 # this code doesn't deal with setting up an active running SSL server
1544 # for an ssl_wrapped connect() to actually return from.
1545
1546
Guido van Rossumd8faa362007-04-27 19:54:29 +00001547class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001548 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001549
1550 def setUp(self):
1551 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001552 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001553 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001554
1555 def tearDown(self):
1556 self.serv.close()
1557 self.serv = None
1558
1559 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001560 # This will prove that the timeout gets through HTTPConnection
1561 # and into the socket.
1562
Georg Brandlf78e02b2008-06-10 17:40:04 +00001563 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001564 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001565 socket.setdefaulttimeout(30)
1566 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001567 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001568 httpConn.connect()
1569 finally:
1570 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001571 self.assertEqual(httpConn.sock.gettimeout(), 30)
1572 httpConn.close()
1573
Georg Brandlf78e02b2008-06-10 17:40:04 +00001574 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001575 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001576 socket.setdefaulttimeout(30)
1577 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001578 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001579 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001580 httpConn.connect()
1581 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001582 socket.setdefaulttimeout(None)
1583 self.assertEqual(httpConn.sock.gettimeout(), None)
1584 httpConn.close()
1585
1586 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001587 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001588 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001589 self.assertEqual(httpConn.sock.gettimeout(), 30)
1590 httpConn.close()
1591
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001592
R David Murraycae7bdb2015-04-05 19:26:29 -04001593class PersistenceTest(TestCase):
1594
1595 def test_reuse_reconnect(self):
1596 # Should reuse or reconnect depending on header from server
1597 tests = (
1598 ('1.0', '', False),
1599 ('1.0', 'Connection: keep-alive\r\n', True),
1600 ('1.1', '', True),
1601 ('1.1', 'Connection: close\r\n', False),
1602 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1603 ('1.1', 'Connection: cloSE\r\n', False),
1604 )
1605 for version, header, reuse in tests:
1606 with self.subTest(version=version, header=header):
1607 msg = (
1608 'HTTP/{} 200 OK\r\n'
1609 '{}'
1610 'Content-Length: 12\r\n'
1611 '\r\n'
1612 'Dummy body\r\n'
1613 ).format(version, header)
1614 conn = FakeSocketHTTPConnection(msg)
1615 self.assertIsNone(conn.sock)
1616 conn.request('GET', '/open-connection')
1617 with conn.getresponse() as response:
1618 self.assertEqual(conn.sock is None, not reuse)
1619 response.read()
1620 self.assertEqual(conn.sock is None, not reuse)
1621 self.assertEqual(conn.connections, 1)
1622 conn.request('GET', '/subsequent-request')
1623 self.assertEqual(conn.connections, 1 if reuse else 2)
1624
1625 def test_disconnected(self):
1626
1627 def make_reset_reader(text):
1628 """Return BufferedReader that raises ECONNRESET at EOF"""
1629 stream = io.BytesIO(text)
1630 def readinto(buffer):
1631 size = io.BytesIO.readinto(stream, buffer)
1632 if size == 0:
1633 raise ConnectionResetError()
1634 return size
1635 stream.readinto = readinto
1636 return io.BufferedReader(stream)
1637
1638 tests = (
1639 (io.BytesIO, client.RemoteDisconnected),
1640 (make_reset_reader, ConnectionResetError),
1641 )
1642 for stream_factory, exception in tests:
1643 with self.subTest(exception=exception):
1644 conn = FakeSocketHTTPConnection(b'', stream_factory)
1645 conn.request('GET', '/eof-response')
1646 self.assertRaises(exception, conn.getresponse)
1647 self.assertIsNone(conn.sock)
1648 # HTTPConnection.connect() should be automatically invoked
1649 conn.request('GET', '/reconnect')
1650 self.assertEqual(conn.connections, 2)
1651
1652 def test_100_close(self):
1653 conn = FakeSocketHTTPConnection(
1654 b'HTTP/1.1 100 Continue\r\n'
1655 b'\r\n'
1656 # Missing final response
1657 )
1658 conn.request('GET', '/', headers={'Expect': '100-continue'})
1659 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1660 self.assertIsNone(conn.sock)
1661 conn.request('GET', '/reconnect')
1662 self.assertEqual(conn.connections, 2)
1663
1664
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001665class HTTPSTest(TestCase):
1666
1667 def setUp(self):
1668 if not hasattr(client, 'HTTPSConnection'):
1669 self.skipTest('ssl support required')
1670
1671 def make_server(self, certfile):
1672 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001673 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001674
1675 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001676 # simple test to check it's storing the timeout
1677 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1678 self.assertEqual(h.timeout, 30)
1679
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001680 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001681 # Default settings: requires a valid cert from a trusted CA
1682 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001683 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001684 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001685 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1686 with self.assertRaises(ssl.SSLError) as exc_info:
1687 h.request('GET', '/')
1688 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1689
1690 def test_networked_noverification(self):
1691 # Switch off cert verification
1692 import ssl
1693 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001694 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001695 context = ssl._create_unverified_context()
1696 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1697 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001698 h.request('GET', '/')
1699 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001700 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001701 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001702 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001703
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001704 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001705 def test_networked_trusted_by_default_cert(self):
1706 # Default settings: requires a valid cert from a trusted CA
1707 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001708 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001709 h = client.HTTPSConnection('www.python.org', 443)
1710 h.request('GET', '/')
1711 resp = h.getresponse()
1712 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001713 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001714 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001715 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001716
1717 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001718 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001719 import ssl
1720 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001721 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001722 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001723 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1724 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1725 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001726 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001727 try:
1728 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1729 context=context)
1730 h.request('GET', '/')
1731 resp = h.getresponse()
1732 except ssl.SSLError as ssl_err:
1733 ssl_err_str = str(ssl_err)
1734 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1735 # modern Linux distros (Debian Buster, etc) default OpenSSL
1736 # configurations it'll fail saying "key too weak" until we
1737 # address https://bugs.python.org/issue36816 to use a proper
1738 # key size on self-signed.pythontest.net.
1739 if re.search(r'(?i)key.too.weak', ssl_err_str):
1740 raise unittest.SkipTest(
1741 f'Got {ssl_err_str} trying to connect '
1742 f'to {selfsigned_pythontestdotnet}. '
1743 'See https://bugs.python.org/issue36816.')
1744 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001745 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001746 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001747 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001748 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001749
1750 def test_networked_bad_cert(self):
1751 # We feed a "CA" cert that is unrelated to the server's cert
1752 import ssl
1753 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001754 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001755 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001756 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001757 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1758 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001759 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001760 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1761
1762 def test_local_unknown_cert(self):
1763 # The custom cert isn't known to the default trust bundle
1764 import ssl
1765 server = self.make_server(CERT_localhost)
1766 h = client.HTTPSConnection('localhost', server.port)
1767 with self.assertRaises(ssl.SSLError) as exc_info:
1768 h.request('GET', '/')
1769 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001770
1771 def test_local_good_hostname(self):
1772 # The (valid) cert validates the HTTP hostname
1773 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001774 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001775 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001776 context.load_verify_locations(CERT_localhost)
1777 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001778 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001779 h.request('GET', '/nonexistent')
1780 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001781 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001782 self.assertEqual(resp.status, 404)
1783
1784 def test_local_bad_hostname(self):
1785 # The (valid) cert doesn't validate the HTTP hostname
1786 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001787 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001788 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001789 context.load_verify_locations(CERT_fakehostname)
1790 h = client.HTTPSConnection('localhost', server.port, context=context)
1791 with self.assertRaises(ssl.CertificateError):
1792 h.request('GET', '/')
1793 # Same with explicit check_hostname=True
Hai Shi883bc632020-07-06 17:12:49 +08001794 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001795 h = client.HTTPSConnection('localhost', server.port,
1796 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001797 with self.assertRaises(ssl.CertificateError):
1798 h.request('GET', '/')
1799 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001800 context.check_hostname = False
Hai Shi883bc632020-07-06 17:12:49 +08001801 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001802 h = client.HTTPSConnection('localhost', server.port,
1803 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001804 h.request('GET', '/nonexistent')
1805 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001806 resp.close()
1807 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001808 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001809 # The context's check_hostname setting is used if one isn't passed to
1810 # HTTPSConnection.
1811 context.check_hostname = False
1812 h = client.HTTPSConnection('localhost', server.port, context=context)
1813 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001814 resp = h.getresponse()
1815 self.assertEqual(resp.status, 404)
1816 resp.close()
1817 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001818 # Passing check_hostname to HTTPSConnection should override the
1819 # context's setting.
Hai Shi883bc632020-07-06 17:12:49 +08001820 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001821 h = client.HTTPSConnection('localhost', server.port,
1822 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001823 with self.assertRaises(ssl.CertificateError):
1824 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001825
Petri Lehtinene119c402011-10-26 21:29:15 +03001826 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1827 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001828 def test_host_port(self):
1829 # Check invalid host_port
1830
1831 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1832 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1833
1834 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1835 "fe80::207:e9ff:fe9b", 8000),
1836 ("www.python.org:443", "www.python.org", 443),
1837 ("www.python.org:", "www.python.org", 443),
1838 ("www.python.org", "www.python.org", 443),
1839 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1840 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1841 443)):
1842 c = client.HTTPSConnection(hp)
1843 self.assertEqual(h, c.host)
1844 self.assertEqual(p, c.port)
1845
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001846 def test_tls13_pha(self):
1847 import ssl
1848 if not ssl.HAS_TLSv1_3:
1849 self.skipTest('TLS 1.3 support required')
1850 # just check status of PHA flag
1851 h = client.HTTPSConnection('localhost', 443)
1852 self.assertTrue(h._context.post_handshake_auth)
1853
1854 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1855 self.assertFalse(context.post_handshake_auth)
1856 h = client.HTTPSConnection('localhost', 443, context=context)
1857 self.assertIs(h._context, context)
1858 self.assertFalse(h._context.post_handshake_auth)
1859
Pablo Galindoaa542c22019-08-08 23:25:46 +01001860 with warnings.catch_warnings():
1861 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1862 DeprecationWarning)
1863 h = client.HTTPSConnection('localhost', 443, context=context,
1864 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001865 self.assertTrue(h._context.post_handshake_auth)
1866
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001867
Jeremy Hylton236654b2009-03-27 20:24:34 +00001868class RequestBodyTest(TestCase):
1869 """Test cases where a request includes a message body."""
1870
1871 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001872 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001873 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001874 self.conn.sock = self.sock
1875
1876 def get_headers_and_fp(self):
1877 f = io.BytesIO(self.sock.data)
1878 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001879 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001880 return message, f
1881
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001882 def test_list_body(self):
1883 # Note that no content-length is automatically calculated for
1884 # an iterable. The request will fall back to send chunked
1885 # transfer encoding.
1886 cases = (
1887 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1888 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1889 )
1890 for body, expected in cases:
1891 with self.subTest(body):
1892 self.conn = client.HTTPConnection('example.com')
1893 self.conn.sock = self.sock = FakeSocket('')
1894
1895 self.conn.request('PUT', '/url', body)
1896 msg, f = self.get_headers_and_fp()
1897 self.assertNotIn('Content-Type', msg)
1898 self.assertNotIn('Content-Length', msg)
1899 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1900 self.assertEqual(expected, f.read())
1901
Jeremy Hylton236654b2009-03-27 20:24:34 +00001902 def test_manual_content_length(self):
1903 # Set an incorrect content-length so that we can verify that
1904 # it will not be over-ridden by the library.
1905 self.conn.request("PUT", "/url", "body",
1906 {"Content-Length": "42"})
1907 message, f = self.get_headers_and_fp()
1908 self.assertEqual("42", message.get("content-length"))
1909 self.assertEqual(4, len(f.read()))
1910
1911 def test_ascii_body(self):
1912 self.conn.request("PUT", "/url", "body")
1913 message, f = self.get_headers_and_fp()
1914 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001915 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001916 self.assertEqual("4", message.get("content-length"))
1917 self.assertEqual(b'body', f.read())
1918
1919 def test_latin1_body(self):
1920 self.conn.request("PUT", "/url", "body\xc1")
1921 message, f = self.get_headers_and_fp()
1922 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001923 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001924 self.assertEqual("5", message.get("content-length"))
1925 self.assertEqual(b'body\xc1', f.read())
1926
1927 def test_bytes_body(self):
1928 self.conn.request("PUT", "/url", b"body\xc1")
1929 message, f = self.get_headers_and_fp()
1930 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001931 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001932 self.assertEqual("5", message.get("content-length"))
1933 self.assertEqual(b'body\xc1', f.read())
1934
Martin Panteref91bb22016-08-27 01:39:26 +00001935 def test_text_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001936 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1937 with open(os_helper.TESTFN, "w") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001938 f.write("body")
Hai Shi883bc632020-07-06 17:12:49 +08001939 with open(os_helper.TESTFN) as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001940 self.conn.request("PUT", "/url", f)
1941 message, f = self.get_headers_and_fp()
1942 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001943 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001944 # No content-length will be determined for files; the body
1945 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001946 self.assertIsNone(message.get("content-length"))
1947 self.assertEqual("chunked", message.get("transfer-encoding"))
1948 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001949
1950 def test_binary_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001951 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1952 with open(os_helper.TESTFN, "wb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001953 f.write(b"body\xc1")
Hai Shi883bc632020-07-06 17:12:49 +08001954 with open(os_helper.TESTFN, "rb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001955 self.conn.request("PUT", "/url", f)
1956 message, f = self.get_headers_and_fp()
1957 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001958 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001959 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1960 self.assertNotIn("Content-Length", message)
1961 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001962
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001963
1964class HTTPResponseTest(TestCase):
1965
1966 def setUp(self):
1967 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1968 second-value\r\n\r\nText"
1969 sock = FakeSocket(body)
1970 self.resp = client.HTTPResponse(sock)
1971 self.resp.begin()
1972
1973 def test_getting_header(self):
1974 header = self.resp.getheader('My-Header')
1975 self.assertEqual(header, 'first-value, second-value')
1976
1977 header = self.resp.getheader('My-Header', 'some default')
1978 self.assertEqual(header, 'first-value, second-value')
1979
1980 def test_getting_nonexistent_header_with_string_default(self):
1981 header = self.resp.getheader('No-Such-Header', 'default-value')
1982 self.assertEqual(header, 'default-value')
1983
1984 def test_getting_nonexistent_header_with_iterable_default(self):
1985 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1986 self.assertEqual(header, 'default, values')
1987
1988 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1989 self.assertEqual(header, 'default, values')
1990
1991 def test_getting_nonexistent_header_without_default(self):
1992 header = self.resp.getheader('No-Such-Header')
1993 self.assertEqual(header, None)
1994
1995 def test_getting_header_defaultint(self):
1996 header = self.resp.getheader('No-Such-Header',default=42)
1997 self.assertEqual(header, 42)
1998
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001999class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002000 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002001 response_text = (
2002 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
2003 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
2004 'Content-Length: 42\r\n\r\n'
2005 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002006 self.host = 'proxy.com'
2007 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02002008 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002009
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002010 def tearDown(self):
2011 self.conn.close()
2012
Berker Peksagab53ab02015-02-03 12:22:11 +02002013 def _create_connection(self, response_text):
2014 def create_connection(address, timeout=None, source_address=None):
2015 return FakeSocket(response_text, host=address[0], port=address[1])
2016 return create_connection
2017
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002018 def test_set_tunnel_host_port_headers(self):
2019 tunnel_host = 'destination.com'
2020 tunnel_port = 8888
2021 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2022 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2023 headers=tunnel_headers)
2024 self.conn.request('HEAD', '/', '')
2025 self.assertEqual(self.conn.sock.host, self.host)
2026 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2027 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2028 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2029 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2030
2031 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002032 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002033 self.conn.connect()
2034 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002035 'destination.com')
2036
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002037 def test_connect_with_tunnel(self):
2038 self.conn.set_tunnel('destination.com')
2039 self.conn.request('HEAD', '/', '')
2040 self.assertEqual(self.conn.sock.host, self.host)
2041 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2042 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002043 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002044 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2045 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002046
2047 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002048 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002049
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002050 def test_connect_put_request(self):
2051 self.conn.set_tunnel('destination.com')
2052 self.conn.request('PUT', '/', '')
2053 self.assertEqual(self.conn.sock.host, self.host)
2054 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2055 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2056 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2057
Berker Peksagab53ab02015-02-03 12:22:11 +02002058 def test_tunnel_debuglog(self):
2059 expected_header = 'X-Dummy: 1'
2060 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2061
2062 self.conn.set_debuglevel(1)
2063 self.conn._create_connection = self._create_connection(response_text)
2064 self.conn.set_tunnel('destination.com')
2065
2066 with support.captured_stdout() as output:
2067 self.conn.request('PUT', '/', '')
2068 lines = output.getvalue().splitlines()
2069 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002070
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002071
Thomas Wouters89f507f2006-12-13 04:49:30 +00002072if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002073 unittest.main(verbosity=2)