blob: 6b7a9dedf1a2a9abf5b5712a21bfffc9eb56c9e6 [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
Antoine Pitrou084daa22012-12-15 19:11:54 +0100572 def test_partial_reads_no_content_length(self):
573 # when no length is present, the socket should be gracefully closed when
574 # all data was read
575 body = "HTTP/1.1 200 Ok\r\n\r\nText"
576 sock = FakeSocket(body)
577 resp = client.HTTPResponse(sock)
578 resp.begin()
579 self.assertEqual(resp.read(2), b'Te')
580 self.assertFalse(resp.isclosed())
581 self.assertEqual(resp.read(2), b'xt')
582 self.assertEqual(resp.read(1), b'')
583 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200584 self.assertFalse(resp.closed)
585 resp.close()
586 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100587
Antoine Pitroud20e7742012-12-15 19:22:30 +0100588 def test_partial_readintos_no_content_length(self):
589 # when no length is present, the socket should be gracefully closed when
590 # all data was read
591 body = "HTTP/1.1 200 Ok\r\n\r\nText"
592 sock = FakeSocket(body)
593 resp = client.HTTPResponse(sock)
594 resp.begin()
595 b = bytearray(2)
596 n = resp.readinto(b)
597 self.assertEqual(n, 2)
598 self.assertEqual(bytes(b), b'Te')
599 self.assertFalse(resp.isclosed())
600 n = resp.readinto(b)
601 self.assertEqual(n, 2)
602 self.assertEqual(bytes(b), b'xt')
603 n = resp.readinto(b)
604 self.assertEqual(n, 0)
605 self.assertTrue(resp.isclosed())
606
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100607 def test_partial_reads_incomplete_body(self):
608 # if the server shuts down the connection before the whole
609 # content-length is delivered, the socket is gracefully closed
610 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
611 sock = FakeSocket(body)
612 resp = client.HTTPResponse(sock)
613 resp.begin()
614 self.assertEqual(resp.read(2), b'Te')
615 self.assertFalse(resp.isclosed())
616 self.assertEqual(resp.read(2), b'xt')
617 self.assertEqual(resp.read(1), b'')
618 self.assertTrue(resp.isclosed())
619
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100620 def test_partial_readintos_incomplete_body(self):
621 # if the server shuts down the connection before the whole
622 # content-length is delivered, the socket is gracefully closed
623 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
624 sock = FakeSocket(body)
625 resp = client.HTTPResponse(sock)
626 resp.begin()
627 b = bytearray(2)
628 n = resp.readinto(b)
629 self.assertEqual(n, 2)
630 self.assertEqual(bytes(b), b'Te')
631 self.assertFalse(resp.isclosed())
632 n = resp.readinto(b)
633 self.assertEqual(n, 2)
634 self.assertEqual(bytes(b), b'xt')
635 n = resp.readinto(b)
636 self.assertEqual(n, 0)
637 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200638 self.assertFalse(resp.closed)
639 resp.close()
640 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100641
Thomas Wouters89f507f2006-12-13 04:49:30 +0000642 def test_host_port(self):
643 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000644
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200645 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000646 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000648 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
649 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200651 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000652 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200653 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
654 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000655 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000656 self.assertEqual(h, c.host)
657 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000658
Thomas Wouters89f507f2006-12-13 04:49:30 +0000659 def test_response_headers(self):
660 # test response with multiple message headers with the same field name.
661 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000662 'Set-Cookie: Customer="WILE_E_COYOTE"; '
663 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000664 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
665 ' Path="/acme"\r\n'
666 '\r\n'
667 'No body\r\n')
668 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
669 ', '
670 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
671 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000672 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000673 r.begin()
674 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000675 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000676
Thomas Wouters89f507f2006-12-13 04:49:30 +0000677 def test_read_head(self):
678 # Test that the library doesn't attempt to read any data
679 # from a HEAD request. (Tickles SF bug #622042.)
680 sock = FakeSocket(
681 'HTTP/1.1 200 OK\r\n'
682 'Content-Length: 14432\r\n'
683 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300684 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000685 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000686 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000687 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000688 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000689
Antoine Pitrou38d96432011-12-06 22:33:57 +0100690 def test_readinto_head(self):
691 # Test that the library doesn't attempt to read any data
692 # from a HEAD request. (Tickles SF bug #622042.)
693 sock = FakeSocket(
694 'HTTP/1.1 200 OK\r\n'
695 'Content-Length: 14432\r\n'
696 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300697 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100698 resp = client.HTTPResponse(sock, method="HEAD")
699 resp.begin()
700 b = bytearray(5)
701 if resp.readinto(b) != 0:
702 self.fail("Did not expect response from HEAD request")
703 self.assertEqual(bytes(b), b'\x00'*5)
704
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100705 def test_too_many_headers(self):
706 headers = '\r\n'.join('Header%d: foo' % i
707 for i in range(client._MAXHEADERS + 1)) + '\r\n'
708 text = ('HTTP/1.1 200 OK\r\n' + headers)
709 s = FakeSocket(text)
710 r = client.HTTPResponse(s)
711 self.assertRaisesRegex(client.HTTPException,
712 r"got more than \d+ headers", r.begin)
713
Thomas Wouters89f507f2006-12-13 04:49:30 +0000714 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000715 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000716 b'Accept-Encoding: identity\r\n'
717 b'Transfer-Encoding: chunked\r\n'
718 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000719
Brett Cannon77b7de62010-10-29 23:31:11 +0000720 with open(__file__, 'rb') as body:
721 conn = client.HTTPConnection('example.com')
722 sock = FakeSocket(body)
723 conn.sock = sock
724 conn.request('GET', '/foo', body)
725 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
726 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000727
Antoine Pitrouead1d622009-09-29 18:44:53 +0000728 def test_send(self):
729 expected = b'this is a test this is only a test'
730 conn = client.HTTPConnection('example.com')
731 sock = FakeSocket(None)
732 conn.sock = sock
733 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000734 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000735 sock.data = b''
736 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000737 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000738 sock.data = b''
739 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000740 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000741
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300742 def test_send_updating_file(self):
743 def data():
744 yield 'data'
745 yield None
746 yield 'data_two'
747
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000748 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300749 mode = 'r'
750 d = data()
751 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000752 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300753
754 expected = b'data'
755
756 conn = client.HTTPConnection('example.com')
757 sock = FakeSocket("")
758 conn.sock = sock
759 conn.send(UpdatingFile())
760 self.assertEqual(sock.data, expected)
761
762
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000763 def test_send_iter(self):
764 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
765 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
766 b'\r\nonetwothree'
767
768 def body():
769 yield b"one"
770 yield b"two"
771 yield b"three"
772
773 conn = client.HTTPConnection('example.com')
774 sock = FakeSocket("")
775 conn.sock = sock
776 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000777 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000778
Nir Sofferad455cd2017-11-06 23:16:37 +0200779 def test_blocksize_request(self):
780 """Check that request() respects the configured block size."""
781 blocksize = 8 # For easy debugging.
782 conn = client.HTTPConnection('example.com', blocksize=blocksize)
783 sock = FakeSocket(None)
784 conn.sock = sock
785 expected = b"a" * blocksize + b"b"
786 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
787 self.assertEqual(sock.sendall_calls, 3)
788 body = sock.data.split(b"\r\n\r\n", 1)[1]
789 self.assertEqual(body, expected)
790
791 def test_blocksize_send(self):
792 """Check that send() respects the configured block size."""
793 blocksize = 8 # For easy debugging.
794 conn = client.HTTPConnection('example.com', blocksize=blocksize)
795 sock = FakeSocket(None)
796 conn.sock = sock
797 expected = b"a" * blocksize + b"b"
798 conn.send(io.BytesIO(expected))
799 self.assertEqual(sock.sendall_calls, 2)
800 self.assertEqual(sock.data, expected)
801
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800802 def test_send_type_error(self):
803 # See: Issue #12676
804 conn = client.HTTPConnection('example.com')
805 conn.sock = FakeSocket('')
806 with self.assertRaises(TypeError):
807 conn.request('POST', 'test', conn)
808
Christian Heimesa612dc02008-02-24 13:08:18 +0000809 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000810 expected = chunked_expected
811 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000812 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000813 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100814 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000815 resp.close()
816
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100817 # Various read sizes
818 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000819 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100820 resp = client.HTTPResponse(sock, method="GET")
821 resp.begin()
822 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
823 resp.close()
824
Christian Heimesa612dc02008-02-24 13:08:18 +0000825 for x in ('', 'foo\r\n'):
826 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000827 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000828 resp.begin()
829 try:
830 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000831 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100832 self.assertEqual(i.partial, expected)
833 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
834 self.assertEqual(repr(i), expected_message)
835 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000836 else:
837 self.fail('IncompleteRead expected')
838 finally:
839 resp.close()
840
Antoine Pitrou38d96432011-12-06 22:33:57 +0100841 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000842
843 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100844 nexpected = len(expected)
845 b = bytearray(128)
846
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000847 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100848 resp = client.HTTPResponse(sock, method="GET")
849 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100850 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100851 self.assertEqual(b[:nexpected], expected)
852 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100853 resp.close()
854
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100855 # Various read sizes
856 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000857 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100858 resp = client.HTTPResponse(sock, method="GET")
859 resp.begin()
860 m = memoryview(b)
861 i = resp.readinto(m[0:n])
862 i += resp.readinto(m[i:n + i])
863 i += resp.readinto(m[i:])
864 self.assertEqual(b[:nexpected], expected)
865 self.assertEqual(i, nexpected)
866 resp.close()
867
Antoine Pitrou38d96432011-12-06 22:33:57 +0100868 for x in ('', 'foo\r\n'):
869 sock = FakeSocket(chunked_start + x)
870 resp = client.HTTPResponse(sock, method="GET")
871 resp.begin()
872 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100873 n = resp.readinto(b)
874 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100875 self.assertEqual(i.partial, expected)
876 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
877 self.assertEqual(repr(i), expected_message)
878 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100879 else:
880 self.fail('IncompleteRead expected')
881 finally:
882 resp.close()
883
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000884 def test_chunked_head(self):
885 chunked_start = (
886 'HTTP/1.1 200 OK\r\n'
887 'Transfer-Encoding: chunked\r\n\r\n'
888 'a\r\n'
889 'hello world\r\n'
890 '1\r\n'
891 'd\r\n'
892 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000893 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000894 resp = client.HTTPResponse(sock, method="HEAD")
895 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000896 self.assertEqual(resp.read(), b'')
897 self.assertEqual(resp.status, 200)
898 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000899 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200900 self.assertFalse(resp.closed)
901 resp.close()
902 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000903
Antoine Pitrou38d96432011-12-06 22:33:57 +0100904 def test_readinto_chunked_head(self):
905 chunked_start = (
906 'HTTP/1.1 200 OK\r\n'
907 'Transfer-Encoding: chunked\r\n\r\n'
908 'a\r\n'
909 'hello world\r\n'
910 '1\r\n'
911 'd\r\n'
912 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000913 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100914 resp = client.HTTPResponse(sock, method="HEAD")
915 resp.begin()
916 b = bytearray(5)
917 n = resp.readinto(b)
918 self.assertEqual(n, 0)
919 self.assertEqual(bytes(b), b'\x00'*5)
920 self.assertEqual(resp.status, 200)
921 self.assertEqual(resp.reason, 'OK')
922 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200923 self.assertFalse(resp.closed)
924 resp.close()
925 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100926
Christian Heimesa612dc02008-02-24 13:08:18 +0000927 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000928 sock = FakeSocket(
929 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000930 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000931 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000932 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100933 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000934
Benjamin Peterson6accb982009-03-02 22:50:25 +0000935 def test_incomplete_read(self):
936 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000937 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000938 resp.begin()
939 try:
940 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000941 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000942 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000943 self.assertEqual(repr(i),
944 "IncompleteRead(7 bytes read, 3 more expected)")
945 self.assertEqual(str(i),
946 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100947 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000948 else:
949 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000950
Jeremy Hylton636950f2009-03-28 04:34:21 +0000951 def test_epipe(self):
952 sock = EPipeSocket(
953 "HTTP/1.0 401 Authorization Required\r\n"
954 "Content-type: text/html\r\n"
955 "WWW-Authenticate: Basic realm=\"example\"\r\n",
956 b"Content-Length")
957 conn = client.HTTPConnection("example.com")
958 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200959 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000960 lambda: conn.request("PUT", "/url", "body"))
961 resp = conn.getresponse()
962 self.assertEqual(401, resp.status)
963 self.assertEqual("Basic realm=\"example\"",
964 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000965
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000966 # Test lines overflowing the max line size (_MAXLINE in http.client)
967
968 def test_overflowing_status_line(self):
969 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
970 resp = client.HTTPResponse(FakeSocket(body))
971 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
972
973 def test_overflowing_header_line(self):
974 body = (
975 'HTTP/1.1 200 OK\r\n'
976 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
977 )
978 resp = client.HTTPResponse(FakeSocket(body))
979 self.assertRaises(client.LineTooLong, resp.begin)
980
981 def test_overflowing_chunked_line(self):
982 body = (
983 'HTTP/1.1 200 OK\r\n'
984 'Transfer-Encoding: chunked\r\n\r\n'
985 + '0' * 65536 + 'a\r\n'
986 'hello world\r\n'
987 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000988 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000989 )
990 resp = client.HTTPResponse(FakeSocket(body))
991 resp.begin()
992 self.assertRaises(client.LineTooLong, resp.read)
993
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800994 def test_early_eof(self):
995 # Test httpresponse with no \r\n termination,
996 body = "HTTP/1.1 200 Ok"
997 sock = FakeSocket(body)
998 resp = client.HTTPResponse(sock)
999 resp.begin()
1000 self.assertEqual(resp.read(), b'')
1001 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001002 self.assertFalse(resp.closed)
1003 resp.close()
1004 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001005
Serhiy Storchakab491e052014-12-01 13:07:45 +02001006 def test_error_leak(self):
1007 # Test that the socket is not leaked if getresponse() fails
1008 conn = client.HTTPConnection('example.com')
1009 response = None
1010 class Response(client.HTTPResponse):
1011 def __init__(self, *pos, **kw):
1012 nonlocal response
1013 response = self # Avoid garbage collector closing the socket
1014 client.HTTPResponse.__init__(self, *pos, **kw)
1015 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001016 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001017 conn.request('GET', '/')
1018 self.assertRaises(client.BadStatusLine, conn.getresponse)
1019 self.assertTrue(response.closed)
1020 self.assertTrue(conn.sock.file_closed)
1021
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001022 def test_chunked_extension(self):
1023 extra = '3;foo=bar\r\n' + 'abc\r\n'
1024 expected = chunked_expected + b'abc'
1025
1026 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1027 resp = client.HTTPResponse(sock, method="GET")
1028 resp.begin()
1029 self.assertEqual(resp.read(), expected)
1030 resp.close()
1031
1032 def test_chunked_missing_end(self):
1033 """some servers may serve up a short chunked encoding stream"""
1034 expected = chunked_expected
1035 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1036 resp = client.HTTPResponse(sock, method="GET")
1037 resp.begin()
1038 self.assertEqual(resp.read(), expected)
1039 resp.close()
1040
1041 def test_chunked_trailers(self):
1042 """See that trailers are read and ignored"""
1043 expected = chunked_expected
1044 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1045 resp = client.HTTPResponse(sock, method="GET")
1046 resp.begin()
1047 self.assertEqual(resp.read(), expected)
1048 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001049 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001050 resp.close()
1051
1052 def test_chunked_sync(self):
1053 """Check that we don't read past the end of the chunked-encoding stream"""
1054 expected = chunked_expected
1055 extradata = "extradata"
1056 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1057 resp = client.HTTPResponse(sock, method="GET")
1058 resp.begin()
1059 self.assertEqual(resp.read(), expected)
1060 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001061 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001062 resp.close()
1063
1064 def test_content_length_sync(self):
1065 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001066 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001067 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001068 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 +00001069 resp = client.HTTPResponse(sock, method="GET")
1070 resp.begin()
1071 self.assertEqual(resp.read(), expected)
1072 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001073 self.assertEqual(sock.file.read(), extradata) #we read to the end
1074 resp.close()
1075
1076 def test_readlines_content_length(self):
1077 extradata = b"extradata"
1078 expected = b"Hello123\r\n"
1079 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1080 resp = client.HTTPResponse(sock, method="GET")
1081 resp.begin()
1082 self.assertEqual(resp.readlines(2000), [expected])
1083 # the file should now have our extradata ready to be read
1084 self.assertEqual(sock.file.read(), extradata) #we read to the end
1085 resp.close()
1086
1087 def test_read1_content_length(self):
1088 extradata = b"extradata"
1089 expected = b"Hello123\r\n"
1090 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1091 resp = client.HTTPResponse(sock, method="GET")
1092 resp.begin()
1093 self.assertEqual(resp.read1(2000), expected)
1094 # the file should now have our extradata ready to be read
1095 self.assertEqual(sock.file.read(), extradata) #we read to the end
1096 resp.close()
1097
1098 def test_readline_bound_content_length(self):
1099 extradata = b"extradata"
1100 expected = b"Hello123\r\n"
1101 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1102 resp = client.HTTPResponse(sock, method="GET")
1103 resp.begin()
1104 self.assertEqual(resp.readline(10), expected)
1105 self.assertEqual(resp.readline(10), b"")
1106 # the file should now have our extradata ready to be read
1107 self.assertEqual(sock.file.read(), extradata) #we read to the end
1108 resp.close()
1109
1110 def test_read1_bound_content_length(self):
1111 extradata = b"extradata"
1112 expected = b"Hello123\r\n"
1113 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1114 resp = client.HTTPResponse(sock, method="GET")
1115 resp.begin()
1116 self.assertEqual(resp.read1(20), expected*2)
1117 self.assertEqual(resp.read(), expected)
1118 # the file should now have our extradata ready to be read
1119 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001120 resp.close()
1121
Martin Panterd979b2c2016-04-09 14:03:17 +00001122 def test_response_fileno(self):
1123 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001124 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001125 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001126
1127 result = None
1128 def run_server():
1129 [conn, address] = serv.accept()
1130 with conn, conn.makefile("rb") as reader:
1131 # Read the request header until a blank line
1132 while True:
1133 line = reader.readline()
1134 if not line.rstrip(b"\r\n"):
1135 break
1136 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1137 nonlocal result
1138 result = reader.read()
1139
1140 thread = threading.Thread(target=run_server)
1141 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001142 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001143 conn = client.HTTPConnection(*serv.getsockname())
1144 conn.request("CONNECT", "dummy:1234")
1145 response = conn.getresponse()
1146 try:
1147 self.assertEqual(response.status, client.OK)
1148 s = socket.socket(fileno=response.fileno())
1149 try:
1150 s.sendall(b"proxied data\n")
1151 finally:
1152 s.detach()
1153 finally:
1154 response.close()
1155 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001156 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001157 self.assertEqual(result, b"proxied data\n")
1158
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001159 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001160 """
1161 It should be possible to override the default validation
1162 behavior in putrequest (bpo-38216).
1163 """
1164 class UnsafeHTTPConnection(client.HTTPConnection):
1165 def _validate_path(self, url):
1166 pass
1167
1168 conn = UnsafeHTTPConnection('example.com')
1169 conn.sock = FakeSocket('')
1170 conn.putrequest('GET', '/\x00')
1171
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001172 def test_putrequest_override_host_validation(self):
1173 class UnsafeHTTPConnection(client.HTTPConnection):
1174 def _validate_host(self, url):
1175 pass
1176
1177 conn = UnsafeHTTPConnection('example.com\r\n')
1178 conn.sock = FakeSocket('')
1179 # set skip_host so a ValueError is not raised upon adding the
1180 # invalid URL as the value of the "Host:" header
1181 conn.putrequest('GET', '/', skip_host=1)
1182
Jason R. Coombs7774d782019-09-28 08:32:01 -04001183 def test_putrequest_override_encoding(self):
1184 """
1185 It should be possible to override the default encoding
1186 to transmit bytes in another encoding even if invalid
1187 (bpo-36274).
1188 """
1189 class UnsafeHTTPConnection(client.HTTPConnection):
1190 def _encode_request(self, str_url):
1191 return str_url.encode('utf-8')
1192
1193 conn = UnsafeHTTPConnection('example.com')
1194 conn.sock = FakeSocket('')
1195 conn.putrequest('GET', '/☃')
1196
1197
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001198class ExtendedReadTest(TestCase):
1199 """
1200 Test peek(), read1(), readline()
1201 """
1202 lines = (
1203 'HTTP/1.1 200 OK\r\n'
1204 '\r\n'
1205 'hello world!\n'
1206 'and now \n'
1207 'for something completely different\n'
1208 'foo'
1209 )
1210 lines_expected = lines[lines.find('hello'):].encode("ascii")
1211 lines_chunked = (
1212 'HTTP/1.1 200 OK\r\n'
1213 'Transfer-Encoding: chunked\r\n\r\n'
1214 'a\r\n'
1215 'hello worl\r\n'
1216 '3\r\n'
1217 'd!\n\r\n'
1218 '9\r\n'
1219 'and now \n\r\n'
1220 '23\r\n'
1221 'for something completely different\n\r\n'
1222 '3\r\n'
1223 'foo\r\n'
1224 '0\r\n' # terminating chunk
1225 '\r\n' # end of trailers
1226 )
1227
1228 def setUp(self):
1229 sock = FakeSocket(self.lines)
1230 resp = client.HTTPResponse(sock, method="GET")
1231 resp.begin()
1232 resp.fp = io.BufferedReader(resp.fp)
1233 self.resp = resp
1234
1235
1236
1237 def test_peek(self):
1238 resp = self.resp
1239 # patch up the buffered peek so that it returns not too much stuff
1240 oldpeek = resp.fp.peek
1241 def mypeek(n=-1):
1242 p = oldpeek(n)
1243 if n >= 0:
1244 return p[:n]
1245 return p[:10]
1246 resp.fp.peek = mypeek
1247
1248 all = []
1249 while True:
1250 # try a short peek
1251 p = resp.peek(3)
1252 if p:
1253 self.assertGreater(len(p), 0)
1254 # then unbounded peek
1255 p2 = resp.peek()
1256 self.assertGreaterEqual(len(p2), len(p))
1257 self.assertTrue(p2.startswith(p))
1258 next = resp.read(len(p2))
1259 self.assertEqual(next, p2)
1260 else:
1261 next = resp.read()
1262 self.assertFalse(next)
1263 all.append(next)
1264 if not next:
1265 break
1266 self.assertEqual(b"".join(all), self.lines_expected)
1267
1268 def test_readline(self):
1269 resp = self.resp
1270 self._verify_readline(self.resp.readline, self.lines_expected)
1271
1272 def _verify_readline(self, readline, expected):
1273 all = []
1274 while True:
1275 # short readlines
1276 line = readline(5)
1277 if line and line != b"foo":
1278 if len(line) < 5:
1279 self.assertTrue(line.endswith(b"\n"))
1280 all.append(line)
1281 if not line:
1282 break
1283 self.assertEqual(b"".join(all), expected)
1284
1285 def test_read1(self):
1286 resp = self.resp
1287 def r():
1288 res = resp.read1(4)
1289 self.assertLessEqual(len(res), 4)
1290 return res
1291 readliner = Readliner(r)
1292 self._verify_readline(readliner.readline, self.lines_expected)
1293
1294 def test_read1_unbounded(self):
1295 resp = self.resp
1296 all = []
1297 while True:
1298 data = resp.read1()
1299 if not data:
1300 break
1301 all.append(data)
1302 self.assertEqual(b"".join(all), self.lines_expected)
1303
1304 def test_read1_bounded(self):
1305 resp = self.resp
1306 all = []
1307 while True:
1308 data = resp.read1(10)
1309 if not data:
1310 break
1311 self.assertLessEqual(len(data), 10)
1312 all.append(data)
1313 self.assertEqual(b"".join(all), self.lines_expected)
1314
1315 def test_read1_0(self):
1316 self.assertEqual(self.resp.read1(0), b"")
1317
1318 def test_peek_0(self):
1319 p = self.resp.peek(0)
1320 self.assertLessEqual(0, len(p))
1321
Jason R. Coombs7774d782019-09-28 08:32:01 -04001322
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001323class ExtendedReadTestChunked(ExtendedReadTest):
1324 """
1325 Test peek(), read1(), readline() in chunked mode
1326 """
1327 lines = (
1328 'HTTP/1.1 200 OK\r\n'
1329 'Transfer-Encoding: chunked\r\n\r\n'
1330 'a\r\n'
1331 'hello worl\r\n'
1332 '3\r\n'
1333 'd!\n\r\n'
1334 '9\r\n'
1335 'and now \n\r\n'
1336 '23\r\n'
1337 'for something completely different\n\r\n'
1338 '3\r\n'
1339 'foo\r\n'
1340 '0\r\n' # terminating chunk
1341 '\r\n' # end of trailers
1342 )
1343
1344
1345class Readliner:
1346 """
1347 a simple readline class that uses an arbitrary read function and buffering
1348 """
1349 def __init__(self, readfunc):
1350 self.readfunc = readfunc
1351 self.remainder = b""
1352
1353 def readline(self, limit):
1354 data = []
1355 datalen = 0
1356 read = self.remainder
1357 try:
1358 while True:
1359 idx = read.find(b'\n')
1360 if idx != -1:
1361 break
1362 if datalen + len(read) >= limit:
1363 idx = limit - datalen - 1
1364 # read more data
1365 data.append(read)
1366 read = self.readfunc()
1367 if not read:
1368 idx = 0 #eof condition
1369 break
1370 idx += 1
1371 data.append(read[:idx])
1372 self.remainder = read[idx:]
1373 return b"".join(data)
1374 except:
1375 self.remainder = b"".join(data)
1376 raise
1377
Berker Peksagbabc6882015-02-20 09:39:38 +02001378
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001379class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001380 def test_all(self):
1381 # Documented objects defined in the module should be in __all__
1382 expected = {"responses"} # White-list documented dict() object
1383 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1384 # intentionally omitted for simplicity
1385 blacklist = {"HTTPMessage", "parse_headers"}
1386 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001387 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001388 continue
1389 module_object = getattr(client, name)
1390 if getattr(module_object, "__module__", None) == "http.client":
1391 expected.add(name)
1392 self.assertCountEqual(client.__all__, expected)
1393
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001394 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001395 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001396
Berker Peksagabbf0f42015-02-20 14:57:31 +02001397 def test_client_constants(self):
1398 # Make sure we don't break backward compatibility with 3.4
1399 expected = [
1400 'CONTINUE',
1401 'SWITCHING_PROTOCOLS',
1402 'PROCESSING',
1403 'OK',
1404 'CREATED',
1405 'ACCEPTED',
1406 'NON_AUTHORITATIVE_INFORMATION',
1407 'NO_CONTENT',
1408 'RESET_CONTENT',
1409 'PARTIAL_CONTENT',
1410 'MULTI_STATUS',
1411 'IM_USED',
1412 'MULTIPLE_CHOICES',
1413 'MOVED_PERMANENTLY',
1414 'FOUND',
1415 'SEE_OTHER',
1416 'NOT_MODIFIED',
1417 'USE_PROXY',
1418 'TEMPORARY_REDIRECT',
1419 'BAD_REQUEST',
1420 'UNAUTHORIZED',
1421 'PAYMENT_REQUIRED',
1422 'FORBIDDEN',
1423 'NOT_FOUND',
1424 'METHOD_NOT_ALLOWED',
1425 'NOT_ACCEPTABLE',
1426 'PROXY_AUTHENTICATION_REQUIRED',
1427 'REQUEST_TIMEOUT',
1428 'CONFLICT',
1429 'GONE',
1430 'LENGTH_REQUIRED',
1431 'PRECONDITION_FAILED',
1432 'REQUEST_ENTITY_TOO_LARGE',
1433 'REQUEST_URI_TOO_LONG',
1434 'UNSUPPORTED_MEDIA_TYPE',
1435 'REQUESTED_RANGE_NOT_SATISFIABLE',
1436 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001437 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001438 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001439 'UNPROCESSABLE_ENTITY',
1440 'LOCKED',
1441 'FAILED_DEPENDENCY',
1442 'UPGRADE_REQUIRED',
1443 'PRECONDITION_REQUIRED',
1444 'TOO_MANY_REQUESTS',
1445 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001446 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001447 'INTERNAL_SERVER_ERROR',
1448 'NOT_IMPLEMENTED',
1449 'BAD_GATEWAY',
1450 'SERVICE_UNAVAILABLE',
1451 'GATEWAY_TIMEOUT',
1452 'HTTP_VERSION_NOT_SUPPORTED',
1453 'INSUFFICIENT_STORAGE',
1454 'NOT_EXTENDED',
1455 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001456 'EARLY_HINTS',
1457 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001458 ]
1459 for const in expected:
1460 with self.subTest(constant=const):
1461 self.assertTrue(hasattr(client, const))
1462
Gregory P. Smithb4066372010-01-03 03:28:29 +00001463
1464class SourceAddressTest(TestCase):
1465 def setUp(self):
1466 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001467 self.port = socket_helper.bind_port(self.serv)
1468 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001469 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001470 self.conn = None
1471
1472 def tearDown(self):
1473 if self.conn:
1474 self.conn.close()
1475 self.conn = None
1476 self.serv.close()
1477 self.serv = None
1478
1479 def testHTTPConnectionSourceAddress(self):
1480 self.conn = client.HTTPConnection(HOST, self.port,
1481 source_address=('', self.source_port))
1482 self.conn.connect()
1483 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1484
1485 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1486 'http.client.HTTPSConnection not defined')
1487 def testHTTPSConnectionSourceAddress(self):
1488 self.conn = client.HTTPSConnection(HOST, self.port,
1489 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001490 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001491 # this code doesn't deal with setting up an active running SSL server
1492 # for an ssl_wrapped connect() to actually return from.
1493
1494
Guido van Rossumd8faa362007-04-27 19:54:29 +00001495class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001496 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001497
1498 def setUp(self):
1499 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001500 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001501 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001502
1503 def tearDown(self):
1504 self.serv.close()
1505 self.serv = None
1506
1507 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001508 # This will prove that the timeout gets through HTTPConnection
1509 # and into the socket.
1510
Georg Brandlf78e02b2008-06-10 17:40:04 +00001511 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001512 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001513 socket.setdefaulttimeout(30)
1514 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001515 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001516 httpConn.connect()
1517 finally:
1518 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001519 self.assertEqual(httpConn.sock.gettimeout(), 30)
1520 httpConn.close()
1521
Georg Brandlf78e02b2008-06-10 17:40:04 +00001522 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001523 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001524 socket.setdefaulttimeout(30)
1525 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001526 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001527 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001528 httpConn.connect()
1529 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001530 socket.setdefaulttimeout(None)
1531 self.assertEqual(httpConn.sock.gettimeout(), None)
1532 httpConn.close()
1533
1534 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001535 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001536 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001537 self.assertEqual(httpConn.sock.gettimeout(), 30)
1538 httpConn.close()
1539
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001540
R David Murraycae7bdb2015-04-05 19:26:29 -04001541class PersistenceTest(TestCase):
1542
1543 def test_reuse_reconnect(self):
1544 # Should reuse or reconnect depending on header from server
1545 tests = (
1546 ('1.0', '', False),
1547 ('1.0', 'Connection: keep-alive\r\n', True),
1548 ('1.1', '', True),
1549 ('1.1', 'Connection: close\r\n', False),
1550 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1551 ('1.1', 'Connection: cloSE\r\n', False),
1552 )
1553 for version, header, reuse in tests:
1554 with self.subTest(version=version, header=header):
1555 msg = (
1556 'HTTP/{} 200 OK\r\n'
1557 '{}'
1558 'Content-Length: 12\r\n'
1559 '\r\n'
1560 'Dummy body\r\n'
1561 ).format(version, header)
1562 conn = FakeSocketHTTPConnection(msg)
1563 self.assertIsNone(conn.sock)
1564 conn.request('GET', '/open-connection')
1565 with conn.getresponse() as response:
1566 self.assertEqual(conn.sock is None, not reuse)
1567 response.read()
1568 self.assertEqual(conn.sock is None, not reuse)
1569 self.assertEqual(conn.connections, 1)
1570 conn.request('GET', '/subsequent-request')
1571 self.assertEqual(conn.connections, 1 if reuse else 2)
1572
1573 def test_disconnected(self):
1574
1575 def make_reset_reader(text):
1576 """Return BufferedReader that raises ECONNRESET at EOF"""
1577 stream = io.BytesIO(text)
1578 def readinto(buffer):
1579 size = io.BytesIO.readinto(stream, buffer)
1580 if size == 0:
1581 raise ConnectionResetError()
1582 return size
1583 stream.readinto = readinto
1584 return io.BufferedReader(stream)
1585
1586 tests = (
1587 (io.BytesIO, client.RemoteDisconnected),
1588 (make_reset_reader, ConnectionResetError),
1589 )
1590 for stream_factory, exception in tests:
1591 with self.subTest(exception=exception):
1592 conn = FakeSocketHTTPConnection(b'', stream_factory)
1593 conn.request('GET', '/eof-response')
1594 self.assertRaises(exception, conn.getresponse)
1595 self.assertIsNone(conn.sock)
1596 # HTTPConnection.connect() should be automatically invoked
1597 conn.request('GET', '/reconnect')
1598 self.assertEqual(conn.connections, 2)
1599
1600 def test_100_close(self):
1601 conn = FakeSocketHTTPConnection(
1602 b'HTTP/1.1 100 Continue\r\n'
1603 b'\r\n'
1604 # Missing final response
1605 )
1606 conn.request('GET', '/', headers={'Expect': '100-continue'})
1607 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1608 self.assertIsNone(conn.sock)
1609 conn.request('GET', '/reconnect')
1610 self.assertEqual(conn.connections, 2)
1611
1612
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001613class HTTPSTest(TestCase):
1614
1615 def setUp(self):
1616 if not hasattr(client, 'HTTPSConnection'):
1617 self.skipTest('ssl support required')
1618
1619 def make_server(self, certfile):
1620 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001621 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001622
1623 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001624 # simple test to check it's storing the timeout
1625 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1626 self.assertEqual(h.timeout, 30)
1627
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001628 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001629 # Default settings: requires a valid cert from a trusted CA
1630 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001631 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001632 with support.transient_internet('self-signed.pythontest.net'):
1633 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1634 with self.assertRaises(ssl.SSLError) as exc_info:
1635 h.request('GET', '/')
1636 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1637
1638 def test_networked_noverification(self):
1639 # Switch off cert verification
1640 import ssl
1641 support.requires('network')
1642 with support.transient_internet('self-signed.pythontest.net'):
1643 context = ssl._create_unverified_context()
1644 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1645 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001646 h.request('GET', '/')
1647 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001648 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001649 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001650 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001651
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001652 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001653 def test_networked_trusted_by_default_cert(self):
1654 # Default settings: requires a valid cert from a trusted CA
1655 support.requires('network')
1656 with support.transient_internet('www.python.org'):
1657 h = client.HTTPSConnection('www.python.org', 443)
1658 h.request('GET', '/')
1659 resp = h.getresponse()
1660 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001661 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001662 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001663 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001664
1665 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001666 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001667 import ssl
1668 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001669 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
1670 with support.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001671 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1672 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1673 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001674 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001675 try:
1676 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1677 context=context)
1678 h.request('GET', '/')
1679 resp = h.getresponse()
1680 except ssl.SSLError as ssl_err:
1681 ssl_err_str = str(ssl_err)
1682 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1683 # modern Linux distros (Debian Buster, etc) default OpenSSL
1684 # configurations it'll fail saying "key too weak" until we
1685 # address https://bugs.python.org/issue36816 to use a proper
1686 # key size on self-signed.pythontest.net.
1687 if re.search(r'(?i)key.too.weak', ssl_err_str):
1688 raise unittest.SkipTest(
1689 f'Got {ssl_err_str} trying to connect '
1690 f'to {selfsigned_pythontestdotnet}. '
1691 'See https://bugs.python.org/issue36816.')
1692 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001693 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001694 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001695 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001696 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001697
1698 def test_networked_bad_cert(self):
1699 # We feed a "CA" cert that is unrelated to the server's cert
1700 import ssl
1701 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001702 with support.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001703 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001704 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001705 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1706 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001707 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001708 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1709
1710 def test_local_unknown_cert(self):
1711 # The custom cert isn't known to the default trust bundle
1712 import ssl
1713 server = self.make_server(CERT_localhost)
1714 h = client.HTTPSConnection('localhost', server.port)
1715 with self.assertRaises(ssl.SSLError) as exc_info:
1716 h.request('GET', '/')
1717 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001718
1719 def test_local_good_hostname(self):
1720 # The (valid) cert validates the HTTP hostname
1721 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001722 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001723 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001724 context.load_verify_locations(CERT_localhost)
1725 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001726 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001727 h.request('GET', '/nonexistent')
1728 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001729 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001730 self.assertEqual(resp.status, 404)
1731
1732 def test_local_bad_hostname(self):
1733 # The (valid) cert doesn't validate the HTTP hostname
1734 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001735 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001736 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001737 context.load_verify_locations(CERT_fakehostname)
1738 h = client.HTTPSConnection('localhost', server.port, context=context)
1739 with self.assertRaises(ssl.CertificateError):
1740 h.request('GET', '/')
1741 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001742 with support.check_warnings(('', DeprecationWarning)):
1743 h = client.HTTPSConnection('localhost', server.port,
1744 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001745 with self.assertRaises(ssl.CertificateError):
1746 h.request('GET', '/')
1747 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001748 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001749 with support.check_warnings(('', DeprecationWarning)):
1750 h = client.HTTPSConnection('localhost', server.port,
1751 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001752 h.request('GET', '/nonexistent')
1753 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001754 resp.close()
1755 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001756 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001757 # The context's check_hostname setting is used if one isn't passed to
1758 # HTTPSConnection.
1759 context.check_hostname = False
1760 h = client.HTTPSConnection('localhost', server.port, context=context)
1761 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001762 resp = h.getresponse()
1763 self.assertEqual(resp.status, 404)
1764 resp.close()
1765 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001766 # Passing check_hostname to HTTPSConnection should override the
1767 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001768 with support.check_warnings(('', DeprecationWarning)):
1769 h = client.HTTPSConnection('localhost', server.port,
1770 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001771 with self.assertRaises(ssl.CertificateError):
1772 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001773
Petri Lehtinene119c402011-10-26 21:29:15 +03001774 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1775 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001776 def test_host_port(self):
1777 # Check invalid host_port
1778
1779 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1780 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1781
1782 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1783 "fe80::207:e9ff:fe9b", 8000),
1784 ("www.python.org:443", "www.python.org", 443),
1785 ("www.python.org:", "www.python.org", 443),
1786 ("www.python.org", "www.python.org", 443),
1787 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1788 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1789 443)):
1790 c = client.HTTPSConnection(hp)
1791 self.assertEqual(h, c.host)
1792 self.assertEqual(p, c.port)
1793
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001794 def test_tls13_pha(self):
1795 import ssl
1796 if not ssl.HAS_TLSv1_3:
1797 self.skipTest('TLS 1.3 support required')
1798 # just check status of PHA flag
1799 h = client.HTTPSConnection('localhost', 443)
1800 self.assertTrue(h._context.post_handshake_auth)
1801
1802 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1803 self.assertFalse(context.post_handshake_auth)
1804 h = client.HTTPSConnection('localhost', 443, context=context)
1805 self.assertIs(h._context, context)
1806 self.assertFalse(h._context.post_handshake_auth)
1807
Pablo Galindoaa542c22019-08-08 23:25:46 +01001808 with warnings.catch_warnings():
1809 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1810 DeprecationWarning)
1811 h = client.HTTPSConnection('localhost', 443, context=context,
1812 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001813 self.assertTrue(h._context.post_handshake_auth)
1814
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001815
Jeremy Hylton236654b2009-03-27 20:24:34 +00001816class RequestBodyTest(TestCase):
1817 """Test cases where a request includes a message body."""
1818
1819 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001820 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001821 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001822 self.conn.sock = self.sock
1823
1824 def get_headers_and_fp(self):
1825 f = io.BytesIO(self.sock.data)
1826 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001827 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001828 return message, f
1829
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001830 def test_list_body(self):
1831 # Note that no content-length is automatically calculated for
1832 # an iterable. The request will fall back to send chunked
1833 # transfer encoding.
1834 cases = (
1835 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1836 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1837 )
1838 for body, expected in cases:
1839 with self.subTest(body):
1840 self.conn = client.HTTPConnection('example.com')
1841 self.conn.sock = self.sock = FakeSocket('')
1842
1843 self.conn.request('PUT', '/url', body)
1844 msg, f = self.get_headers_and_fp()
1845 self.assertNotIn('Content-Type', msg)
1846 self.assertNotIn('Content-Length', msg)
1847 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1848 self.assertEqual(expected, f.read())
1849
Jeremy Hylton236654b2009-03-27 20:24:34 +00001850 def test_manual_content_length(self):
1851 # Set an incorrect content-length so that we can verify that
1852 # it will not be over-ridden by the library.
1853 self.conn.request("PUT", "/url", "body",
1854 {"Content-Length": "42"})
1855 message, f = self.get_headers_and_fp()
1856 self.assertEqual("42", message.get("content-length"))
1857 self.assertEqual(4, len(f.read()))
1858
1859 def test_ascii_body(self):
1860 self.conn.request("PUT", "/url", "body")
1861 message, f = self.get_headers_and_fp()
1862 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001863 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001864 self.assertEqual("4", message.get("content-length"))
1865 self.assertEqual(b'body', f.read())
1866
1867 def test_latin1_body(self):
1868 self.conn.request("PUT", "/url", "body\xc1")
1869 message, f = self.get_headers_and_fp()
1870 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001871 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001872 self.assertEqual("5", message.get("content-length"))
1873 self.assertEqual(b'body\xc1', f.read())
1874
1875 def test_bytes_body(self):
1876 self.conn.request("PUT", "/url", b"body\xc1")
1877 message, f = self.get_headers_and_fp()
1878 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001879 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001880 self.assertEqual("5", message.get("content-length"))
1881 self.assertEqual(b'body\xc1', f.read())
1882
Martin Panteref91bb22016-08-27 01:39:26 +00001883 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001884 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001885 with open(support.TESTFN, "w") as f:
1886 f.write("body")
1887 with open(support.TESTFN) as f:
1888 self.conn.request("PUT", "/url", f)
1889 message, f = self.get_headers_and_fp()
1890 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001891 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001892 # No content-length will be determined for files; the body
1893 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001894 self.assertIsNone(message.get("content-length"))
1895 self.assertEqual("chunked", message.get("transfer-encoding"))
1896 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001897
1898 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001899 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001900 with open(support.TESTFN, "wb") as f:
1901 f.write(b"body\xc1")
1902 with open(support.TESTFN, "rb") as f:
1903 self.conn.request("PUT", "/url", f)
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())
Martin Panteref91bb22016-08-27 01:39:26 +00001907 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1908 self.assertNotIn("Content-Length", message)
1909 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001910
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001911
1912class HTTPResponseTest(TestCase):
1913
1914 def setUp(self):
1915 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1916 second-value\r\n\r\nText"
1917 sock = FakeSocket(body)
1918 self.resp = client.HTTPResponse(sock)
1919 self.resp.begin()
1920
1921 def test_getting_header(self):
1922 header = self.resp.getheader('My-Header')
1923 self.assertEqual(header, 'first-value, second-value')
1924
1925 header = self.resp.getheader('My-Header', 'some default')
1926 self.assertEqual(header, 'first-value, second-value')
1927
1928 def test_getting_nonexistent_header_with_string_default(self):
1929 header = self.resp.getheader('No-Such-Header', 'default-value')
1930 self.assertEqual(header, 'default-value')
1931
1932 def test_getting_nonexistent_header_with_iterable_default(self):
1933 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1934 self.assertEqual(header, 'default, values')
1935
1936 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1937 self.assertEqual(header, 'default, values')
1938
1939 def test_getting_nonexistent_header_without_default(self):
1940 header = self.resp.getheader('No-Such-Header')
1941 self.assertEqual(header, None)
1942
1943 def test_getting_header_defaultint(self):
1944 header = self.resp.getheader('No-Such-Header',default=42)
1945 self.assertEqual(header, 42)
1946
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001947class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001948 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001949 response_text = (
1950 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1951 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1952 'Content-Length: 42\r\n\r\n'
1953 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001954 self.host = 'proxy.com'
1955 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001956 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001957
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001958 def tearDown(self):
1959 self.conn.close()
1960
Berker Peksagab53ab02015-02-03 12:22:11 +02001961 def _create_connection(self, response_text):
1962 def create_connection(address, timeout=None, source_address=None):
1963 return FakeSocket(response_text, host=address[0], port=address[1])
1964 return create_connection
1965
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001966 def test_set_tunnel_host_port_headers(self):
1967 tunnel_host = 'destination.com'
1968 tunnel_port = 8888
1969 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1970 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1971 headers=tunnel_headers)
1972 self.conn.request('HEAD', '/', '')
1973 self.assertEqual(self.conn.sock.host, self.host)
1974 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1975 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1976 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1977 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1978
1979 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001980 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001981 self.conn.connect()
1982 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001983 'destination.com')
1984
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001985 def test_connect_with_tunnel(self):
1986 self.conn.set_tunnel('destination.com')
1987 self.conn.request('HEAD', '/', '')
1988 self.assertEqual(self.conn.sock.host, self.host)
1989 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1990 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001991 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001992 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1993 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001994
1995 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001996 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001997
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001998 def test_connect_put_request(self):
1999 self.conn.set_tunnel('destination.com')
2000 self.conn.request('PUT', '/', '')
2001 self.assertEqual(self.conn.sock.host, self.host)
2002 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2003 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2004 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2005
Berker Peksagab53ab02015-02-03 12:22:11 +02002006 def test_tunnel_debuglog(self):
2007 expected_header = 'X-Dummy: 1'
2008 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2009
2010 self.conn.set_debuglevel(1)
2011 self.conn._create_connection = self._create_connection(response_text)
2012 self.conn.set_tunnel('destination.com')
2013
2014 with support.captured_stdout() as output:
2015 self.conn.request('PUT', '/', '')
2016 lines = output.getvalue().splitlines()
2017 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002018
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002019
Thomas Wouters89f507f2006-12-13 04:49:30 +00002020if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002021 unittest.main(verbosity=2)