blob: 1ac31bf2a8e7fbce4d7c1d9aaa9011277973f711 [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
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000371class TransferEncodingTest(TestCase):
372 expected_body = b"It's just a flesh wound"
373
374 def test_endheaders_chunked(self):
375 conn = client.HTTPConnection('example.com')
376 conn.sock = FakeSocket(b'')
377 conn.putrequest('POST', '/')
378 conn.endheaders(self._make_body(), encode_chunked=True)
379
380 _, _, body = self._parse_request(conn.sock.data)
381 body = self._parse_chunked(body)
382 self.assertEqual(body, self.expected_body)
383
384 def test_explicit_headers(self):
385 # explicit chunked
386 conn = client.HTTPConnection('example.com')
387 conn.sock = FakeSocket(b'')
388 # this shouldn't actually be automatically chunk-encoded because the
389 # calling code has explicitly stated that it's taking care of it
390 conn.request(
391 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
392
393 _, headers, body = self._parse_request(conn.sock.data)
394 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
395 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
396 self.assertEqual(body, self.expected_body)
397
398 # explicit chunked, string body
399 conn = client.HTTPConnection('example.com')
400 conn.sock = FakeSocket(b'')
401 conn.request(
402 'POST', '/', self.expected_body.decode('latin-1'),
403 {'Transfer-Encoding': 'chunked'})
404
405 _, headers, body = self._parse_request(conn.sock.data)
406 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
407 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
408 self.assertEqual(body, self.expected_body)
409
410 # User-specified TE, but request() does the chunk encoding
411 conn = client.HTTPConnection('example.com')
412 conn.sock = FakeSocket(b'')
413 conn.request('POST', '/',
414 headers={'Transfer-Encoding': 'gzip, chunked'},
415 encode_chunked=True,
416 body=self._make_body())
417 _, headers, body = self._parse_request(conn.sock.data)
418 self.assertNotIn('content-length', [k.lower() for k in headers])
419 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
420 self.assertEqual(self._parse_chunked(body), self.expected_body)
421
422 def test_request(self):
423 for empty_lines in (False, True,):
424 conn = client.HTTPConnection('example.com')
425 conn.sock = FakeSocket(b'')
426 conn.request(
427 'POST', '/', self._make_body(empty_lines=empty_lines))
428
429 _, headers, body = self._parse_request(conn.sock.data)
430 body = self._parse_chunked(body)
431 self.assertEqual(body, self.expected_body)
432 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
433
434 # Content-Length and Transfer-Encoding SHOULD not be sent in the
435 # same request
436 self.assertNotIn('content-length', [k.lower() for k in headers])
437
Martin Panteref91bb22016-08-27 01:39:26 +0000438 def test_empty_body(self):
439 # Zero-length iterable should be treated like any other iterable
440 conn = client.HTTPConnection('example.com')
441 conn.sock = FakeSocket(b'')
442 conn.request('POST', '/', ())
443 _, headers, body = self._parse_request(conn.sock.data)
444 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
445 self.assertNotIn('content-length', [k.lower() for k in headers])
446 self.assertEqual(body, b"0\r\n\r\n")
447
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000448 def _make_body(self, empty_lines=False):
449 lines = self.expected_body.split(b' ')
450 for idx, line in enumerate(lines):
451 # for testing handling empty lines
452 if empty_lines and idx % 2:
453 yield b''
454 if idx < len(lines) - 1:
455 yield line + b' '
456 else:
457 yield line
458
459 def _parse_request(self, data):
460 lines = data.split(b'\r\n')
461 request = lines[0]
462 headers = {}
463 n = 1
464 while n < len(lines) and len(lines[n]) > 0:
465 key, val = lines[n].split(b':')
466 key = key.decode('latin-1').strip()
467 headers[key] = val.decode('latin-1').strip()
468 n += 1
469
470 return request, headers, b'\r\n'.join(lines[n + 1:])
471
472 def _parse_chunked(self, data):
473 body = []
474 trailers = {}
475 n = 0
476 lines = data.split(b'\r\n')
477 # parse body
478 while True:
479 size, chunk = lines[n:n+2]
480 size = int(size, 16)
481
482 if size == 0:
483 n += 1
484 break
485
486 self.assertEqual(size, len(chunk))
487 body.append(chunk)
488
489 n += 2
490 # we /should/ hit the end chunk, but check against the size of
491 # lines so we're not stuck in an infinite loop should we get
492 # malformed data
493 if n > len(lines):
494 break
495
496 return b''.join(body)
497
498
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499class BasicTest(TestCase):
500 def test_status_lines(self):
501 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000502
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 body = "HTTP/1.1 200 Ok\r\n\r\nText"
504 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000505 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000506 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200507 self.assertEqual(resp.read(0), b'') # Issue #20007
508 self.assertFalse(resp.isclosed())
509 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000510 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000511 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200512 self.assertFalse(resp.closed)
513 resp.close()
514 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000515
Thomas Wouters89f507f2006-12-13 04:49:30 +0000516 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
517 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000518 resp = client.HTTPResponse(sock)
519 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000520
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000521 def test_bad_status_repr(self):
522 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200523 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000524
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000525 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000526 # if we have Content-Length, HTTPResponse knows when to close itself,
527 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000528 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
529 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000530 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000531 resp.begin()
532 self.assertEqual(resp.read(2), b'Te')
533 self.assertFalse(resp.isclosed())
534 self.assertEqual(resp.read(2), b'xt')
535 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200536 self.assertFalse(resp.closed)
537 resp.close()
538 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000539
Martin Panterce911c32016-03-17 06:42:48 +0000540 def test_mixed_reads(self):
541 # readline() should update the remaining length, so that read() knows
542 # how much data is left and does not raise IncompleteRead
543 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
544 sock = FakeSocket(body)
545 resp = client.HTTPResponse(sock)
546 resp.begin()
547 self.assertEqual(resp.readline(), b'Text\r\n')
548 self.assertFalse(resp.isclosed())
549 self.assertEqual(resp.read(), b'Another')
550 self.assertTrue(resp.isclosed())
551 self.assertFalse(resp.closed)
552 resp.close()
553 self.assertTrue(resp.closed)
554
Antoine Pitrou38d96432011-12-06 22:33:57 +0100555 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000556 # if we have Content-Length, HTTPResponse knows when to close itself,
557 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100558 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
559 sock = FakeSocket(body)
560 resp = client.HTTPResponse(sock)
561 resp.begin()
562 b = bytearray(2)
563 n = resp.readinto(b)
564 self.assertEqual(n, 2)
565 self.assertEqual(bytes(b), b'Te')
566 self.assertFalse(resp.isclosed())
567 n = resp.readinto(b)
568 self.assertEqual(n, 2)
569 self.assertEqual(bytes(b), b'xt')
570 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200571 self.assertFalse(resp.closed)
572 resp.close()
573 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100574
Bruce Merry152f0b82020-06-25 08:30:21 +0200575 def test_partial_reads_past_end(self):
576 # if we have Content-Length, clip reads to the end
577 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
578 sock = FakeSocket(body)
579 resp = client.HTTPResponse(sock)
580 resp.begin()
581 self.assertEqual(resp.read(10), b'Text')
582 self.assertTrue(resp.isclosed())
583 self.assertFalse(resp.closed)
584 resp.close()
585 self.assertTrue(resp.closed)
586
587 def test_partial_readintos_past_end(self):
588 # if we have Content-Length, clip readintos to the end
589 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
590 sock = FakeSocket(body)
591 resp = client.HTTPResponse(sock)
592 resp.begin()
593 b = bytearray(10)
594 n = resp.readinto(b)
595 self.assertEqual(n, 4)
596 self.assertEqual(bytes(b)[:4], b'Text')
597 self.assertTrue(resp.isclosed())
598 self.assertFalse(resp.closed)
599 resp.close()
600 self.assertTrue(resp.closed)
601
Antoine Pitrou084daa22012-12-15 19:11:54 +0100602 def test_partial_reads_no_content_length(self):
603 # when no length is present, the socket should be gracefully closed when
604 # all data was read
605 body = "HTTP/1.1 200 Ok\r\n\r\nText"
606 sock = FakeSocket(body)
607 resp = client.HTTPResponse(sock)
608 resp.begin()
609 self.assertEqual(resp.read(2), b'Te')
610 self.assertFalse(resp.isclosed())
611 self.assertEqual(resp.read(2), b'xt')
612 self.assertEqual(resp.read(1), b'')
613 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200614 self.assertFalse(resp.closed)
615 resp.close()
616 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100617
Antoine Pitroud20e7742012-12-15 19:22:30 +0100618 def test_partial_readintos_no_content_length(self):
619 # when no length is present, the socket should be gracefully closed when
620 # all data was read
621 body = "HTTP/1.1 200 Ok\r\n\r\nText"
622 sock = FakeSocket(body)
623 resp = client.HTTPResponse(sock)
624 resp.begin()
625 b = bytearray(2)
626 n = resp.readinto(b)
627 self.assertEqual(n, 2)
628 self.assertEqual(bytes(b), b'Te')
629 self.assertFalse(resp.isclosed())
630 n = resp.readinto(b)
631 self.assertEqual(n, 2)
632 self.assertEqual(bytes(b), b'xt')
633 n = resp.readinto(b)
634 self.assertEqual(n, 0)
635 self.assertTrue(resp.isclosed())
636
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100637 def test_partial_reads_incomplete_body(self):
638 # if the server shuts down the connection before the whole
639 # content-length is delivered, the socket is gracefully closed
640 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
641 sock = FakeSocket(body)
642 resp = client.HTTPResponse(sock)
643 resp.begin()
644 self.assertEqual(resp.read(2), b'Te')
645 self.assertFalse(resp.isclosed())
646 self.assertEqual(resp.read(2), b'xt')
647 self.assertEqual(resp.read(1), b'')
648 self.assertTrue(resp.isclosed())
649
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100650 def test_partial_readintos_incomplete_body(self):
651 # if the server shuts down the connection before the whole
652 # content-length is delivered, the socket is gracefully closed
653 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
654 sock = FakeSocket(body)
655 resp = client.HTTPResponse(sock)
656 resp.begin()
657 b = bytearray(2)
658 n = resp.readinto(b)
659 self.assertEqual(n, 2)
660 self.assertEqual(bytes(b), b'Te')
661 self.assertFalse(resp.isclosed())
662 n = resp.readinto(b)
663 self.assertEqual(n, 2)
664 self.assertEqual(bytes(b), b'xt')
665 n = resp.readinto(b)
666 self.assertEqual(n, 0)
667 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200668 self.assertFalse(resp.closed)
669 resp.close()
670 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100671
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 def test_host_port(self):
673 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000674
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200675 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000676 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000678 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
679 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000680 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200681 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000682 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200683 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
684 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000685 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000686 self.assertEqual(h, c.host)
687 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000688
Thomas Wouters89f507f2006-12-13 04:49:30 +0000689 def test_response_headers(self):
690 # test response with multiple message headers with the same field name.
691 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000692 'Set-Cookie: Customer="WILE_E_COYOTE"; '
693 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
695 ' Path="/acme"\r\n'
696 '\r\n'
697 'No body\r\n')
698 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
699 ', '
700 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
701 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000702 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000703 r.begin()
704 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000705 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000706
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 def test_read_head(self):
708 # Test that the library doesn't attempt to read any data
709 # from a HEAD request. (Tickles SF bug #622042.)
710 sock = FakeSocket(
711 'HTTP/1.1 200 OK\r\n'
712 'Content-Length: 14432\r\n'
713 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300714 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000715 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000716 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000717 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000718 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000719
Antoine Pitrou38d96432011-12-06 22:33:57 +0100720 def test_readinto_head(self):
721 # Test that the library doesn't attempt to read any data
722 # from a HEAD request. (Tickles SF bug #622042.)
723 sock = FakeSocket(
724 'HTTP/1.1 200 OK\r\n'
725 'Content-Length: 14432\r\n'
726 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300727 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100728 resp = client.HTTPResponse(sock, method="HEAD")
729 resp.begin()
730 b = bytearray(5)
731 if resp.readinto(b) != 0:
732 self.fail("Did not expect response from HEAD request")
733 self.assertEqual(bytes(b), b'\x00'*5)
734
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100735 def test_too_many_headers(self):
736 headers = '\r\n'.join('Header%d: foo' % i
737 for i in range(client._MAXHEADERS + 1)) + '\r\n'
738 text = ('HTTP/1.1 200 OK\r\n' + headers)
739 s = FakeSocket(text)
740 r = client.HTTPResponse(s)
741 self.assertRaisesRegex(client.HTTPException,
742 r"got more than \d+ headers", r.begin)
743
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000745 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000746 b'Accept-Encoding: identity\r\n'
747 b'Transfer-Encoding: chunked\r\n'
748 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000749
Brett Cannon77b7de62010-10-29 23:31:11 +0000750 with open(__file__, 'rb') as body:
751 conn = client.HTTPConnection('example.com')
752 sock = FakeSocket(body)
753 conn.sock = sock
754 conn.request('GET', '/foo', body)
755 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
756 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000757
Antoine Pitrouead1d622009-09-29 18:44:53 +0000758 def test_send(self):
759 expected = b'this is a test this is only a test'
760 conn = client.HTTPConnection('example.com')
761 sock = FakeSocket(None)
762 conn.sock = sock
763 conn.send(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(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000767 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000768 sock.data = b''
769 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000770 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000771
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300772 def test_send_updating_file(self):
773 def data():
774 yield 'data'
775 yield None
776 yield 'data_two'
777
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000778 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300779 mode = 'r'
780 d = data()
781 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000782 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300783
784 expected = b'data'
785
786 conn = client.HTTPConnection('example.com')
787 sock = FakeSocket("")
788 conn.sock = sock
789 conn.send(UpdatingFile())
790 self.assertEqual(sock.data, expected)
791
792
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000793 def test_send_iter(self):
794 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
795 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
796 b'\r\nonetwothree'
797
798 def body():
799 yield b"one"
800 yield b"two"
801 yield b"three"
802
803 conn = client.HTTPConnection('example.com')
804 sock = FakeSocket("")
805 conn.sock = sock
806 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000807 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000808
Nir Sofferad455cd2017-11-06 23:16:37 +0200809 def test_blocksize_request(self):
810 """Check that request() respects the configured block size."""
811 blocksize = 8 # For easy debugging.
812 conn = client.HTTPConnection('example.com', blocksize=blocksize)
813 sock = FakeSocket(None)
814 conn.sock = sock
815 expected = b"a" * blocksize + b"b"
816 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
817 self.assertEqual(sock.sendall_calls, 3)
818 body = sock.data.split(b"\r\n\r\n", 1)[1]
819 self.assertEqual(body, expected)
820
821 def test_blocksize_send(self):
822 """Check that send() respects the configured block size."""
823 blocksize = 8 # For easy debugging.
824 conn = client.HTTPConnection('example.com', blocksize=blocksize)
825 sock = FakeSocket(None)
826 conn.sock = sock
827 expected = b"a" * blocksize + b"b"
828 conn.send(io.BytesIO(expected))
829 self.assertEqual(sock.sendall_calls, 2)
830 self.assertEqual(sock.data, expected)
831
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800832 def test_send_type_error(self):
833 # See: Issue #12676
834 conn = client.HTTPConnection('example.com')
835 conn.sock = FakeSocket('')
836 with self.assertRaises(TypeError):
837 conn.request('POST', 'test', conn)
838
Christian Heimesa612dc02008-02-24 13:08:18 +0000839 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000840 expected = chunked_expected
841 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000842 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000843 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100844 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000845 resp.close()
846
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100847 # Various read sizes
848 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000849 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100850 resp = client.HTTPResponse(sock, method="GET")
851 resp.begin()
852 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
853 resp.close()
854
Christian Heimesa612dc02008-02-24 13:08:18 +0000855 for x in ('', 'foo\r\n'):
856 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000857 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000858 resp.begin()
859 try:
860 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000861 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100862 self.assertEqual(i.partial, expected)
863 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
864 self.assertEqual(repr(i), expected_message)
865 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000866 else:
867 self.fail('IncompleteRead expected')
868 finally:
869 resp.close()
870
Antoine Pitrou38d96432011-12-06 22:33:57 +0100871 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000872
873 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100874 nexpected = len(expected)
875 b = bytearray(128)
876
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000877 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100878 resp = client.HTTPResponse(sock, method="GET")
879 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100880 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100881 self.assertEqual(b[:nexpected], expected)
882 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100883 resp.close()
884
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100885 # Various read sizes
886 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000887 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100888 resp = client.HTTPResponse(sock, method="GET")
889 resp.begin()
890 m = memoryview(b)
891 i = resp.readinto(m[0:n])
892 i += resp.readinto(m[i:n + i])
893 i += resp.readinto(m[i:])
894 self.assertEqual(b[:nexpected], expected)
895 self.assertEqual(i, nexpected)
896 resp.close()
897
Antoine Pitrou38d96432011-12-06 22:33:57 +0100898 for x in ('', 'foo\r\n'):
899 sock = FakeSocket(chunked_start + x)
900 resp = client.HTTPResponse(sock, method="GET")
901 resp.begin()
902 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100903 n = resp.readinto(b)
904 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100905 self.assertEqual(i.partial, expected)
906 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
907 self.assertEqual(repr(i), expected_message)
908 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100909 else:
910 self.fail('IncompleteRead expected')
911 finally:
912 resp.close()
913
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000914 def test_chunked_head(self):
915 chunked_start = (
916 'HTTP/1.1 200 OK\r\n'
917 'Transfer-Encoding: chunked\r\n\r\n'
918 'a\r\n'
919 'hello world\r\n'
920 '1\r\n'
921 'd\r\n'
922 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000923 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000924 resp = client.HTTPResponse(sock, method="HEAD")
925 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000926 self.assertEqual(resp.read(), b'')
927 self.assertEqual(resp.status, 200)
928 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000929 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200930 self.assertFalse(resp.closed)
931 resp.close()
932 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000933
Antoine Pitrou38d96432011-12-06 22:33:57 +0100934 def test_readinto_chunked_head(self):
935 chunked_start = (
936 'HTTP/1.1 200 OK\r\n'
937 'Transfer-Encoding: chunked\r\n\r\n'
938 'a\r\n'
939 'hello world\r\n'
940 '1\r\n'
941 'd\r\n'
942 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000943 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100944 resp = client.HTTPResponse(sock, method="HEAD")
945 resp.begin()
946 b = bytearray(5)
947 n = resp.readinto(b)
948 self.assertEqual(n, 0)
949 self.assertEqual(bytes(b), b'\x00'*5)
950 self.assertEqual(resp.status, 200)
951 self.assertEqual(resp.reason, 'OK')
952 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200953 self.assertFalse(resp.closed)
954 resp.close()
955 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100956
Christian Heimesa612dc02008-02-24 13:08:18 +0000957 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000958 sock = FakeSocket(
959 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000960 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000961 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000962 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100963 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000964
Benjamin Peterson6accb982009-03-02 22:50:25 +0000965 def test_incomplete_read(self):
966 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000967 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000968 resp.begin()
969 try:
970 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000971 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000972 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000973 self.assertEqual(repr(i),
974 "IncompleteRead(7 bytes read, 3 more expected)")
975 self.assertEqual(str(i),
976 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100977 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000978 else:
979 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000980
Jeremy Hylton636950f2009-03-28 04:34:21 +0000981 def test_epipe(self):
982 sock = EPipeSocket(
983 "HTTP/1.0 401 Authorization Required\r\n"
984 "Content-type: text/html\r\n"
985 "WWW-Authenticate: Basic realm=\"example\"\r\n",
986 b"Content-Length")
987 conn = client.HTTPConnection("example.com")
988 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200989 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000990 lambda: conn.request("PUT", "/url", "body"))
991 resp = conn.getresponse()
992 self.assertEqual(401, resp.status)
993 self.assertEqual("Basic realm=\"example\"",
994 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000995
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000996 # Test lines overflowing the max line size (_MAXLINE in http.client)
997
998 def test_overflowing_status_line(self):
999 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
1000 resp = client.HTTPResponse(FakeSocket(body))
1001 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
1002
1003 def test_overflowing_header_line(self):
1004 body = (
1005 'HTTP/1.1 200 OK\r\n'
1006 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
1007 )
1008 resp = client.HTTPResponse(FakeSocket(body))
1009 self.assertRaises(client.LineTooLong, resp.begin)
1010
1011 def test_overflowing_chunked_line(self):
1012 body = (
1013 'HTTP/1.1 200 OK\r\n'
1014 'Transfer-Encoding: chunked\r\n\r\n'
1015 + '0' * 65536 + 'a\r\n'
1016 'hello world\r\n'
1017 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001018 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001019 )
1020 resp = client.HTTPResponse(FakeSocket(body))
1021 resp.begin()
1022 self.assertRaises(client.LineTooLong, resp.read)
1023
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001024 def test_early_eof(self):
1025 # Test httpresponse with no \r\n termination,
1026 body = "HTTP/1.1 200 Ok"
1027 sock = FakeSocket(body)
1028 resp = client.HTTPResponse(sock)
1029 resp.begin()
1030 self.assertEqual(resp.read(), b'')
1031 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001032 self.assertFalse(resp.closed)
1033 resp.close()
1034 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001035
Serhiy Storchakab491e052014-12-01 13:07:45 +02001036 def test_error_leak(self):
1037 # Test that the socket is not leaked if getresponse() fails
1038 conn = client.HTTPConnection('example.com')
1039 response = None
1040 class Response(client.HTTPResponse):
1041 def __init__(self, *pos, **kw):
1042 nonlocal response
1043 response = self # Avoid garbage collector closing the socket
1044 client.HTTPResponse.__init__(self, *pos, **kw)
1045 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001046 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001047 conn.request('GET', '/')
1048 self.assertRaises(client.BadStatusLine, conn.getresponse)
1049 self.assertTrue(response.closed)
1050 self.assertTrue(conn.sock.file_closed)
1051
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001052 def test_chunked_extension(self):
1053 extra = '3;foo=bar\r\n' + 'abc\r\n'
1054 expected = chunked_expected + b'abc'
1055
1056 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1057 resp = client.HTTPResponse(sock, method="GET")
1058 resp.begin()
1059 self.assertEqual(resp.read(), expected)
1060 resp.close()
1061
1062 def test_chunked_missing_end(self):
1063 """some servers may serve up a short chunked encoding stream"""
1064 expected = chunked_expected
1065 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1066 resp = client.HTTPResponse(sock, method="GET")
1067 resp.begin()
1068 self.assertEqual(resp.read(), expected)
1069 resp.close()
1070
1071 def test_chunked_trailers(self):
1072 """See that trailers are read and ignored"""
1073 expected = chunked_expected
1074 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1075 resp = client.HTTPResponse(sock, method="GET")
1076 resp.begin()
1077 self.assertEqual(resp.read(), expected)
1078 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001079 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001080 resp.close()
1081
1082 def test_chunked_sync(self):
1083 """Check that we don't read past the end of the chunked-encoding stream"""
1084 expected = chunked_expected
1085 extradata = "extradata"
1086 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1087 resp = client.HTTPResponse(sock, method="GET")
1088 resp.begin()
1089 self.assertEqual(resp.read(), expected)
1090 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001091 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001092 resp.close()
1093
1094 def test_content_length_sync(self):
1095 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001096 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001097 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001098 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 +00001099 resp = client.HTTPResponse(sock, method="GET")
1100 resp.begin()
1101 self.assertEqual(resp.read(), expected)
1102 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001103 self.assertEqual(sock.file.read(), extradata) #we read to the end
1104 resp.close()
1105
1106 def test_readlines_content_length(self):
1107 extradata = b"extradata"
1108 expected = b"Hello123\r\n"
1109 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1110 resp = client.HTTPResponse(sock, method="GET")
1111 resp.begin()
1112 self.assertEqual(resp.readlines(2000), [expected])
1113 # the file should now have our extradata ready to be read
1114 self.assertEqual(sock.file.read(), extradata) #we read to the end
1115 resp.close()
1116
1117 def test_read1_content_length(self):
1118 extradata = b"extradata"
1119 expected = b"Hello123\r\n"
1120 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1121 resp = client.HTTPResponse(sock, method="GET")
1122 resp.begin()
1123 self.assertEqual(resp.read1(2000), expected)
1124 # the file should now have our extradata ready to be read
1125 self.assertEqual(sock.file.read(), extradata) #we read to the end
1126 resp.close()
1127
1128 def test_readline_bound_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.readline(10), expected)
1135 self.assertEqual(resp.readline(10), b"")
1136 # the file should now have our extradata ready to be read
1137 self.assertEqual(sock.file.read(), extradata) #we read to the end
1138 resp.close()
1139
1140 def test_read1_bound_content_length(self):
1141 extradata = b"extradata"
1142 expected = b"Hello123\r\n"
1143 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1144 resp = client.HTTPResponse(sock, method="GET")
1145 resp.begin()
1146 self.assertEqual(resp.read1(20), expected*2)
1147 self.assertEqual(resp.read(), expected)
1148 # the file should now have our extradata ready to be read
1149 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001150 resp.close()
1151
Martin Panterd979b2c2016-04-09 14:03:17 +00001152 def test_response_fileno(self):
1153 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001154 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001155 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001156
1157 result = None
1158 def run_server():
1159 [conn, address] = serv.accept()
1160 with conn, conn.makefile("rb") as reader:
1161 # Read the request header until a blank line
1162 while True:
1163 line = reader.readline()
1164 if not line.rstrip(b"\r\n"):
1165 break
1166 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1167 nonlocal result
1168 result = reader.read()
1169
1170 thread = threading.Thread(target=run_server)
1171 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001172 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001173 conn = client.HTTPConnection(*serv.getsockname())
1174 conn.request("CONNECT", "dummy:1234")
1175 response = conn.getresponse()
1176 try:
1177 self.assertEqual(response.status, client.OK)
1178 s = socket.socket(fileno=response.fileno())
1179 try:
1180 s.sendall(b"proxied data\n")
1181 finally:
1182 s.detach()
1183 finally:
1184 response.close()
1185 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001186 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001187 self.assertEqual(result, b"proxied data\n")
1188
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001189 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001190 """
1191 It should be possible to override the default validation
1192 behavior in putrequest (bpo-38216).
1193 """
1194 class UnsafeHTTPConnection(client.HTTPConnection):
1195 def _validate_path(self, url):
1196 pass
1197
1198 conn = UnsafeHTTPConnection('example.com')
1199 conn.sock = FakeSocket('')
1200 conn.putrequest('GET', '/\x00')
1201
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001202 def test_putrequest_override_host_validation(self):
1203 class UnsafeHTTPConnection(client.HTTPConnection):
1204 def _validate_host(self, url):
1205 pass
1206
1207 conn = UnsafeHTTPConnection('example.com\r\n')
1208 conn.sock = FakeSocket('')
1209 # set skip_host so a ValueError is not raised upon adding the
1210 # invalid URL as the value of the "Host:" header
1211 conn.putrequest('GET', '/', skip_host=1)
1212
Jason R. Coombs7774d782019-09-28 08:32:01 -04001213 def test_putrequest_override_encoding(self):
1214 """
1215 It should be possible to override the default encoding
1216 to transmit bytes in another encoding even if invalid
1217 (bpo-36274).
1218 """
1219 class UnsafeHTTPConnection(client.HTTPConnection):
1220 def _encode_request(self, str_url):
1221 return str_url.encode('utf-8')
1222
1223 conn = UnsafeHTTPConnection('example.com')
1224 conn.sock = FakeSocket('')
1225 conn.putrequest('GET', '/☃')
1226
1227
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001228class ExtendedReadTest(TestCase):
1229 """
1230 Test peek(), read1(), readline()
1231 """
1232 lines = (
1233 'HTTP/1.1 200 OK\r\n'
1234 '\r\n'
1235 'hello world!\n'
1236 'and now \n'
1237 'for something completely different\n'
1238 'foo'
1239 )
1240 lines_expected = lines[lines.find('hello'):].encode("ascii")
1241 lines_chunked = (
1242 'HTTP/1.1 200 OK\r\n'
1243 'Transfer-Encoding: chunked\r\n\r\n'
1244 'a\r\n'
1245 'hello worl\r\n'
1246 '3\r\n'
1247 'd!\n\r\n'
1248 '9\r\n'
1249 'and now \n\r\n'
1250 '23\r\n'
1251 'for something completely different\n\r\n'
1252 '3\r\n'
1253 'foo\r\n'
1254 '0\r\n' # terminating chunk
1255 '\r\n' # end of trailers
1256 )
1257
1258 def setUp(self):
1259 sock = FakeSocket(self.lines)
1260 resp = client.HTTPResponse(sock, method="GET")
1261 resp.begin()
1262 resp.fp = io.BufferedReader(resp.fp)
1263 self.resp = resp
1264
1265
1266
1267 def test_peek(self):
1268 resp = self.resp
1269 # patch up the buffered peek so that it returns not too much stuff
1270 oldpeek = resp.fp.peek
1271 def mypeek(n=-1):
1272 p = oldpeek(n)
1273 if n >= 0:
1274 return p[:n]
1275 return p[:10]
1276 resp.fp.peek = mypeek
1277
1278 all = []
1279 while True:
1280 # try a short peek
1281 p = resp.peek(3)
1282 if p:
1283 self.assertGreater(len(p), 0)
1284 # then unbounded peek
1285 p2 = resp.peek()
1286 self.assertGreaterEqual(len(p2), len(p))
1287 self.assertTrue(p2.startswith(p))
1288 next = resp.read(len(p2))
1289 self.assertEqual(next, p2)
1290 else:
1291 next = resp.read()
1292 self.assertFalse(next)
1293 all.append(next)
1294 if not next:
1295 break
1296 self.assertEqual(b"".join(all), self.lines_expected)
1297
1298 def test_readline(self):
1299 resp = self.resp
1300 self._verify_readline(self.resp.readline, self.lines_expected)
1301
1302 def _verify_readline(self, readline, expected):
1303 all = []
1304 while True:
1305 # short readlines
1306 line = readline(5)
1307 if line and line != b"foo":
1308 if len(line) < 5:
1309 self.assertTrue(line.endswith(b"\n"))
1310 all.append(line)
1311 if not line:
1312 break
1313 self.assertEqual(b"".join(all), expected)
1314
1315 def test_read1(self):
1316 resp = self.resp
1317 def r():
1318 res = resp.read1(4)
1319 self.assertLessEqual(len(res), 4)
1320 return res
1321 readliner = Readliner(r)
1322 self._verify_readline(readliner.readline, self.lines_expected)
1323
1324 def test_read1_unbounded(self):
1325 resp = self.resp
1326 all = []
1327 while True:
1328 data = resp.read1()
1329 if not data:
1330 break
1331 all.append(data)
1332 self.assertEqual(b"".join(all), self.lines_expected)
1333
1334 def test_read1_bounded(self):
1335 resp = self.resp
1336 all = []
1337 while True:
1338 data = resp.read1(10)
1339 if not data:
1340 break
1341 self.assertLessEqual(len(data), 10)
1342 all.append(data)
1343 self.assertEqual(b"".join(all), self.lines_expected)
1344
1345 def test_read1_0(self):
1346 self.assertEqual(self.resp.read1(0), b"")
1347
1348 def test_peek_0(self):
1349 p = self.resp.peek(0)
1350 self.assertLessEqual(0, len(p))
1351
Jason R. Coombs7774d782019-09-28 08:32:01 -04001352
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001353class ExtendedReadTestChunked(ExtendedReadTest):
1354 """
1355 Test peek(), read1(), readline() in chunked mode
1356 """
1357 lines = (
1358 'HTTP/1.1 200 OK\r\n'
1359 'Transfer-Encoding: chunked\r\n\r\n'
1360 'a\r\n'
1361 'hello worl\r\n'
1362 '3\r\n'
1363 'd!\n\r\n'
1364 '9\r\n'
1365 'and now \n\r\n'
1366 '23\r\n'
1367 'for something completely different\n\r\n'
1368 '3\r\n'
1369 'foo\r\n'
1370 '0\r\n' # terminating chunk
1371 '\r\n' # end of trailers
1372 )
1373
1374
1375class Readliner:
1376 """
1377 a simple readline class that uses an arbitrary read function and buffering
1378 """
1379 def __init__(self, readfunc):
1380 self.readfunc = readfunc
1381 self.remainder = b""
1382
1383 def readline(self, limit):
1384 data = []
1385 datalen = 0
1386 read = self.remainder
1387 try:
1388 while True:
1389 idx = read.find(b'\n')
1390 if idx != -1:
1391 break
1392 if datalen + len(read) >= limit:
1393 idx = limit - datalen - 1
1394 # read more data
1395 data.append(read)
1396 read = self.readfunc()
1397 if not read:
1398 idx = 0 #eof condition
1399 break
1400 idx += 1
1401 data.append(read[:idx])
1402 self.remainder = read[idx:]
1403 return b"".join(data)
1404 except:
1405 self.remainder = b"".join(data)
1406 raise
1407
Berker Peksagbabc6882015-02-20 09:39:38 +02001408
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001409class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001410 def test_all(self):
1411 # Documented objects defined in the module should be in __all__
1412 expected = {"responses"} # White-list documented dict() object
1413 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1414 # intentionally omitted for simplicity
1415 blacklist = {"HTTPMessage", "parse_headers"}
1416 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001417 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001418 continue
1419 module_object = getattr(client, name)
1420 if getattr(module_object, "__module__", None) == "http.client":
1421 expected.add(name)
1422 self.assertCountEqual(client.__all__, expected)
1423
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001424 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001425 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001426
Berker Peksagabbf0f42015-02-20 14:57:31 +02001427 def test_client_constants(self):
1428 # Make sure we don't break backward compatibility with 3.4
1429 expected = [
1430 'CONTINUE',
1431 'SWITCHING_PROTOCOLS',
1432 'PROCESSING',
1433 'OK',
1434 'CREATED',
1435 'ACCEPTED',
1436 'NON_AUTHORITATIVE_INFORMATION',
1437 'NO_CONTENT',
1438 'RESET_CONTENT',
1439 'PARTIAL_CONTENT',
1440 'MULTI_STATUS',
1441 'IM_USED',
1442 'MULTIPLE_CHOICES',
1443 'MOVED_PERMANENTLY',
1444 'FOUND',
1445 'SEE_OTHER',
1446 'NOT_MODIFIED',
1447 'USE_PROXY',
1448 'TEMPORARY_REDIRECT',
1449 'BAD_REQUEST',
1450 'UNAUTHORIZED',
1451 'PAYMENT_REQUIRED',
1452 'FORBIDDEN',
1453 'NOT_FOUND',
1454 'METHOD_NOT_ALLOWED',
1455 'NOT_ACCEPTABLE',
1456 'PROXY_AUTHENTICATION_REQUIRED',
1457 'REQUEST_TIMEOUT',
1458 'CONFLICT',
1459 'GONE',
1460 'LENGTH_REQUIRED',
1461 'PRECONDITION_FAILED',
1462 'REQUEST_ENTITY_TOO_LARGE',
1463 'REQUEST_URI_TOO_LONG',
1464 'UNSUPPORTED_MEDIA_TYPE',
1465 'REQUESTED_RANGE_NOT_SATISFIABLE',
1466 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001467 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001468 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001469 'UNPROCESSABLE_ENTITY',
1470 'LOCKED',
1471 'FAILED_DEPENDENCY',
1472 'UPGRADE_REQUIRED',
1473 'PRECONDITION_REQUIRED',
1474 'TOO_MANY_REQUESTS',
1475 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001476 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001477 'INTERNAL_SERVER_ERROR',
1478 'NOT_IMPLEMENTED',
1479 'BAD_GATEWAY',
1480 'SERVICE_UNAVAILABLE',
1481 'GATEWAY_TIMEOUT',
1482 'HTTP_VERSION_NOT_SUPPORTED',
1483 'INSUFFICIENT_STORAGE',
1484 'NOT_EXTENDED',
1485 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001486 'EARLY_HINTS',
1487 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001488 ]
1489 for const in expected:
1490 with self.subTest(constant=const):
1491 self.assertTrue(hasattr(client, const))
1492
Gregory P. Smithb4066372010-01-03 03:28:29 +00001493
1494class SourceAddressTest(TestCase):
1495 def setUp(self):
1496 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001497 self.port = socket_helper.bind_port(self.serv)
1498 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001499 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001500 self.conn = None
1501
1502 def tearDown(self):
1503 if self.conn:
1504 self.conn.close()
1505 self.conn = None
1506 self.serv.close()
1507 self.serv = None
1508
1509 def testHTTPConnectionSourceAddress(self):
1510 self.conn = client.HTTPConnection(HOST, self.port,
1511 source_address=('', self.source_port))
1512 self.conn.connect()
1513 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1514
1515 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1516 'http.client.HTTPSConnection not defined')
1517 def testHTTPSConnectionSourceAddress(self):
1518 self.conn = client.HTTPSConnection(HOST, self.port,
1519 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001520 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001521 # this code doesn't deal with setting up an active running SSL server
1522 # for an ssl_wrapped connect() to actually return from.
1523
1524
Guido van Rossumd8faa362007-04-27 19:54:29 +00001525class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001526 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001527
1528 def setUp(self):
1529 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001530 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001531 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001532
1533 def tearDown(self):
1534 self.serv.close()
1535 self.serv = None
1536
1537 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001538 # This will prove that the timeout gets through HTTPConnection
1539 # and into the socket.
1540
Georg Brandlf78e02b2008-06-10 17:40:04 +00001541 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001542 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001543 socket.setdefaulttimeout(30)
1544 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001545 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001546 httpConn.connect()
1547 finally:
1548 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001549 self.assertEqual(httpConn.sock.gettimeout(), 30)
1550 httpConn.close()
1551
Georg Brandlf78e02b2008-06-10 17:40:04 +00001552 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001553 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001554 socket.setdefaulttimeout(30)
1555 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001556 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001557 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001558 httpConn.connect()
1559 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001560 socket.setdefaulttimeout(None)
1561 self.assertEqual(httpConn.sock.gettimeout(), None)
1562 httpConn.close()
1563
1564 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001565 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001566 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001567 self.assertEqual(httpConn.sock.gettimeout(), 30)
1568 httpConn.close()
1569
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001570
R David Murraycae7bdb2015-04-05 19:26:29 -04001571class PersistenceTest(TestCase):
1572
1573 def test_reuse_reconnect(self):
1574 # Should reuse or reconnect depending on header from server
1575 tests = (
1576 ('1.0', '', False),
1577 ('1.0', 'Connection: keep-alive\r\n', True),
1578 ('1.1', '', True),
1579 ('1.1', 'Connection: close\r\n', False),
1580 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1581 ('1.1', 'Connection: cloSE\r\n', False),
1582 )
1583 for version, header, reuse in tests:
1584 with self.subTest(version=version, header=header):
1585 msg = (
1586 'HTTP/{} 200 OK\r\n'
1587 '{}'
1588 'Content-Length: 12\r\n'
1589 '\r\n'
1590 'Dummy body\r\n'
1591 ).format(version, header)
1592 conn = FakeSocketHTTPConnection(msg)
1593 self.assertIsNone(conn.sock)
1594 conn.request('GET', '/open-connection')
1595 with conn.getresponse() as response:
1596 self.assertEqual(conn.sock is None, not reuse)
1597 response.read()
1598 self.assertEqual(conn.sock is None, not reuse)
1599 self.assertEqual(conn.connections, 1)
1600 conn.request('GET', '/subsequent-request')
1601 self.assertEqual(conn.connections, 1 if reuse else 2)
1602
1603 def test_disconnected(self):
1604
1605 def make_reset_reader(text):
1606 """Return BufferedReader that raises ECONNRESET at EOF"""
1607 stream = io.BytesIO(text)
1608 def readinto(buffer):
1609 size = io.BytesIO.readinto(stream, buffer)
1610 if size == 0:
1611 raise ConnectionResetError()
1612 return size
1613 stream.readinto = readinto
1614 return io.BufferedReader(stream)
1615
1616 tests = (
1617 (io.BytesIO, client.RemoteDisconnected),
1618 (make_reset_reader, ConnectionResetError),
1619 )
1620 for stream_factory, exception in tests:
1621 with self.subTest(exception=exception):
1622 conn = FakeSocketHTTPConnection(b'', stream_factory)
1623 conn.request('GET', '/eof-response')
1624 self.assertRaises(exception, conn.getresponse)
1625 self.assertIsNone(conn.sock)
1626 # HTTPConnection.connect() should be automatically invoked
1627 conn.request('GET', '/reconnect')
1628 self.assertEqual(conn.connections, 2)
1629
1630 def test_100_close(self):
1631 conn = FakeSocketHTTPConnection(
1632 b'HTTP/1.1 100 Continue\r\n'
1633 b'\r\n'
1634 # Missing final response
1635 )
1636 conn.request('GET', '/', headers={'Expect': '100-continue'})
1637 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1638 self.assertIsNone(conn.sock)
1639 conn.request('GET', '/reconnect')
1640 self.assertEqual(conn.connections, 2)
1641
1642
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001643class HTTPSTest(TestCase):
1644
1645 def setUp(self):
1646 if not hasattr(client, 'HTTPSConnection'):
1647 self.skipTest('ssl support required')
1648
1649 def make_server(self, certfile):
1650 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001651 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001652
1653 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001654 # simple test to check it's storing the timeout
1655 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1656 self.assertEqual(h.timeout, 30)
1657
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001658 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001659 # Default settings: requires a valid cert from a trusted CA
1660 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001661 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001662 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001663 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1664 with self.assertRaises(ssl.SSLError) as exc_info:
1665 h.request('GET', '/')
1666 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1667
1668 def test_networked_noverification(self):
1669 # Switch off cert verification
1670 import ssl
1671 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001672 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001673 context = ssl._create_unverified_context()
1674 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1675 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001676 h.request('GET', '/')
1677 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001678 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001679 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001680 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001681
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001682 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001683 def test_networked_trusted_by_default_cert(self):
1684 # Default settings: requires a valid cert from a trusted CA
1685 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001686 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001687 h = client.HTTPSConnection('www.python.org', 443)
1688 h.request('GET', '/')
1689 resp = h.getresponse()
1690 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001691 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001692 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001693 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001694
1695 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001696 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001697 import ssl
1698 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001699 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001700 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001701 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1702 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1703 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001704 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001705 try:
1706 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1707 context=context)
1708 h.request('GET', '/')
1709 resp = h.getresponse()
1710 except ssl.SSLError as ssl_err:
1711 ssl_err_str = str(ssl_err)
1712 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1713 # modern Linux distros (Debian Buster, etc) default OpenSSL
1714 # configurations it'll fail saying "key too weak" until we
1715 # address https://bugs.python.org/issue36816 to use a proper
1716 # key size on self-signed.pythontest.net.
1717 if re.search(r'(?i)key.too.weak', ssl_err_str):
1718 raise unittest.SkipTest(
1719 f'Got {ssl_err_str} trying to connect '
1720 f'to {selfsigned_pythontestdotnet}. '
1721 'See https://bugs.python.org/issue36816.')
1722 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001723 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001724 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001725 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001726 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001727
1728 def test_networked_bad_cert(self):
1729 # We feed a "CA" cert that is unrelated to the server's cert
1730 import ssl
1731 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001732 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001733 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001734 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001735 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1736 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001737 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001738 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1739
1740 def test_local_unknown_cert(self):
1741 # The custom cert isn't known to the default trust bundle
1742 import ssl
1743 server = self.make_server(CERT_localhost)
1744 h = client.HTTPSConnection('localhost', server.port)
1745 with self.assertRaises(ssl.SSLError) as exc_info:
1746 h.request('GET', '/')
1747 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001748
1749 def test_local_good_hostname(self):
1750 # The (valid) cert validates the HTTP hostname
1751 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001752 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001753 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001754 context.load_verify_locations(CERT_localhost)
1755 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001756 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001757 h.request('GET', '/nonexistent')
1758 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001759 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001760 self.assertEqual(resp.status, 404)
1761
1762 def test_local_bad_hostname(self):
1763 # The (valid) cert doesn't validate the HTTP hostname
1764 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001765 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001766 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001767 context.load_verify_locations(CERT_fakehostname)
1768 h = client.HTTPSConnection('localhost', server.port, context=context)
1769 with self.assertRaises(ssl.CertificateError):
1770 h.request('GET', '/')
1771 # Same with explicit check_hostname=True
Hai Shi883bc632020-07-06 17:12:49 +08001772 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001773 h = client.HTTPSConnection('localhost', server.port,
1774 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001775 with self.assertRaises(ssl.CertificateError):
1776 h.request('GET', '/')
1777 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001778 context.check_hostname = False
Hai Shi883bc632020-07-06 17:12:49 +08001779 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001780 h = client.HTTPSConnection('localhost', server.port,
1781 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001782 h.request('GET', '/nonexistent')
1783 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001784 resp.close()
1785 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001786 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001787 # The context's check_hostname setting is used if one isn't passed to
1788 # HTTPSConnection.
1789 context.check_hostname = False
1790 h = client.HTTPSConnection('localhost', server.port, context=context)
1791 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001792 resp = h.getresponse()
1793 self.assertEqual(resp.status, 404)
1794 resp.close()
1795 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001796 # Passing check_hostname to HTTPSConnection should override the
1797 # context's setting.
Hai Shi883bc632020-07-06 17:12:49 +08001798 with warnings_helper.check_warnings(('', DeprecationWarning)):
Christian Heimes8d14abc2016-09-11 19:54:43 +02001799 h = client.HTTPSConnection('localhost', server.port,
1800 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001801 with self.assertRaises(ssl.CertificateError):
1802 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001803
Petri Lehtinene119c402011-10-26 21:29:15 +03001804 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1805 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001806 def test_host_port(self):
1807 # Check invalid host_port
1808
1809 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1810 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1811
1812 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1813 "fe80::207:e9ff:fe9b", 8000),
1814 ("www.python.org:443", "www.python.org", 443),
1815 ("www.python.org:", "www.python.org", 443),
1816 ("www.python.org", "www.python.org", 443),
1817 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1818 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1819 443)):
1820 c = client.HTTPSConnection(hp)
1821 self.assertEqual(h, c.host)
1822 self.assertEqual(p, c.port)
1823
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001824 def test_tls13_pha(self):
1825 import ssl
1826 if not ssl.HAS_TLSv1_3:
1827 self.skipTest('TLS 1.3 support required')
1828 # just check status of PHA flag
1829 h = client.HTTPSConnection('localhost', 443)
1830 self.assertTrue(h._context.post_handshake_auth)
1831
1832 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1833 self.assertFalse(context.post_handshake_auth)
1834 h = client.HTTPSConnection('localhost', 443, context=context)
1835 self.assertIs(h._context, context)
1836 self.assertFalse(h._context.post_handshake_auth)
1837
Pablo Galindoaa542c22019-08-08 23:25:46 +01001838 with warnings.catch_warnings():
1839 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1840 DeprecationWarning)
1841 h = client.HTTPSConnection('localhost', 443, context=context,
1842 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001843 self.assertTrue(h._context.post_handshake_auth)
1844
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001845
Jeremy Hylton236654b2009-03-27 20:24:34 +00001846class RequestBodyTest(TestCase):
1847 """Test cases where a request includes a message body."""
1848
1849 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001850 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001851 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001852 self.conn.sock = self.sock
1853
1854 def get_headers_and_fp(self):
1855 f = io.BytesIO(self.sock.data)
1856 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001857 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001858 return message, f
1859
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001860 def test_list_body(self):
1861 # Note that no content-length is automatically calculated for
1862 # an iterable. The request will fall back to send chunked
1863 # transfer encoding.
1864 cases = (
1865 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1866 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1867 )
1868 for body, expected in cases:
1869 with self.subTest(body):
1870 self.conn = client.HTTPConnection('example.com')
1871 self.conn.sock = self.sock = FakeSocket('')
1872
1873 self.conn.request('PUT', '/url', body)
1874 msg, f = self.get_headers_and_fp()
1875 self.assertNotIn('Content-Type', msg)
1876 self.assertNotIn('Content-Length', msg)
1877 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1878 self.assertEqual(expected, f.read())
1879
Jeremy Hylton236654b2009-03-27 20:24:34 +00001880 def test_manual_content_length(self):
1881 # Set an incorrect content-length so that we can verify that
1882 # it will not be over-ridden by the library.
1883 self.conn.request("PUT", "/url", "body",
1884 {"Content-Length": "42"})
1885 message, f = self.get_headers_and_fp()
1886 self.assertEqual("42", message.get("content-length"))
1887 self.assertEqual(4, len(f.read()))
1888
1889 def test_ascii_body(self):
1890 self.conn.request("PUT", "/url", "body")
1891 message, f = self.get_headers_and_fp()
1892 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001893 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001894 self.assertEqual("4", message.get("content-length"))
1895 self.assertEqual(b'body', f.read())
1896
1897 def test_latin1_body(self):
1898 self.conn.request("PUT", "/url", "body\xc1")
1899 message, f = self.get_headers_and_fp()
1900 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001901 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001902 self.assertEqual("5", message.get("content-length"))
1903 self.assertEqual(b'body\xc1', f.read())
1904
1905 def test_bytes_body(self):
1906 self.conn.request("PUT", "/url", b"body\xc1")
1907 message, f = self.get_headers_and_fp()
1908 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001909 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001910 self.assertEqual("5", message.get("content-length"))
1911 self.assertEqual(b'body\xc1', f.read())
1912
Martin Panteref91bb22016-08-27 01:39:26 +00001913 def test_text_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001914 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1915 with open(os_helper.TESTFN, "w") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001916 f.write("body")
Hai Shi883bc632020-07-06 17:12:49 +08001917 with open(os_helper.TESTFN) as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001918 self.conn.request("PUT", "/url", f)
1919 message, f = self.get_headers_and_fp()
1920 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001921 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001922 # No content-length will be determined for files; the body
1923 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001924 self.assertIsNone(message.get("content-length"))
1925 self.assertEqual("chunked", message.get("transfer-encoding"))
1926 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001927
1928 def test_binary_file_body(self):
Hai Shi883bc632020-07-06 17:12:49 +08001929 self.addCleanup(os_helper.unlink, os_helper.TESTFN)
1930 with open(os_helper.TESTFN, "wb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001931 f.write(b"body\xc1")
Hai Shi883bc632020-07-06 17:12:49 +08001932 with open(os_helper.TESTFN, "rb") as f:
Brett Cannon77b7de62010-10-29 23:31:11 +00001933 self.conn.request("PUT", "/url", f)
1934 message, f = self.get_headers_and_fp()
1935 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001936 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001937 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1938 self.assertNotIn("Content-Length", message)
1939 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001940
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001941
1942class HTTPResponseTest(TestCase):
1943
1944 def setUp(self):
1945 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1946 second-value\r\n\r\nText"
1947 sock = FakeSocket(body)
1948 self.resp = client.HTTPResponse(sock)
1949 self.resp.begin()
1950
1951 def test_getting_header(self):
1952 header = self.resp.getheader('My-Header')
1953 self.assertEqual(header, 'first-value, second-value')
1954
1955 header = self.resp.getheader('My-Header', 'some default')
1956 self.assertEqual(header, 'first-value, second-value')
1957
1958 def test_getting_nonexistent_header_with_string_default(self):
1959 header = self.resp.getheader('No-Such-Header', 'default-value')
1960 self.assertEqual(header, 'default-value')
1961
1962 def test_getting_nonexistent_header_with_iterable_default(self):
1963 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1964 self.assertEqual(header, 'default, values')
1965
1966 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1967 self.assertEqual(header, 'default, values')
1968
1969 def test_getting_nonexistent_header_without_default(self):
1970 header = self.resp.getheader('No-Such-Header')
1971 self.assertEqual(header, None)
1972
1973 def test_getting_header_defaultint(self):
1974 header = self.resp.getheader('No-Such-Header',default=42)
1975 self.assertEqual(header, 42)
1976
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001977class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001978 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001979 response_text = (
1980 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1981 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1982 'Content-Length: 42\r\n\r\n'
1983 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001984 self.host = 'proxy.com'
1985 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001986 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001987
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001988 def tearDown(self):
1989 self.conn.close()
1990
Berker Peksagab53ab02015-02-03 12:22:11 +02001991 def _create_connection(self, response_text):
1992 def create_connection(address, timeout=None, source_address=None):
1993 return FakeSocket(response_text, host=address[0], port=address[1])
1994 return create_connection
1995
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001996 def test_set_tunnel_host_port_headers(self):
1997 tunnel_host = 'destination.com'
1998 tunnel_port = 8888
1999 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
2000 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
2001 headers=tunnel_headers)
2002 self.conn.request('HEAD', '/', '')
2003 self.assertEqual(self.conn.sock.host, self.host)
2004 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2005 self.assertEqual(self.conn._tunnel_host, tunnel_host)
2006 self.assertEqual(self.conn._tunnel_port, tunnel_port)
2007 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2008
2009 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002010 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002011 self.conn.connect()
2012 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002013 'destination.com')
2014
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002015 def test_connect_with_tunnel(self):
2016 self.conn.set_tunnel('destination.com')
2017 self.conn.request('HEAD', '/', '')
2018 self.assertEqual(self.conn.sock.host, self.host)
2019 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2020 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002021 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002022 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2023 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002024
2025 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002026 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002027
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002028 def test_connect_put_request(self):
2029 self.conn.set_tunnel('destination.com')
2030 self.conn.request('PUT', '/', '')
2031 self.assertEqual(self.conn.sock.host, self.host)
2032 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2033 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2034 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2035
Berker Peksagab53ab02015-02-03 12:22:11 +02002036 def test_tunnel_debuglog(self):
2037 expected_header = 'X-Dummy: 1'
2038 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2039
2040 self.conn.set_debuglevel(1)
2041 self.conn._create_connection = self._create_connection(response_text)
2042 self.conn.set_tunnel('destination.com')
2043
2044 with support.captured_stdout() as output:
2045 self.conn.request('PUT', '/', '')
2046 lines = output.getvalue().splitlines()
2047 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002048
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002049
Thomas Wouters89f507f2006-12-13 04:49:30 +00002050if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002051 unittest.main(verbosity=2)