blob: e909980d23aac1275023574117f171d88354899b [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
Serhiy Storchaka16994912020-04-25 10:06:29 +030016from test.support import socket_helper
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000017
Antoine Pitrou803e6d62010-10-13 10:36:15 +000018here = os.path.dirname(__file__)
19# Self-signed cert file for 'localhost'
20CERT_localhost = os.path.join(here, 'keycert.pem')
21# Self-signed cert file for 'fakehostname'
22CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010023# Self-signed cert file for self-signed.pythontest.net
24CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000025
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000026# constants for testing chunked encoding
27chunked_start = (
28 'HTTP/1.1 200 OK\r\n'
29 'Transfer-Encoding: chunked\r\n\r\n'
30 'a\r\n'
31 'hello worl\r\n'
32 '3\r\n'
33 'd! \r\n'
34 '8\r\n'
35 'and now \r\n'
36 '22\r\n'
37 'for something completely different\r\n'
38)
39chunked_expected = b'hello world! and now for something completely different'
40chunk_extension = ";foo=bar"
41last_chunk = "0\r\n"
42last_chunk_extended = "0" + chunk_extension + "\r\n"
43trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
44chunked_end = "\r\n"
45
Serhiy Storchaka16994912020-04-25 10:06:29 +030046HOST = socket_helper.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000047
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000048class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040049 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000050 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000051 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000052 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000053 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000054 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010055 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020056 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040057 self.host = host
58 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000059
Jeremy Hylton2c178252004-08-07 16:28:14 +000060 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010061 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000062 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000063
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000064 def makefile(self, mode, bufsize=None):
65 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000066 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000067 # keep the file around so we can check how much was read from it
68 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020069 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000070 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000071
Serhiy Storchakab491e052014-12-01 13:07:45 +020072 def file_close(self):
73 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000074
Senthil Kumaran9da047b2014-04-14 13:07:56 -040075 def close(self):
76 pass
77
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050078 def setsockopt(self, level, optname, value):
79 pass
80
Jeremy Hylton636950f2009-03-28 04:34:21 +000081class EPipeSocket(FakeSocket):
82
83 def __init__(self, text, pipe_trigger):
84 # When sendall() is called with pipe_trigger, raise EPIPE.
85 FakeSocket.__init__(self, text)
86 self.pipe_trigger = pipe_trigger
87
88 def sendall(self, data):
89 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020090 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000091 self.data += data
92
93 def close(self):
94 pass
95
Serhiy Storchaka50254c52013-08-29 11:35:43 +030096class NoEOFBytesIO(io.BytesIO):
97 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000098
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000099 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000100 more from the underlying file than it should.
101 """
102 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000103 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000104 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000105 raise AssertionError('caller tried to read past EOF')
106 return data
107
108 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000109 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000110 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000111 raise AssertionError('caller tried to read past EOF')
112 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000113
R David Murraycae7bdb2015-04-05 19:26:29 -0400114class FakeSocketHTTPConnection(client.HTTPConnection):
115 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
116
117 def __init__(self, *args):
118 self.connections = 0
119 super().__init__('example.com')
120 self.fake_socket_args = args
121 self._create_connection = self.create_connection
122
123 def connect(self):
124 """Count the number of times connect() is invoked"""
125 self.connections += 1
126 return super().connect()
127
128 def create_connection(self, *pos, **kw):
129 return FakeSocket(*self.fake_socket_args)
130
Jeremy Hylton2c178252004-08-07 16:28:14 +0000131class HeaderTests(TestCase):
132 def test_auto_headers(self):
133 # Some headers are added automatically, but should not be added by
134 # .request() if they are explicitly set.
135
Jeremy Hylton2c178252004-08-07 16:28:14 +0000136 class HeaderCountingBuffer(list):
137 def __init__(self):
138 self.count = {}
139 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000140 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000141 if len(kv) > 1:
142 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000143 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000144 self.count.setdefault(lcKey, 0)
145 self.count[lcKey] += 1
146 list.append(self, item)
147
148 for explicit_header in True, False:
149 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000150 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000151 conn.sock = FakeSocket('blahblahblah')
152 conn._buffer = HeaderCountingBuffer()
153
154 body = 'spamspamspam'
155 headers = {}
156 if explicit_header:
157 headers[header] = str(len(body))
158 conn.request('POST', '/', body, headers)
159 self.assertEqual(conn._buffer.count[header.lower()], 1)
160
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800161 def test_content_length_0(self):
162
163 class ContentLengthChecker(list):
164 def __init__(self):
165 list.__init__(self)
166 self.content_length = None
167 def append(self, item):
168 kv = item.split(b':', 1)
169 if len(kv) > 1 and kv[0].lower() == b'content-length':
170 self.content_length = kv[1].strip()
171 list.append(self, item)
172
R David Murraybeed8402015-03-22 15:18:23 -0400173 # Here, we're testing that methods expecting a body get a
174 # content-length set to zero if the body is empty (either None or '')
175 bodies = (None, '')
176 methods_with_body = ('PUT', 'POST', 'PATCH')
177 for method, body in itertools.product(methods_with_body, bodies):
178 conn = client.HTTPConnection('example.com')
179 conn.sock = FakeSocket(None)
180 conn._buffer = ContentLengthChecker()
181 conn.request(method, '/', body)
182 self.assertEqual(
183 conn._buffer.content_length, b'0',
184 'Header Content-Length incorrect on {}'.format(method)
185 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800186
R David Murraybeed8402015-03-22 15:18:23 -0400187 # For these methods, we make sure that content-length is not set when
188 # the body is None because it might cause unexpected behaviour on the
189 # server.
190 methods_without_body = (
191 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
192 )
193 for method in methods_without_body:
194 conn = client.HTTPConnection('example.com')
195 conn.sock = FakeSocket(None)
196 conn._buffer = ContentLengthChecker()
197 conn.request(method, '/', None)
198 self.assertEqual(
199 conn._buffer.content_length, None,
200 'Header Content-Length set for empty body on {}'.format(method)
201 )
202
203 # If the body is set to '', that's considered to be "present but
204 # empty" rather than "missing", so content length would be set, even
205 # for methods that don't expect a body.
206 for method in methods_without_body:
207 conn = client.HTTPConnection('example.com')
208 conn.sock = FakeSocket(None)
209 conn._buffer = ContentLengthChecker()
210 conn.request(method, '/', '')
211 self.assertEqual(
212 conn._buffer.content_length, b'0',
213 'Header Content-Length incorrect on {}'.format(method)
214 )
215
216 # If the body is set, make sure Content-Length is set.
217 for method in itertools.chain(methods_without_body, methods_with_body):
218 conn = client.HTTPConnection('example.com')
219 conn.sock = FakeSocket(None)
220 conn._buffer = ContentLengthChecker()
221 conn.request(method, '/', ' ')
222 self.assertEqual(
223 conn._buffer.content_length, b'1',
224 'Header Content-Length incorrect on {}'.format(method)
225 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800226
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000227 def test_putheader(self):
228 conn = client.HTTPConnection('example.com')
229 conn.sock = FakeSocket(None)
230 conn.putrequest('GET','/')
231 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200232 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000233
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200234 conn.putheader('Foo', ' bar ')
235 self.assertIn(b'Foo: bar ', conn._buffer)
236 conn.putheader('Bar', '\tbaz\t')
237 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
238 conn.putheader('Authorization', 'Bearer mytoken')
239 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
240 conn.putheader('IterHeader', 'IterA', 'IterB')
241 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
242 conn.putheader('LatinHeader', b'\xFF')
243 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
244 conn.putheader('Utf8Header', b'\xc3\x80')
245 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
246 conn.putheader('C1-Control', b'next\x85line')
247 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
248 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
249 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
250 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
251 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
252 conn.putheader('Key Space', 'value')
253 self.assertIn(b'Key Space: value', conn._buffer)
254 conn.putheader('KeySpace ', 'value')
255 self.assertIn(b'KeySpace : value', conn._buffer)
256 conn.putheader(b'Nonbreak\xa0Space', 'value')
257 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
258 conn.putheader(b'\xa0NonbreakSpace', 'value')
259 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
260
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000261 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000262 # Default host header on IPv6 transaction should be wrapped by [] if
263 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000264 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
265 b'Accept-Encoding: identity\r\n\r\n'
266 conn = client.HTTPConnection('[2001::]:81')
267 sock = FakeSocket('')
268 conn.sock = sock
269 conn.request('GET', '/foo')
270 self.assertTrue(sock.data.startswith(expected))
271
272 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
273 b'Accept-Encoding: identity\r\n\r\n'
274 conn = client.HTTPConnection('[2001:102A::]')
275 sock = FakeSocket('')
276 conn.sock = sock
277 conn.request('GET', '/foo')
278 self.assertTrue(sock.data.startswith(expected))
279
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500280 def test_malformed_headers_coped_with(self):
281 # Issue 19996
282 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
283 sock = FakeSocket(body)
284 resp = client.HTTPResponse(sock)
285 resp.begin()
286
287 self.assertEqual(resp.getheader('First'), 'val')
288 self.assertEqual(resp.getheader('Second'), 'val')
289
R David Murraydc1650c2016-09-07 17:44:34 -0400290 def test_parse_all_octets(self):
291 # Ensure no valid header field octet breaks the parser
292 body = (
293 b'HTTP/1.1 200 OK\r\n'
294 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
295 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
296 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
297 b'obs-fold: text\r\n'
298 b' folded with space\r\n'
299 b'\tfolded with tab\r\n'
300 b'Content-Length: 0\r\n'
301 b'\r\n'
302 )
303 sock = FakeSocket(body)
304 resp = client.HTTPResponse(sock)
305 resp.begin()
306 self.assertEqual(resp.getheader('Content-Length'), '0')
307 self.assertEqual(resp.msg['Content-Length'], '0')
308 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
309 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
310 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
311 self.assertEqual(resp.getheader('VCHAR'), vchar)
312 self.assertEqual(resp.msg['VCHAR'], vchar)
313 self.assertIsNotNone(resp.getheader('obs-text'))
314 self.assertIn('obs-text', resp.msg)
315 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
316 self.assertTrue(folded.startswith('text'))
317 self.assertIn(' folded with space', folded)
318 self.assertTrue(folded.endswith('folded with tab'))
319
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200320 def test_invalid_headers(self):
321 conn = client.HTTPConnection('example.com')
322 conn.sock = FakeSocket('')
323 conn.putrequest('GET', '/')
324
325 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
326 # longer allowed in header names
327 cases = (
328 (b'Invalid\r\nName', b'ValidValue'),
329 (b'Invalid\rName', b'ValidValue'),
330 (b'Invalid\nName', b'ValidValue'),
331 (b'\r\nInvalidName', b'ValidValue'),
332 (b'\rInvalidName', b'ValidValue'),
333 (b'\nInvalidName', b'ValidValue'),
334 (b' InvalidName', b'ValidValue'),
335 (b'\tInvalidName', b'ValidValue'),
336 (b'Invalid:Name', b'ValidValue'),
337 (b':InvalidName', b'ValidValue'),
338 (b'ValidName', b'Invalid\r\nValue'),
339 (b'ValidName', b'Invalid\rValue'),
340 (b'ValidName', b'Invalid\nValue'),
341 (b'ValidName', b'InvalidValue\r\n'),
342 (b'ValidName', b'InvalidValue\r'),
343 (b'ValidName', b'InvalidValue\n'),
344 )
345 for name, value in cases:
346 with self.subTest((name, value)):
347 with self.assertRaisesRegex(ValueError, 'Invalid header'):
348 conn.putheader(name, value)
349
Marco Strigl936f03e2018-06-19 15:20:58 +0200350 def test_headers_debuglevel(self):
351 body = (
352 b'HTTP/1.1 200 OK\r\n'
353 b'First: val\r\n'
Matt Houglum461c4162019-04-03 21:36:47 -0700354 b'Second: val1\r\n'
355 b'Second: val2\r\n'
Marco Strigl936f03e2018-06-19 15:20:58 +0200356 )
357 sock = FakeSocket(body)
358 resp = client.HTTPResponse(sock, debuglevel=1)
359 with support.captured_stdout() as output:
360 resp.begin()
361 lines = output.getvalue().splitlines()
362 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
363 self.assertEqual(lines[1], "header: First: val")
Matt Houglum461c4162019-04-03 21:36:47 -0700364 self.assertEqual(lines[2], "header: Second: val1")
365 self.assertEqual(lines[3], "header: Second: val2")
Marco Strigl936f03e2018-06-19 15:20:58 +0200366
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000367
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000368class TransferEncodingTest(TestCase):
369 expected_body = b"It's just a flesh wound"
370
371 def test_endheaders_chunked(self):
372 conn = client.HTTPConnection('example.com')
373 conn.sock = FakeSocket(b'')
374 conn.putrequest('POST', '/')
375 conn.endheaders(self._make_body(), encode_chunked=True)
376
377 _, _, body = self._parse_request(conn.sock.data)
378 body = self._parse_chunked(body)
379 self.assertEqual(body, self.expected_body)
380
381 def test_explicit_headers(self):
382 # explicit chunked
383 conn = client.HTTPConnection('example.com')
384 conn.sock = FakeSocket(b'')
385 # this shouldn't actually be automatically chunk-encoded because the
386 # calling code has explicitly stated that it's taking care of it
387 conn.request(
388 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
389
390 _, headers, body = self._parse_request(conn.sock.data)
391 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
392 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
393 self.assertEqual(body, self.expected_body)
394
395 # explicit chunked, string body
396 conn = client.HTTPConnection('example.com')
397 conn.sock = FakeSocket(b'')
398 conn.request(
399 'POST', '/', self.expected_body.decode('latin-1'),
400 {'Transfer-Encoding': 'chunked'})
401
402 _, headers, body = self._parse_request(conn.sock.data)
403 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
404 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
405 self.assertEqual(body, self.expected_body)
406
407 # User-specified TE, but request() does the chunk encoding
408 conn = client.HTTPConnection('example.com')
409 conn.sock = FakeSocket(b'')
410 conn.request('POST', '/',
411 headers={'Transfer-Encoding': 'gzip, chunked'},
412 encode_chunked=True,
413 body=self._make_body())
414 _, headers, body = self._parse_request(conn.sock.data)
415 self.assertNotIn('content-length', [k.lower() for k in headers])
416 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
417 self.assertEqual(self._parse_chunked(body), self.expected_body)
418
419 def test_request(self):
420 for empty_lines in (False, True,):
421 conn = client.HTTPConnection('example.com')
422 conn.sock = FakeSocket(b'')
423 conn.request(
424 'POST', '/', self._make_body(empty_lines=empty_lines))
425
426 _, headers, body = self._parse_request(conn.sock.data)
427 body = self._parse_chunked(body)
428 self.assertEqual(body, self.expected_body)
429 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
430
431 # Content-Length and Transfer-Encoding SHOULD not be sent in the
432 # same request
433 self.assertNotIn('content-length', [k.lower() for k in headers])
434
Martin Panteref91bb22016-08-27 01:39:26 +0000435 def test_empty_body(self):
436 # Zero-length iterable should be treated like any other iterable
437 conn = client.HTTPConnection('example.com')
438 conn.sock = FakeSocket(b'')
439 conn.request('POST', '/', ())
440 _, headers, body = self._parse_request(conn.sock.data)
441 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
442 self.assertNotIn('content-length', [k.lower() for k in headers])
443 self.assertEqual(body, b"0\r\n\r\n")
444
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000445 def _make_body(self, empty_lines=False):
446 lines = self.expected_body.split(b' ')
447 for idx, line in enumerate(lines):
448 # for testing handling empty lines
449 if empty_lines and idx % 2:
450 yield b''
451 if idx < len(lines) - 1:
452 yield line + b' '
453 else:
454 yield line
455
456 def _parse_request(self, data):
457 lines = data.split(b'\r\n')
458 request = lines[0]
459 headers = {}
460 n = 1
461 while n < len(lines) and len(lines[n]) > 0:
462 key, val = lines[n].split(b':')
463 key = key.decode('latin-1').strip()
464 headers[key] = val.decode('latin-1').strip()
465 n += 1
466
467 return request, headers, b'\r\n'.join(lines[n + 1:])
468
469 def _parse_chunked(self, data):
470 body = []
471 trailers = {}
472 n = 0
473 lines = data.split(b'\r\n')
474 # parse body
475 while True:
476 size, chunk = lines[n:n+2]
477 size = int(size, 16)
478
479 if size == 0:
480 n += 1
481 break
482
483 self.assertEqual(size, len(chunk))
484 body.append(chunk)
485
486 n += 2
487 # we /should/ hit the end chunk, but check against the size of
488 # lines so we're not stuck in an infinite loop should we get
489 # malformed data
490 if n > len(lines):
491 break
492
493 return b''.join(body)
494
495
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496class BasicTest(TestCase):
497 def test_status_lines(self):
498 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000499
Thomas Wouters89f507f2006-12-13 04:49:30 +0000500 body = "HTTP/1.1 200 Ok\r\n\r\nText"
501 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000502 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000503 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200504 self.assertEqual(resp.read(0), b'') # Issue #20007
505 self.assertFalse(resp.isclosed())
506 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000507 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000508 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200509 self.assertFalse(resp.closed)
510 resp.close()
511 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000512
Thomas Wouters89f507f2006-12-13 04:49:30 +0000513 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
514 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000515 resp = client.HTTPResponse(sock)
516 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000517
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000518 def test_bad_status_repr(self):
519 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200520 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000521
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000522 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000523 # if we have Content-Length, HTTPResponse knows when to close itself,
524 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000525 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
526 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000527 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000528 resp.begin()
529 self.assertEqual(resp.read(2), b'Te')
530 self.assertFalse(resp.isclosed())
531 self.assertEqual(resp.read(2), b'xt')
532 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200533 self.assertFalse(resp.closed)
534 resp.close()
535 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000536
Martin Panterce911c32016-03-17 06:42:48 +0000537 def test_mixed_reads(self):
538 # readline() should update the remaining length, so that read() knows
539 # how much data is left and does not raise IncompleteRead
540 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
541 sock = FakeSocket(body)
542 resp = client.HTTPResponse(sock)
543 resp.begin()
544 self.assertEqual(resp.readline(), b'Text\r\n')
545 self.assertFalse(resp.isclosed())
546 self.assertEqual(resp.read(), b'Another')
547 self.assertTrue(resp.isclosed())
548 self.assertFalse(resp.closed)
549 resp.close()
550 self.assertTrue(resp.closed)
551
Antoine Pitrou38d96432011-12-06 22:33:57 +0100552 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000553 # if we have Content-Length, HTTPResponse knows when to close itself,
554 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100555 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
556 sock = FakeSocket(body)
557 resp = client.HTTPResponse(sock)
558 resp.begin()
559 b = bytearray(2)
560 n = resp.readinto(b)
561 self.assertEqual(n, 2)
562 self.assertEqual(bytes(b), b'Te')
563 self.assertFalse(resp.isclosed())
564 n = resp.readinto(b)
565 self.assertEqual(n, 2)
566 self.assertEqual(bytes(b), b'xt')
567 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200568 self.assertFalse(resp.closed)
569 resp.close()
570 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100571
Bruce Merry152f0b82020-06-25 08:30:21 +0200572 def test_partial_reads_past_end(self):
573 # if we have Content-Length, clip reads to the end
574 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
575 sock = FakeSocket(body)
576 resp = client.HTTPResponse(sock)
577 resp.begin()
578 self.assertEqual(resp.read(10), b'Text')
579 self.assertTrue(resp.isclosed())
580 self.assertFalse(resp.closed)
581 resp.close()
582 self.assertTrue(resp.closed)
583
584 def test_partial_readintos_past_end(self):
585 # if we have Content-Length, clip readintos to the end
586 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
587 sock = FakeSocket(body)
588 resp = client.HTTPResponse(sock)
589 resp.begin()
590 b = bytearray(10)
591 n = resp.readinto(b)
592 self.assertEqual(n, 4)
593 self.assertEqual(bytes(b)[:4], b'Text')
594 self.assertTrue(resp.isclosed())
595 self.assertFalse(resp.closed)
596 resp.close()
597 self.assertTrue(resp.closed)
598
Antoine Pitrou084daa22012-12-15 19:11:54 +0100599 def test_partial_reads_no_content_length(self):
600 # when no length is present, the socket should be gracefully closed when
601 # all data was read
602 body = "HTTP/1.1 200 Ok\r\n\r\nText"
603 sock = FakeSocket(body)
604 resp = client.HTTPResponse(sock)
605 resp.begin()
606 self.assertEqual(resp.read(2), b'Te')
607 self.assertFalse(resp.isclosed())
608 self.assertEqual(resp.read(2), b'xt')
609 self.assertEqual(resp.read(1), b'')
610 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200611 self.assertFalse(resp.closed)
612 resp.close()
613 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100614
Antoine Pitroud20e7742012-12-15 19:22:30 +0100615 def test_partial_readintos_no_content_length(self):
616 # when no length is present, the socket should be gracefully closed when
617 # all data was read
618 body = "HTTP/1.1 200 Ok\r\n\r\nText"
619 sock = FakeSocket(body)
620 resp = client.HTTPResponse(sock)
621 resp.begin()
622 b = bytearray(2)
623 n = resp.readinto(b)
624 self.assertEqual(n, 2)
625 self.assertEqual(bytes(b), b'Te')
626 self.assertFalse(resp.isclosed())
627 n = resp.readinto(b)
628 self.assertEqual(n, 2)
629 self.assertEqual(bytes(b), b'xt')
630 n = resp.readinto(b)
631 self.assertEqual(n, 0)
632 self.assertTrue(resp.isclosed())
633
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100634 def test_partial_reads_incomplete_body(self):
635 # if the server shuts down the connection before the whole
636 # content-length is delivered, the socket is gracefully closed
637 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
638 sock = FakeSocket(body)
639 resp = client.HTTPResponse(sock)
640 resp.begin()
641 self.assertEqual(resp.read(2), b'Te')
642 self.assertFalse(resp.isclosed())
643 self.assertEqual(resp.read(2), b'xt')
644 self.assertEqual(resp.read(1), b'')
645 self.assertTrue(resp.isclosed())
646
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100647 def test_partial_readintos_incomplete_body(self):
648 # if the server shuts down the connection before the whole
649 # content-length is delivered, the socket is gracefully closed
650 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
651 sock = FakeSocket(body)
652 resp = client.HTTPResponse(sock)
653 resp.begin()
654 b = bytearray(2)
655 n = resp.readinto(b)
656 self.assertEqual(n, 2)
657 self.assertEqual(bytes(b), b'Te')
658 self.assertFalse(resp.isclosed())
659 n = resp.readinto(b)
660 self.assertEqual(n, 2)
661 self.assertEqual(bytes(b), b'xt')
662 n = resp.readinto(b)
663 self.assertEqual(n, 0)
664 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200665 self.assertFalse(resp.closed)
666 resp.close()
667 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100668
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669 def test_host_port(self):
670 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000671
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200672 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000673 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000675 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
676 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200678 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000679 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200680 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
681 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000682 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000683 self.assertEqual(h, c.host)
684 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000685
Thomas Wouters89f507f2006-12-13 04:49:30 +0000686 def test_response_headers(self):
687 # test response with multiple message headers with the same field name.
688 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000689 'Set-Cookie: Customer="WILE_E_COYOTE"; '
690 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000691 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
692 ' Path="/acme"\r\n'
693 '\r\n'
694 'No body\r\n')
695 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
696 ', '
697 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
698 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000699 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000700 r.begin()
701 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000702 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000703
Thomas Wouters89f507f2006-12-13 04:49:30 +0000704 def test_read_head(self):
705 # Test that the library doesn't attempt to read any data
706 # from a HEAD request. (Tickles SF bug #622042.)
707 sock = FakeSocket(
708 'HTTP/1.1 200 OK\r\n'
709 'Content-Length: 14432\r\n'
710 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300711 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000712 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000713 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000714 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000715 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000716
Antoine Pitrou38d96432011-12-06 22:33:57 +0100717 def test_readinto_head(self):
718 # Test that the library doesn't attempt to read any data
719 # from a HEAD request. (Tickles SF bug #622042.)
720 sock = FakeSocket(
721 'HTTP/1.1 200 OK\r\n'
722 'Content-Length: 14432\r\n'
723 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300724 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100725 resp = client.HTTPResponse(sock, method="HEAD")
726 resp.begin()
727 b = bytearray(5)
728 if resp.readinto(b) != 0:
729 self.fail("Did not expect response from HEAD request")
730 self.assertEqual(bytes(b), b'\x00'*5)
731
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100732 def test_too_many_headers(self):
733 headers = '\r\n'.join('Header%d: foo' % i
734 for i in range(client._MAXHEADERS + 1)) + '\r\n'
735 text = ('HTTP/1.1 200 OK\r\n' + headers)
736 s = FakeSocket(text)
737 r = client.HTTPResponse(s)
738 self.assertRaisesRegex(client.HTTPException,
739 r"got more than \d+ headers", r.begin)
740
Thomas Wouters89f507f2006-12-13 04:49:30 +0000741 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000742 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000743 b'Accept-Encoding: identity\r\n'
744 b'Transfer-Encoding: chunked\r\n'
745 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000746
Brett Cannon77b7de62010-10-29 23:31:11 +0000747 with open(__file__, 'rb') as body:
748 conn = client.HTTPConnection('example.com')
749 sock = FakeSocket(body)
750 conn.sock = sock
751 conn.request('GET', '/foo', body)
752 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
753 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000754
Antoine Pitrouead1d622009-09-29 18:44:53 +0000755 def test_send(self):
756 expected = b'this is a test this is only a test'
757 conn = client.HTTPConnection('example.com')
758 sock = FakeSocket(None)
759 conn.sock = sock
760 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000761 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000762 sock.data = b''
763 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000764 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000765 sock.data = b''
766 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000767 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000768
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300769 def test_send_updating_file(self):
770 def data():
771 yield 'data'
772 yield None
773 yield 'data_two'
774
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000775 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300776 mode = 'r'
777 d = data()
778 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000779 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300780
781 expected = b'data'
782
783 conn = client.HTTPConnection('example.com')
784 sock = FakeSocket("")
785 conn.sock = sock
786 conn.send(UpdatingFile())
787 self.assertEqual(sock.data, expected)
788
789
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000790 def test_send_iter(self):
791 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
792 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
793 b'\r\nonetwothree'
794
795 def body():
796 yield b"one"
797 yield b"two"
798 yield b"three"
799
800 conn = client.HTTPConnection('example.com')
801 sock = FakeSocket("")
802 conn.sock = sock
803 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000804 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000805
Nir Sofferad455cd2017-11-06 23:16:37 +0200806 def test_blocksize_request(self):
807 """Check that request() respects the configured block size."""
808 blocksize = 8 # For easy debugging.
809 conn = client.HTTPConnection('example.com', blocksize=blocksize)
810 sock = FakeSocket(None)
811 conn.sock = sock
812 expected = b"a" * blocksize + b"b"
813 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
814 self.assertEqual(sock.sendall_calls, 3)
815 body = sock.data.split(b"\r\n\r\n", 1)[1]
816 self.assertEqual(body, expected)
817
818 def test_blocksize_send(self):
819 """Check that send() respects the configured block size."""
820 blocksize = 8 # For easy debugging.
821 conn = client.HTTPConnection('example.com', blocksize=blocksize)
822 sock = FakeSocket(None)
823 conn.sock = sock
824 expected = b"a" * blocksize + b"b"
825 conn.send(io.BytesIO(expected))
826 self.assertEqual(sock.sendall_calls, 2)
827 self.assertEqual(sock.data, expected)
828
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800829 def test_send_type_error(self):
830 # See: Issue #12676
831 conn = client.HTTPConnection('example.com')
832 conn.sock = FakeSocket('')
833 with self.assertRaises(TypeError):
834 conn.request('POST', 'test', conn)
835
Christian Heimesa612dc02008-02-24 13:08:18 +0000836 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000837 expected = chunked_expected
838 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000839 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000840 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100841 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000842 resp.close()
843
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100844 # Various read sizes
845 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000846 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100847 resp = client.HTTPResponse(sock, method="GET")
848 resp.begin()
849 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
850 resp.close()
851
Christian Heimesa612dc02008-02-24 13:08:18 +0000852 for x in ('', 'foo\r\n'):
853 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000854 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000855 resp.begin()
856 try:
857 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000858 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100859 self.assertEqual(i.partial, expected)
860 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
861 self.assertEqual(repr(i), expected_message)
862 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000863 else:
864 self.fail('IncompleteRead expected')
865 finally:
866 resp.close()
867
Antoine Pitrou38d96432011-12-06 22:33:57 +0100868 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000869
870 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100871 nexpected = len(expected)
872 b = bytearray(128)
873
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000874 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100875 resp = client.HTTPResponse(sock, method="GET")
876 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100877 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100878 self.assertEqual(b[:nexpected], expected)
879 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100880 resp.close()
881
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100882 # Various read sizes
883 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000884 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100885 resp = client.HTTPResponse(sock, method="GET")
886 resp.begin()
887 m = memoryview(b)
888 i = resp.readinto(m[0:n])
889 i += resp.readinto(m[i:n + i])
890 i += resp.readinto(m[i:])
891 self.assertEqual(b[:nexpected], expected)
892 self.assertEqual(i, nexpected)
893 resp.close()
894
Antoine Pitrou38d96432011-12-06 22:33:57 +0100895 for x in ('', 'foo\r\n'):
896 sock = FakeSocket(chunked_start + x)
897 resp = client.HTTPResponse(sock, method="GET")
898 resp.begin()
899 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100900 n = resp.readinto(b)
901 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100902 self.assertEqual(i.partial, expected)
903 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
904 self.assertEqual(repr(i), expected_message)
905 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100906 else:
907 self.fail('IncompleteRead expected')
908 finally:
909 resp.close()
910
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000911 def test_chunked_head(self):
912 chunked_start = (
913 'HTTP/1.1 200 OK\r\n'
914 'Transfer-Encoding: chunked\r\n\r\n'
915 'a\r\n'
916 'hello world\r\n'
917 '1\r\n'
918 'd\r\n'
919 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000920 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000921 resp = client.HTTPResponse(sock, method="HEAD")
922 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000923 self.assertEqual(resp.read(), b'')
924 self.assertEqual(resp.status, 200)
925 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000926 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200927 self.assertFalse(resp.closed)
928 resp.close()
929 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000930
Antoine Pitrou38d96432011-12-06 22:33:57 +0100931 def test_readinto_chunked_head(self):
932 chunked_start = (
933 'HTTP/1.1 200 OK\r\n'
934 'Transfer-Encoding: chunked\r\n\r\n'
935 'a\r\n'
936 'hello world\r\n'
937 '1\r\n'
938 'd\r\n'
939 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000940 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100941 resp = client.HTTPResponse(sock, method="HEAD")
942 resp.begin()
943 b = bytearray(5)
944 n = resp.readinto(b)
945 self.assertEqual(n, 0)
946 self.assertEqual(bytes(b), b'\x00'*5)
947 self.assertEqual(resp.status, 200)
948 self.assertEqual(resp.reason, 'OK')
949 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200950 self.assertFalse(resp.closed)
951 resp.close()
952 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100953
Christian Heimesa612dc02008-02-24 13:08:18 +0000954 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000955 sock = FakeSocket(
956 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000957 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000958 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000959 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100960 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000961
Benjamin Peterson6accb982009-03-02 22:50:25 +0000962 def test_incomplete_read(self):
963 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000964 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000965 resp.begin()
966 try:
967 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000968 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000969 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000970 self.assertEqual(repr(i),
971 "IncompleteRead(7 bytes read, 3 more expected)")
972 self.assertEqual(str(i),
973 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100974 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000975 else:
976 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000977
Jeremy Hylton636950f2009-03-28 04:34:21 +0000978 def test_epipe(self):
979 sock = EPipeSocket(
980 "HTTP/1.0 401 Authorization Required\r\n"
981 "Content-type: text/html\r\n"
982 "WWW-Authenticate: Basic realm=\"example\"\r\n",
983 b"Content-Length")
984 conn = client.HTTPConnection("example.com")
985 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200986 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000987 lambda: conn.request("PUT", "/url", "body"))
988 resp = conn.getresponse()
989 self.assertEqual(401, resp.status)
990 self.assertEqual("Basic realm=\"example\"",
991 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000992
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000993 # Test lines overflowing the max line size (_MAXLINE in http.client)
994
995 def test_overflowing_status_line(self):
996 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
997 resp = client.HTTPResponse(FakeSocket(body))
998 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
999
1000 def test_overflowing_header_line(self):
1001 body = (
1002 'HTTP/1.1 200 OK\r\n'
1003 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1004 )
1005 resp = client.HTTPResponse(FakeSocket(body))
1006 self.assertRaises(client.LineTooLong, resp.begin)
1007
1008 def test_overflowing_chunked_line(self):
1009 body = (
1010 'HTTP/1.1 200 OK\r\n'
1011 'Transfer-Encoding: chunked\r\n\r\n'
1012 + '0' * 65536 + 'a\r\n'
1013 'hello world\r\n'
1014 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001015 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001016 )
1017 resp = client.HTTPResponse(FakeSocket(body))
1018 resp.begin()
1019 self.assertRaises(client.LineTooLong, resp.read)
1020
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001021 def test_early_eof(self):
1022 # Test httpresponse with no \r\n termination,
1023 body = "HTTP/1.1 200 Ok"
1024 sock = FakeSocket(body)
1025 resp = client.HTTPResponse(sock)
1026 resp.begin()
1027 self.assertEqual(resp.read(), b'')
1028 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001029 self.assertFalse(resp.closed)
1030 resp.close()
1031 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001032
Serhiy Storchakab491e052014-12-01 13:07:45 +02001033 def test_error_leak(self):
1034 # Test that the socket is not leaked if getresponse() fails
1035 conn = client.HTTPConnection('example.com')
1036 response = None
1037 class Response(client.HTTPResponse):
1038 def __init__(self, *pos, **kw):
1039 nonlocal response
1040 response = self # Avoid garbage collector closing the socket
1041 client.HTTPResponse.__init__(self, *pos, **kw)
1042 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001043 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001044 conn.request('GET', '/')
1045 self.assertRaises(client.BadStatusLine, conn.getresponse)
1046 self.assertTrue(response.closed)
1047 self.assertTrue(conn.sock.file_closed)
1048
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001049 def test_chunked_extension(self):
1050 extra = '3;foo=bar\r\n' + 'abc\r\n'
1051 expected = chunked_expected + b'abc'
1052
1053 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1054 resp = client.HTTPResponse(sock, method="GET")
1055 resp.begin()
1056 self.assertEqual(resp.read(), expected)
1057 resp.close()
1058
1059 def test_chunked_missing_end(self):
1060 """some servers may serve up a short chunked encoding stream"""
1061 expected = chunked_expected
1062 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1063 resp = client.HTTPResponse(sock, method="GET")
1064 resp.begin()
1065 self.assertEqual(resp.read(), expected)
1066 resp.close()
1067
1068 def test_chunked_trailers(self):
1069 """See that trailers are read and ignored"""
1070 expected = chunked_expected
1071 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1072 resp = client.HTTPResponse(sock, method="GET")
1073 resp.begin()
1074 self.assertEqual(resp.read(), expected)
1075 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001076 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001077 resp.close()
1078
1079 def test_chunked_sync(self):
1080 """Check that we don't read past the end of the chunked-encoding stream"""
1081 expected = chunked_expected
1082 extradata = "extradata"
1083 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1084 resp = client.HTTPResponse(sock, method="GET")
1085 resp.begin()
1086 self.assertEqual(resp.read(), expected)
1087 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001088 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001089 resp.close()
1090
1091 def test_content_length_sync(self):
1092 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001093 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001094 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001095 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 +00001096 resp = client.HTTPResponse(sock, method="GET")
1097 resp.begin()
1098 self.assertEqual(resp.read(), expected)
1099 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001100 self.assertEqual(sock.file.read(), extradata) #we read to the end
1101 resp.close()
1102
1103 def test_readlines_content_length(self):
1104 extradata = b"extradata"
1105 expected = b"Hello123\r\n"
1106 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1107 resp = client.HTTPResponse(sock, method="GET")
1108 resp.begin()
1109 self.assertEqual(resp.readlines(2000), [expected])
1110 # the file should now have our extradata ready to be read
1111 self.assertEqual(sock.file.read(), extradata) #we read to the end
1112 resp.close()
1113
1114 def test_read1_content_length(self):
1115 extradata = b"extradata"
1116 expected = b"Hello123\r\n"
1117 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1118 resp = client.HTTPResponse(sock, method="GET")
1119 resp.begin()
1120 self.assertEqual(resp.read1(2000), expected)
1121 # the file should now have our extradata ready to be read
1122 self.assertEqual(sock.file.read(), extradata) #we read to the end
1123 resp.close()
1124
1125 def test_readline_bound_content_length(self):
1126 extradata = b"extradata"
1127 expected = b"Hello123\r\n"
1128 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1129 resp = client.HTTPResponse(sock, method="GET")
1130 resp.begin()
1131 self.assertEqual(resp.readline(10), expected)
1132 self.assertEqual(resp.readline(10), b"")
1133 # the file should now have our extradata ready to be read
1134 self.assertEqual(sock.file.read(), extradata) #we read to the end
1135 resp.close()
1136
1137 def test_read1_bound_content_length(self):
1138 extradata = b"extradata"
1139 expected = b"Hello123\r\n"
1140 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1141 resp = client.HTTPResponse(sock, method="GET")
1142 resp.begin()
1143 self.assertEqual(resp.read1(20), expected*2)
1144 self.assertEqual(resp.read(), expected)
1145 # the file should now have our extradata ready to be read
1146 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001147 resp.close()
1148
Martin Panterd979b2c2016-04-09 14:03:17 +00001149 def test_response_fileno(self):
1150 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001151 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001152 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001153
1154 result = None
1155 def run_server():
1156 [conn, address] = serv.accept()
1157 with conn, conn.makefile("rb") as reader:
1158 # Read the request header until a blank line
1159 while True:
1160 line = reader.readline()
1161 if not line.rstrip(b"\r\n"):
1162 break
1163 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1164 nonlocal result
1165 result = reader.read()
1166
1167 thread = threading.Thread(target=run_server)
1168 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001169 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001170 conn = client.HTTPConnection(*serv.getsockname())
1171 conn.request("CONNECT", "dummy:1234")
1172 response = conn.getresponse()
1173 try:
1174 self.assertEqual(response.status, client.OK)
1175 s = socket.socket(fileno=response.fileno())
1176 try:
1177 s.sendall(b"proxied data\n")
1178 finally:
1179 s.detach()
1180 finally:
1181 response.close()
1182 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001183 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001184 self.assertEqual(result, b"proxied data\n")
1185
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001186 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001187 """
1188 It should be possible to override the default validation
1189 behavior in putrequest (bpo-38216).
1190 """
1191 class UnsafeHTTPConnection(client.HTTPConnection):
1192 def _validate_path(self, url):
1193 pass
1194
1195 conn = UnsafeHTTPConnection('example.com')
1196 conn.sock = FakeSocket('')
1197 conn.putrequest('GET', '/\x00')
1198
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001199 def test_putrequest_override_host_validation(self):
1200 class UnsafeHTTPConnection(client.HTTPConnection):
1201 def _validate_host(self, url):
1202 pass
1203
1204 conn = UnsafeHTTPConnection('example.com\r\n')
1205 conn.sock = FakeSocket('')
1206 # set skip_host so a ValueError is not raised upon adding the
1207 # invalid URL as the value of the "Host:" header
1208 conn.putrequest('GET', '/', skip_host=1)
1209
Jason R. Coombs7774d782019-09-28 08:32:01 -04001210 def test_putrequest_override_encoding(self):
1211 """
1212 It should be possible to override the default encoding
1213 to transmit bytes in another encoding even if invalid
1214 (bpo-36274).
1215 """
1216 class UnsafeHTTPConnection(client.HTTPConnection):
1217 def _encode_request(self, str_url):
1218 return str_url.encode('utf-8')
1219
1220 conn = UnsafeHTTPConnection('example.com')
1221 conn.sock = FakeSocket('')
1222 conn.putrequest('GET', '/☃')
1223
1224
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001225class ExtendedReadTest(TestCase):
1226 """
1227 Test peek(), read1(), readline()
1228 """
1229 lines = (
1230 'HTTP/1.1 200 OK\r\n'
1231 '\r\n'
1232 'hello world!\n'
1233 'and now \n'
1234 'for something completely different\n'
1235 'foo'
1236 )
1237 lines_expected = lines[lines.find('hello'):].encode("ascii")
1238 lines_chunked = (
1239 'HTTP/1.1 200 OK\r\n'
1240 'Transfer-Encoding: chunked\r\n\r\n'
1241 'a\r\n'
1242 'hello worl\r\n'
1243 '3\r\n'
1244 'd!\n\r\n'
1245 '9\r\n'
1246 'and now \n\r\n'
1247 '23\r\n'
1248 'for something completely different\n\r\n'
1249 '3\r\n'
1250 'foo\r\n'
1251 '0\r\n' # terminating chunk
1252 '\r\n' # end of trailers
1253 )
1254
1255 def setUp(self):
1256 sock = FakeSocket(self.lines)
1257 resp = client.HTTPResponse(sock, method="GET")
1258 resp.begin()
1259 resp.fp = io.BufferedReader(resp.fp)
1260 self.resp = resp
1261
1262
1263
1264 def test_peek(self):
1265 resp = self.resp
1266 # patch up the buffered peek so that it returns not too much stuff
1267 oldpeek = resp.fp.peek
1268 def mypeek(n=-1):
1269 p = oldpeek(n)
1270 if n >= 0:
1271 return p[:n]
1272 return p[:10]
1273 resp.fp.peek = mypeek
1274
1275 all = []
1276 while True:
1277 # try a short peek
1278 p = resp.peek(3)
1279 if p:
1280 self.assertGreater(len(p), 0)
1281 # then unbounded peek
1282 p2 = resp.peek()
1283 self.assertGreaterEqual(len(p2), len(p))
1284 self.assertTrue(p2.startswith(p))
1285 next = resp.read(len(p2))
1286 self.assertEqual(next, p2)
1287 else:
1288 next = resp.read()
1289 self.assertFalse(next)
1290 all.append(next)
1291 if not next:
1292 break
1293 self.assertEqual(b"".join(all), self.lines_expected)
1294
1295 def test_readline(self):
1296 resp = self.resp
1297 self._verify_readline(self.resp.readline, self.lines_expected)
1298
1299 def _verify_readline(self, readline, expected):
1300 all = []
1301 while True:
1302 # short readlines
1303 line = readline(5)
1304 if line and line != b"foo":
1305 if len(line) < 5:
1306 self.assertTrue(line.endswith(b"\n"))
1307 all.append(line)
1308 if not line:
1309 break
1310 self.assertEqual(b"".join(all), expected)
1311
1312 def test_read1(self):
1313 resp = self.resp
1314 def r():
1315 res = resp.read1(4)
1316 self.assertLessEqual(len(res), 4)
1317 return res
1318 readliner = Readliner(r)
1319 self._verify_readline(readliner.readline, self.lines_expected)
1320
1321 def test_read1_unbounded(self):
1322 resp = self.resp
1323 all = []
1324 while True:
1325 data = resp.read1()
1326 if not data:
1327 break
1328 all.append(data)
1329 self.assertEqual(b"".join(all), self.lines_expected)
1330
1331 def test_read1_bounded(self):
1332 resp = self.resp
1333 all = []
1334 while True:
1335 data = resp.read1(10)
1336 if not data:
1337 break
1338 self.assertLessEqual(len(data), 10)
1339 all.append(data)
1340 self.assertEqual(b"".join(all), self.lines_expected)
1341
1342 def test_read1_0(self):
1343 self.assertEqual(self.resp.read1(0), b"")
1344
1345 def test_peek_0(self):
1346 p = self.resp.peek(0)
1347 self.assertLessEqual(0, len(p))
1348
Jason R. Coombs7774d782019-09-28 08:32:01 -04001349
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001350class ExtendedReadTestChunked(ExtendedReadTest):
1351 """
1352 Test peek(), read1(), readline() in chunked mode
1353 """
1354 lines = (
1355 'HTTP/1.1 200 OK\r\n'
1356 'Transfer-Encoding: chunked\r\n\r\n'
1357 'a\r\n'
1358 'hello worl\r\n'
1359 '3\r\n'
1360 'd!\n\r\n'
1361 '9\r\n'
1362 'and now \n\r\n'
1363 '23\r\n'
1364 'for something completely different\n\r\n'
1365 '3\r\n'
1366 'foo\r\n'
1367 '0\r\n' # terminating chunk
1368 '\r\n' # end of trailers
1369 )
1370
1371
1372class Readliner:
1373 """
1374 a simple readline class that uses an arbitrary read function and buffering
1375 """
1376 def __init__(self, readfunc):
1377 self.readfunc = readfunc
1378 self.remainder = b""
1379
1380 def readline(self, limit):
1381 data = []
1382 datalen = 0
1383 read = self.remainder
1384 try:
1385 while True:
1386 idx = read.find(b'\n')
1387 if idx != -1:
1388 break
1389 if datalen + len(read) >= limit:
1390 idx = limit - datalen - 1
1391 # read more data
1392 data.append(read)
1393 read = self.readfunc()
1394 if not read:
1395 idx = 0 #eof condition
1396 break
1397 idx += 1
1398 data.append(read[:idx])
1399 self.remainder = read[idx:]
1400 return b"".join(data)
1401 except:
1402 self.remainder = b"".join(data)
1403 raise
1404
Berker Peksagbabc6882015-02-20 09:39:38 +02001405
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001406class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001407 def test_all(self):
1408 # Documented objects defined in the module should be in __all__
1409 expected = {"responses"} # White-list documented dict() object
1410 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1411 # intentionally omitted for simplicity
1412 blacklist = {"HTTPMessage", "parse_headers"}
1413 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001414 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001415 continue
1416 module_object = getattr(client, name)
1417 if getattr(module_object, "__module__", None) == "http.client":
1418 expected.add(name)
1419 self.assertCountEqual(client.__all__, expected)
1420
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001421 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001422 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001423
Berker Peksagabbf0f42015-02-20 14:57:31 +02001424 def test_client_constants(self):
1425 # Make sure we don't break backward compatibility with 3.4
1426 expected = [
1427 'CONTINUE',
1428 'SWITCHING_PROTOCOLS',
1429 'PROCESSING',
1430 'OK',
1431 'CREATED',
1432 'ACCEPTED',
1433 'NON_AUTHORITATIVE_INFORMATION',
1434 'NO_CONTENT',
1435 'RESET_CONTENT',
1436 'PARTIAL_CONTENT',
1437 'MULTI_STATUS',
1438 'IM_USED',
1439 'MULTIPLE_CHOICES',
1440 'MOVED_PERMANENTLY',
1441 'FOUND',
1442 'SEE_OTHER',
1443 'NOT_MODIFIED',
1444 'USE_PROXY',
1445 'TEMPORARY_REDIRECT',
1446 'BAD_REQUEST',
1447 'UNAUTHORIZED',
1448 'PAYMENT_REQUIRED',
1449 'FORBIDDEN',
1450 'NOT_FOUND',
1451 'METHOD_NOT_ALLOWED',
1452 'NOT_ACCEPTABLE',
1453 'PROXY_AUTHENTICATION_REQUIRED',
1454 'REQUEST_TIMEOUT',
1455 'CONFLICT',
1456 'GONE',
1457 'LENGTH_REQUIRED',
1458 'PRECONDITION_FAILED',
1459 'REQUEST_ENTITY_TOO_LARGE',
1460 'REQUEST_URI_TOO_LONG',
1461 'UNSUPPORTED_MEDIA_TYPE',
1462 'REQUESTED_RANGE_NOT_SATISFIABLE',
1463 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001464 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001465 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001466 'UNPROCESSABLE_ENTITY',
1467 'LOCKED',
1468 'FAILED_DEPENDENCY',
1469 'UPGRADE_REQUIRED',
1470 'PRECONDITION_REQUIRED',
1471 'TOO_MANY_REQUESTS',
1472 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001473 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001474 'INTERNAL_SERVER_ERROR',
1475 'NOT_IMPLEMENTED',
1476 'BAD_GATEWAY',
1477 'SERVICE_UNAVAILABLE',
1478 'GATEWAY_TIMEOUT',
1479 'HTTP_VERSION_NOT_SUPPORTED',
1480 'INSUFFICIENT_STORAGE',
1481 'NOT_EXTENDED',
1482 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001483 'EARLY_HINTS',
1484 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001485 ]
1486 for const in expected:
1487 with self.subTest(constant=const):
1488 self.assertTrue(hasattr(client, const))
1489
Gregory P. Smithb4066372010-01-03 03:28:29 +00001490
1491class SourceAddressTest(TestCase):
1492 def setUp(self):
1493 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001494 self.port = socket_helper.bind_port(self.serv)
1495 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001496 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001497 self.conn = None
1498
1499 def tearDown(self):
1500 if self.conn:
1501 self.conn.close()
1502 self.conn = None
1503 self.serv.close()
1504 self.serv = None
1505
1506 def testHTTPConnectionSourceAddress(self):
1507 self.conn = client.HTTPConnection(HOST, self.port,
1508 source_address=('', self.source_port))
1509 self.conn.connect()
1510 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1511
1512 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1513 'http.client.HTTPSConnection not defined')
1514 def testHTTPSConnectionSourceAddress(self):
1515 self.conn = client.HTTPSConnection(HOST, self.port,
1516 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001517 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001518 # this code doesn't deal with setting up an active running SSL server
1519 # for an ssl_wrapped connect() to actually return from.
1520
1521
Guido van Rossumd8faa362007-04-27 19:54:29 +00001522class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001523 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001524
1525 def setUp(self):
1526 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001527 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001528 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001529
1530 def tearDown(self):
1531 self.serv.close()
1532 self.serv = None
1533
1534 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001535 # This will prove that the timeout gets through HTTPConnection
1536 # and into the socket.
1537
Georg Brandlf78e02b2008-06-10 17:40:04 +00001538 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001539 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001540 socket.setdefaulttimeout(30)
1541 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001542 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001543 httpConn.connect()
1544 finally:
1545 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546 self.assertEqual(httpConn.sock.gettimeout(), 30)
1547 httpConn.close()
1548
Georg Brandlf78e02b2008-06-10 17:40:04 +00001549 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001550 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001551 socket.setdefaulttimeout(30)
1552 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001553 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001554 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555 httpConn.connect()
1556 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001557 socket.setdefaulttimeout(None)
1558 self.assertEqual(httpConn.sock.gettimeout(), None)
1559 httpConn.close()
1560
1561 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001562 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001563 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001564 self.assertEqual(httpConn.sock.gettimeout(), 30)
1565 httpConn.close()
1566
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001567
R David Murraycae7bdb2015-04-05 19:26:29 -04001568class PersistenceTest(TestCase):
1569
1570 def test_reuse_reconnect(self):
1571 # Should reuse or reconnect depending on header from server
1572 tests = (
1573 ('1.0', '', False),
1574 ('1.0', 'Connection: keep-alive\r\n', True),
1575 ('1.1', '', True),
1576 ('1.1', 'Connection: close\r\n', False),
1577 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1578 ('1.1', 'Connection: cloSE\r\n', False),
1579 )
1580 for version, header, reuse in tests:
1581 with self.subTest(version=version, header=header):
1582 msg = (
1583 'HTTP/{} 200 OK\r\n'
1584 '{}'
1585 'Content-Length: 12\r\n'
1586 '\r\n'
1587 'Dummy body\r\n'
1588 ).format(version, header)
1589 conn = FakeSocketHTTPConnection(msg)
1590 self.assertIsNone(conn.sock)
1591 conn.request('GET', '/open-connection')
1592 with conn.getresponse() as response:
1593 self.assertEqual(conn.sock is None, not reuse)
1594 response.read()
1595 self.assertEqual(conn.sock is None, not reuse)
1596 self.assertEqual(conn.connections, 1)
1597 conn.request('GET', '/subsequent-request')
1598 self.assertEqual(conn.connections, 1 if reuse else 2)
1599
1600 def test_disconnected(self):
1601
1602 def make_reset_reader(text):
1603 """Return BufferedReader that raises ECONNRESET at EOF"""
1604 stream = io.BytesIO(text)
1605 def readinto(buffer):
1606 size = io.BytesIO.readinto(stream, buffer)
1607 if size == 0:
1608 raise ConnectionResetError()
1609 return size
1610 stream.readinto = readinto
1611 return io.BufferedReader(stream)
1612
1613 tests = (
1614 (io.BytesIO, client.RemoteDisconnected),
1615 (make_reset_reader, ConnectionResetError),
1616 )
1617 for stream_factory, exception in tests:
1618 with self.subTest(exception=exception):
1619 conn = FakeSocketHTTPConnection(b'', stream_factory)
1620 conn.request('GET', '/eof-response')
1621 self.assertRaises(exception, conn.getresponse)
1622 self.assertIsNone(conn.sock)
1623 # HTTPConnection.connect() should be automatically invoked
1624 conn.request('GET', '/reconnect')
1625 self.assertEqual(conn.connections, 2)
1626
1627 def test_100_close(self):
1628 conn = FakeSocketHTTPConnection(
1629 b'HTTP/1.1 100 Continue\r\n'
1630 b'\r\n'
1631 # Missing final response
1632 )
1633 conn.request('GET', '/', headers={'Expect': '100-continue'})
1634 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1635 self.assertIsNone(conn.sock)
1636 conn.request('GET', '/reconnect')
1637 self.assertEqual(conn.connections, 2)
1638
1639
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001640class HTTPSTest(TestCase):
1641
1642 def setUp(self):
1643 if not hasattr(client, 'HTTPSConnection'):
1644 self.skipTest('ssl support required')
1645
1646 def make_server(self, certfile):
1647 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001648 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001649
1650 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001651 # simple test to check it's storing the timeout
1652 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1653 self.assertEqual(h.timeout, 30)
1654
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001655 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001656 # Default settings: requires a valid cert from a trusted CA
1657 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001658 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001659 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001660 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1661 with self.assertRaises(ssl.SSLError) as exc_info:
1662 h.request('GET', '/')
1663 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1664
1665 def test_networked_noverification(self):
1666 # Switch off cert verification
1667 import ssl
1668 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001669 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001670 context = ssl._create_unverified_context()
1671 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1672 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001673 h.request('GET', '/')
1674 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001675 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001676 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001677 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001678
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001679 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001680 def test_networked_trusted_by_default_cert(self):
1681 # Default settings: requires a valid cert from a trusted CA
1682 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001683 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001684 h = client.HTTPSConnection('www.python.org', 443)
1685 h.request('GET', '/')
1686 resp = h.getresponse()
1687 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001688 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001689 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001690 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001691
1692 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001693 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001694 import ssl
1695 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001696 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001697 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001698 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1699 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1700 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001701 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001702 try:
1703 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1704 context=context)
1705 h.request('GET', '/')
1706 resp = h.getresponse()
1707 except ssl.SSLError as ssl_err:
1708 ssl_err_str = str(ssl_err)
1709 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1710 # modern Linux distros (Debian Buster, etc) default OpenSSL
1711 # configurations it'll fail saying "key too weak" until we
1712 # address https://bugs.python.org/issue36816 to use a proper
1713 # key size on self-signed.pythontest.net.
1714 if re.search(r'(?i)key.too.weak', ssl_err_str):
1715 raise unittest.SkipTest(
1716 f'Got {ssl_err_str} trying to connect '
1717 f'to {selfsigned_pythontestdotnet}. '
1718 'See https://bugs.python.org/issue36816.')
1719 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001720 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001721 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001722 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001723 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001724
1725 def test_networked_bad_cert(self):
1726 # We feed a "CA" cert that is unrelated to the server's cert
1727 import ssl
1728 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001729 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001730 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001731 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001732 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1733 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001734 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001735 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1736
1737 def test_local_unknown_cert(self):
1738 # The custom cert isn't known to the default trust bundle
1739 import ssl
1740 server = self.make_server(CERT_localhost)
1741 h = client.HTTPSConnection('localhost', server.port)
1742 with self.assertRaises(ssl.SSLError) as exc_info:
1743 h.request('GET', '/')
1744 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001745
1746 def test_local_good_hostname(self):
1747 # The (valid) cert validates the HTTP hostname
1748 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001749 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001750 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001751 context.load_verify_locations(CERT_localhost)
1752 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001753 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001754 h.request('GET', '/nonexistent')
1755 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001756 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001757 self.assertEqual(resp.status, 404)
1758
1759 def test_local_bad_hostname(self):
1760 # The (valid) cert doesn't validate the HTTP hostname
1761 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001762 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001763 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001764 context.load_verify_locations(CERT_fakehostname)
1765 h = client.HTTPSConnection('localhost', server.port, context=context)
1766 with self.assertRaises(ssl.CertificateError):
1767 h.request('GET', '/')
1768 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001769 with support.check_warnings(('', DeprecationWarning)):
1770 h = client.HTTPSConnection('localhost', server.port,
1771 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001772 with self.assertRaises(ssl.CertificateError):
1773 h.request('GET', '/')
1774 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001775 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001776 with support.check_warnings(('', DeprecationWarning)):
1777 h = client.HTTPSConnection('localhost', server.port,
1778 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001779 h.request('GET', '/nonexistent')
1780 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001781 resp.close()
1782 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001783 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001784 # The context's check_hostname setting is used if one isn't passed to
1785 # HTTPSConnection.
1786 context.check_hostname = False
1787 h = client.HTTPSConnection('localhost', server.port, context=context)
1788 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001789 resp = h.getresponse()
1790 self.assertEqual(resp.status, 404)
1791 resp.close()
1792 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001793 # Passing check_hostname to HTTPSConnection should override the
1794 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001795 with support.check_warnings(('', DeprecationWarning)):
1796 h = client.HTTPSConnection('localhost', server.port,
1797 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001798 with self.assertRaises(ssl.CertificateError):
1799 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001800
Petri Lehtinene119c402011-10-26 21:29:15 +03001801 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1802 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001803 def test_host_port(self):
1804 # Check invalid host_port
1805
1806 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1807 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1808
1809 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1810 "fe80::207:e9ff:fe9b", 8000),
1811 ("www.python.org:443", "www.python.org", 443),
1812 ("www.python.org:", "www.python.org", 443),
1813 ("www.python.org", "www.python.org", 443),
1814 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1815 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1816 443)):
1817 c = client.HTTPSConnection(hp)
1818 self.assertEqual(h, c.host)
1819 self.assertEqual(p, c.port)
1820
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001821 def test_tls13_pha(self):
1822 import ssl
1823 if not ssl.HAS_TLSv1_3:
1824 self.skipTest('TLS 1.3 support required')
1825 # just check status of PHA flag
1826 h = client.HTTPSConnection('localhost', 443)
1827 self.assertTrue(h._context.post_handshake_auth)
1828
1829 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1830 self.assertFalse(context.post_handshake_auth)
1831 h = client.HTTPSConnection('localhost', 443, context=context)
1832 self.assertIs(h._context, context)
1833 self.assertFalse(h._context.post_handshake_auth)
1834
Pablo Galindoaa542c22019-08-08 23:25:46 +01001835 with warnings.catch_warnings():
1836 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1837 DeprecationWarning)
1838 h = client.HTTPSConnection('localhost', 443, context=context,
1839 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001840 self.assertTrue(h._context.post_handshake_auth)
1841
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001842
Jeremy Hylton236654b2009-03-27 20:24:34 +00001843class RequestBodyTest(TestCase):
1844 """Test cases where a request includes a message body."""
1845
1846 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001847 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001848 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001849 self.conn.sock = self.sock
1850
1851 def get_headers_and_fp(self):
1852 f = io.BytesIO(self.sock.data)
1853 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001854 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001855 return message, f
1856
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001857 def test_list_body(self):
1858 # Note that no content-length is automatically calculated for
1859 # an iterable. The request will fall back to send chunked
1860 # transfer encoding.
1861 cases = (
1862 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1863 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1864 )
1865 for body, expected in cases:
1866 with self.subTest(body):
1867 self.conn = client.HTTPConnection('example.com')
1868 self.conn.sock = self.sock = FakeSocket('')
1869
1870 self.conn.request('PUT', '/url', body)
1871 msg, f = self.get_headers_and_fp()
1872 self.assertNotIn('Content-Type', msg)
1873 self.assertNotIn('Content-Length', msg)
1874 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1875 self.assertEqual(expected, f.read())
1876
Jeremy Hylton236654b2009-03-27 20:24:34 +00001877 def test_manual_content_length(self):
1878 # Set an incorrect content-length so that we can verify that
1879 # it will not be over-ridden by the library.
1880 self.conn.request("PUT", "/url", "body",
1881 {"Content-Length": "42"})
1882 message, f = self.get_headers_and_fp()
1883 self.assertEqual("42", message.get("content-length"))
1884 self.assertEqual(4, len(f.read()))
1885
1886 def test_ascii_body(self):
1887 self.conn.request("PUT", "/url", "body")
1888 message, f = self.get_headers_and_fp()
1889 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001890 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001891 self.assertEqual("4", message.get("content-length"))
1892 self.assertEqual(b'body', f.read())
1893
1894 def test_latin1_body(self):
1895 self.conn.request("PUT", "/url", "body\xc1")
1896 message, f = self.get_headers_and_fp()
1897 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001898 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001899 self.assertEqual("5", message.get("content-length"))
1900 self.assertEqual(b'body\xc1', f.read())
1901
1902 def test_bytes_body(self):
1903 self.conn.request("PUT", "/url", b"body\xc1")
1904 message, f = self.get_headers_and_fp()
1905 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001906 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001907 self.assertEqual("5", message.get("content-length"))
1908 self.assertEqual(b'body\xc1', f.read())
1909
Martin Panteref91bb22016-08-27 01:39:26 +00001910 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001911 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001912 with open(support.TESTFN, "w") as f:
1913 f.write("body")
1914 with open(support.TESTFN) as f:
1915 self.conn.request("PUT", "/url", f)
1916 message, f = self.get_headers_and_fp()
1917 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001918 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001919 # No content-length will be determined for files; the body
1920 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001921 self.assertIsNone(message.get("content-length"))
1922 self.assertEqual("chunked", message.get("transfer-encoding"))
1923 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001924
1925 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001926 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001927 with open(support.TESTFN, "wb") as f:
1928 f.write(b"body\xc1")
1929 with open(support.TESTFN, "rb") as f:
1930 self.conn.request("PUT", "/url", f)
1931 message, f = self.get_headers_and_fp()
1932 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001933 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001934 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1935 self.assertNotIn("Content-Length", message)
1936 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001937
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001938
1939class HTTPResponseTest(TestCase):
1940
1941 def setUp(self):
1942 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1943 second-value\r\n\r\nText"
1944 sock = FakeSocket(body)
1945 self.resp = client.HTTPResponse(sock)
1946 self.resp.begin()
1947
1948 def test_getting_header(self):
1949 header = self.resp.getheader('My-Header')
1950 self.assertEqual(header, 'first-value, second-value')
1951
1952 header = self.resp.getheader('My-Header', 'some default')
1953 self.assertEqual(header, 'first-value, second-value')
1954
1955 def test_getting_nonexistent_header_with_string_default(self):
1956 header = self.resp.getheader('No-Such-Header', 'default-value')
1957 self.assertEqual(header, 'default-value')
1958
1959 def test_getting_nonexistent_header_with_iterable_default(self):
1960 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1961 self.assertEqual(header, 'default, values')
1962
1963 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1964 self.assertEqual(header, 'default, values')
1965
1966 def test_getting_nonexistent_header_without_default(self):
1967 header = self.resp.getheader('No-Such-Header')
1968 self.assertEqual(header, None)
1969
1970 def test_getting_header_defaultint(self):
1971 header = self.resp.getheader('No-Such-Header',default=42)
1972 self.assertEqual(header, 42)
1973
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001974class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001975 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001976 response_text = (
1977 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1978 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1979 'Content-Length: 42\r\n\r\n'
1980 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001981 self.host = 'proxy.com'
1982 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001983 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001984
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001985 def tearDown(self):
1986 self.conn.close()
1987
Berker Peksagab53ab02015-02-03 12:22:11 +02001988 def _create_connection(self, response_text):
1989 def create_connection(address, timeout=None, source_address=None):
1990 return FakeSocket(response_text, host=address[0], port=address[1])
1991 return create_connection
1992
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001993 def test_set_tunnel_host_port_headers(self):
1994 tunnel_host = 'destination.com'
1995 tunnel_port = 8888
1996 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1997 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1998 headers=tunnel_headers)
1999 self.conn.request('HEAD', '/', '')
2000 self.assertEqual(self.conn.sock.host, self.host)
2001 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2002 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2003 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2004 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2005
2006 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002007 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002008 self.conn.connect()
2009 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002010 'destination.com')
2011
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002012 def test_connect_with_tunnel(self):
2013 self.conn.set_tunnel('destination.com')
2014 self.conn.request('HEAD', '/', '')
2015 self.assertEqual(self.conn.sock.host, self.host)
2016 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2017 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002018 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002019 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2020 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002021
2022 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002023 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002024
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002025 def test_connect_put_request(self):
2026 self.conn.set_tunnel('destination.com')
2027 self.conn.request('PUT', '/', '')
2028 self.assertEqual(self.conn.sock.host, self.host)
2029 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2030 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2031 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2032
Berker Peksagab53ab02015-02-03 12:22:11 +02002033 def test_tunnel_debuglog(self):
2034 expected_header = 'X-Dummy: 1'
2035 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2036
2037 self.conn.set_debuglevel(1)
2038 self.conn._create_connection = self._create_connection(response_text)
2039 self.conn.set_tunnel('destination.com')
2040
2041 with support.captured_stdout() as output:
2042 self.conn.request('PUT', '/', '')
2043 lines = output.getvalue().splitlines()
2044 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002045
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002046
Thomas Wouters89f507f2006-12-13 04:49:30 +00002047if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002048 unittest.main(verbosity=2)