blob: ed125893d6d07292e8244d11e7baae2d19170bce [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
Miss Islington (bot)27b81102020-07-18 13:41:55 -0700368class HttpMethodTests(TestCase):
369 def test_invalid_method_names(self):
370 methods = (
371 'GET\r',
372 'POST\n',
373 'PUT\n\r',
374 'POST\nValue',
375 'POST\nHOST:abc',
376 'GET\nrHost:abc\n',
377 'POST\rRemainder:\r',
378 'GET\rHOST:\n',
379 '\nPUT'
380 )
381
382 for method in methods:
383 with self.assertRaisesRegex(
384 ValueError, "method can't contain control characters"):
385 conn = client.HTTPConnection('example.com')
386 conn.sock = FakeSocket(None)
387 conn.request(method=method, url="/")
388
389
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000390class TransferEncodingTest(TestCase):
391 expected_body = b"It's just a flesh wound"
392
393 def test_endheaders_chunked(self):
394 conn = client.HTTPConnection('example.com')
395 conn.sock = FakeSocket(b'')
396 conn.putrequest('POST', '/')
397 conn.endheaders(self._make_body(), encode_chunked=True)
398
399 _, _, body = self._parse_request(conn.sock.data)
400 body = self._parse_chunked(body)
401 self.assertEqual(body, self.expected_body)
402
403 def test_explicit_headers(self):
404 # explicit chunked
405 conn = client.HTTPConnection('example.com')
406 conn.sock = FakeSocket(b'')
407 # this shouldn't actually be automatically chunk-encoded because the
408 # calling code has explicitly stated that it's taking care of it
409 conn.request(
410 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
411
412 _, headers, body = self._parse_request(conn.sock.data)
413 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
414 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
415 self.assertEqual(body, self.expected_body)
416
417 # explicit chunked, string body
418 conn = client.HTTPConnection('example.com')
419 conn.sock = FakeSocket(b'')
420 conn.request(
421 'POST', '/', self.expected_body.decode('latin-1'),
422 {'Transfer-Encoding': 'chunked'})
423
424 _, headers, body = self._parse_request(conn.sock.data)
425 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
426 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
427 self.assertEqual(body, self.expected_body)
428
429 # User-specified TE, but request() does the chunk encoding
430 conn = client.HTTPConnection('example.com')
431 conn.sock = FakeSocket(b'')
432 conn.request('POST', '/',
433 headers={'Transfer-Encoding': 'gzip, chunked'},
434 encode_chunked=True,
435 body=self._make_body())
436 _, headers, body = self._parse_request(conn.sock.data)
437 self.assertNotIn('content-length', [k.lower() for k in headers])
438 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
439 self.assertEqual(self._parse_chunked(body), self.expected_body)
440
441 def test_request(self):
442 for empty_lines in (False, True,):
443 conn = client.HTTPConnection('example.com')
444 conn.sock = FakeSocket(b'')
445 conn.request(
446 'POST', '/', self._make_body(empty_lines=empty_lines))
447
448 _, headers, body = self._parse_request(conn.sock.data)
449 body = self._parse_chunked(body)
450 self.assertEqual(body, self.expected_body)
451 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
452
453 # Content-Length and Transfer-Encoding SHOULD not be sent in the
454 # same request
455 self.assertNotIn('content-length', [k.lower() for k in headers])
456
Martin Panteref91bb22016-08-27 01:39:26 +0000457 def test_empty_body(self):
458 # Zero-length iterable should be treated like any other iterable
459 conn = client.HTTPConnection('example.com')
460 conn.sock = FakeSocket(b'')
461 conn.request('POST', '/', ())
462 _, headers, body = self._parse_request(conn.sock.data)
463 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
464 self.assertNotIn('content-length', [k.lower() for k in headers])
465 self.assertEqual(body, b"0\r\n\r\n")
466
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000467 def _make_body(self, empty_lines=False):
468 lines = self.expected_body.split(b' ')
469 for idx, line in enumerate(lines):
470 # for testing handling empty lines
471 if empty_lines and idx % 2:
472 yield b''
473 if idx < len(lines) - 1:
474 yield line + b' '
475 else:
476 yield line
477
478 def _parse_request(self, data):
479 lines = data.split(b'\r\n')
480 request = lines[0]
481 headers = {}
482 n = 1
483 while n < len(lines) and len(lines[n]) > 0:
484 key, val = lines[n].split(b':')
485 key = key.decode('latin-1').strip()
486 headers[key] = val.decode('latin-1').strip()
487 n += 1
488
489 return request, headers, b'\r\n'.join(lines[n + 1:])
490
491 def _parse_chunked(self, data):
492 body = []
493 trailers = {}
494 n = 0
495 lines = data.split(b'\r\n')
496 # parse body
497 while True:
498 size, chunk = lines[n:n+2]
499 size = int(size, 16)
500
501 if size == 0:
502 n += 1
503 break
504
505 self.assertEqual(size, len(chunk))
506 body.append(chunk)
507
508 n += 2
509 # we /should/ hit the end chunk, but check against the size of
510 # lines so we're not stuck in an infinite loop should we get
511 # malformed data
512 if n > len(lines):
513 break
514
515 return b''.join(body)
516
517
Thomas Wouters89f507f2006-12-13 04:49:30 +0000518class BasicTest(TestCase):
519 def test_status_lines(self):
520 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000521
Thomas Wouters89f507f2006-12-13 04:49:30 +0000522 body = "HTTP/1.1 200 Ok\r\n\r\nText"
523 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000524 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000525 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200526 self.assertEqual(resp.read(0), b'') # Issue #20007
527 self.assertFalse(resp.isclosed())
528 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000529 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000530 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200531 self.assertFalse(resp.closed)
532 resp.close()
533 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000534
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
536 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000537 resp = client.HTTPResponse(sock)
538 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000539
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000540 def test_bad_status_repr(self):
541 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200542 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000543
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000544 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000545 # if we have Content-Length, HTTPResponse knows when to close itself,
546 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000547 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
548 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000549 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000550 resp.begin()
551 self.assertEqual(resp.read(2), b'Te')
552 self.assertFalse(resp.isclosed())
553 self.assertEqual(resp.read(2), b'xt')
554 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200555 self.assertFalse(resp.closed)
556 resp.close()
557 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000558
Martin Panterce911c32016-03-17 06:42:48 +0000559 def test_mixed_reads(self):
560 # readline() should update the remaining length, so that read() knows
561 # how much data is left and does not raise IncompleteRead
562 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
563 sock = FakeSocket(body)
564 resp = client.HTTPResponse(sock)
565 resp.begin()
566 self.assertEqual(resp.readline(), b'Text\r\n')
567 self.assertFalse(resp.isclosed())
568 self.assertEqual(resp.read(), b'Another')
569 self.assertTrue(resp.isclosed())
570 self.assertFalse(resp.closed)
571 resp.close()
572 self.assertTrue(resp.closed)
573
Antoine Pitrou38d96432011-12-06 22:33:57 +0100574 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000575 # if we have Content-Length, HTTPResponse knows when to close itself,
576 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100577 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 b = bytearray(2)
582 n = resp.readinto(b)
583 self.assertEqual(n, 2)
584 self.assertEqual(bytes(b), b'Te')
585 self.assertFalse(resp.isclosed())
586 n = resp.readinto(b)
587 self.assertEqual(n, 2)
588 self.assertEqual(bytes(b), b'xt')
589 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200590 self.assertFalse(resp.closed)
591 resp.close()
592 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100593
Antoine Pitrou084daa22012-12-15 19:11:54 +0100594 def test_partial_reads_no_content_length(self):
595 # when no length is present, the socket should be gracefully closed when
596 # all data was read
597 body = "HTTP/1.1 200 Ok\r\n\r\nText"
598 sock = FakeSocket(body)
599 resp = client.HTTPResponse(sock)
600 resp.begin()
601 self.assertEqual(resp.read(2), b'Te')
602 self.assertFalse(resp.isclosed())
603 self.assertEqual(resp.read(2), b'xt')
604 self.assertEqual(resp.read(1), b'')
605 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200606 self.assertFalse(resp.closed)
607 resp.close()
608 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100609
Antoine Pitroud20e7742012-12-15 19:22:30 +0100610 def test_partial_readintos_no_content_length(self):
611 # when no length is present, the socket should be gracefully closed when
612 # all data was read
613 body = "HTTP/1.1 200 Ok\r\n\r\nText"
614 sock = FakeSocket(body)
615 resp = client.HTTPResponse(sock)
616 resp.begin()
617 b = bytearray(2)
618 n = resp.readinto(b)
619 self.assertEqual(n, 2)
620 self.assertEqual(bytes(b), b'Te')
621 self.assertFalse(resp.isclosed())
622 n = resp.readinto(b)
623 self.assertEqual(n, 2)
624 self.assertEqual(bytes(b), b'xt')
625 n = resp.readinto(b)
626 self.assertEqual(n, 0)
627 self.assertTrue(resp.isclosed())
628
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100629 def test_partial_reads_incomplete_body(self):
630 # if the server shuts down the connection before the whole
631 # content-length is delivered, the socket is gracefully closed
632 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
633 sock = FakeSocket(body)
634 resp = client.HTTPResponse(sock)
635 resp.begin()
636 self.assertEqual(resp.read(2), b'Te')
637 self.assertFalse(resp.isclosed())
638 self.assertEqual(resp.read(2), b'xt')
639 self.assertEqual(resp.read(1), b'')
640 self.assertTrue(resp.isclosed())
641
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100642 def test_partial_readintos_incomplete_body(self):
643 # if the server shuts down the connection before the whole
644 # content-length is delivered, the socket is gracefully closed
645 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
646 sock = FakeSocket(body)
647 resp = client.HTTPResponse(sock)
648 resp.begin()
649 b = bytearray(2)
650 n = resp.readinto(b)
651 self.assertEqual(n, 2)
652 self.assertEqual(bytes(b), b'Te')
653 self.assertFalse(resp.isclosed())
654 n = resp.readinto(b)
655 self.assertEqual(n, 2)
656 self.assertEqual(bytes(b), b'xt')
657 n = resp.readinto(b)
658 self.assertEqual(n, 0)
659 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200660 self.assertFalse(resp.closed)
661 resp.close()
662 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100663
Thomas Wouters89f507f2006-12-13 04:49:30 +0000664 def test_host_port(self):
665 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000666
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200667 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000668 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000669
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000670 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
671 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200673 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200675 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
676 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000677 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000678 self.assertEqual(h, c.host)
679 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000680
Thomas Wouters89f507f2006-12-13 04:49:30 +0000681 def test_response_headers(self):
682 # test response with multiple message headers with the same field name.
683 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000684 'Set-Cookie: Customer="WILE_E_COYOTE"; '
685 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000686 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
687 ' Path="/acme"\r\n'
688 '\r\n'
689 'No body\r\n')
690 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
691 ', '
692 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
693 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000694 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000695 r.begin()
696 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000697 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000698
Thomas Wouters89f507f2006-12-13 04:49:30 +0000699 def test_read_head(self):
700 # Test that the library doesn't attempt to read any data
701 # from a HEAD request. (Tickles SF bug #622042.)
702 sock = FakeSocket(
703 'HTTP/1.1 200 OK\r\n'
704 'Content-Length: 14432\r\n'
705 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300706 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000707 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000708 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000709 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000710 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000711
Antoine Pitrou38d96432011-12-06 22:33:57 +0100712 def test_readinto_head(self):
713 # Test that the library doesn't attempt to read any data
714 # from a HEAD request. (Tickles SF bug #622042.)
715 sock = FakeSocket(
716 'HTTP/1.1 200 OK\r\n'
717 'Content-Length: 14432\r\n'
718 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300719 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100720 resp = client.HTTPResponse(sock, method="HEAD")
721 resp.begin()
722 b = bytearray(5)
723 if resp.readinto(b) != 0:
724 self.fail("Did not expect response from HEAD request")
725 self.assertEqual(bytes(b), b'\x00'*5)
726
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100727 def test_too_many_headers(self):
728 headers = '\r\n'.join('Header%d: foo' % i
729 for i in range(client._MAXHEADERS + 1)) + '\r\n'
730 text = ('HTTP/1.1 200 OK\r\n' + headers)
731 s = FakeSocket(text)
732 r = client.HTTPResponse(s)
733 self.assertRaisesRegex(client.HTTPException,
734 r"got more than \d+ headers", r.begin)
735
Thomas Wouters89f507f2006-12-13 04:49:30 +0000736 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000737 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000738 b'Accept-Encoding: identity\r\n'
739 b'Transfer-Encoding: chunked\r\n'
740 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000741
Brett Cannon77b7de62010-10-29 23:31:11 +0000742 with open(__file__, 'rb') as body:
743 conn = client.HTTPConnection('example.com')
744 sock = FakeSocket(body)
745 conn.sock = sock
746 conn.request('GET', '/foo', body)
747 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
748 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000749
Antoine Pitrouead1d622009-09-29 18:44:53 +0000750 def test_send(self):
751 expected = b'this is a test this is only a test'
752 conn = client.HTTPConnection('example.com')
753 sock = FakeSocket(None)
754 conn.sock = sock
755 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000756 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000757 sock.data = b''
758 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000759 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000760 sock.data = b''
761 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000762 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000763
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300764 def test_send_updating_file(self):
765 def data():
766 yield 'data'
767 yield None
768 yield 'data_two'
769
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000770 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300771 mode = 'r'
772 d = data()
773 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000774 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300775
776 expected = b'data'
777
778 conn = client.HTTPConnection('example.com')
779 sock = FakeSocket("")
780 conn.sock = sock
781 conn.send(UpdatingFile())
782 self.assertEqual(sock.data, expected)
783
784
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000785 def test_send_iter(self):
786 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
787 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
788 b'\r\nonetwothree'
789
790 def body():
791 yield b"one"
792 yield b"two"
793 yield b"three"
794
795 conn = client.HTTPConnection('example.com')
796 sock = FakeSocket("")
797 conn.sock = sock
798 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000799 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000800
Nir Sofferad455cd2017-11-06 23:16:37 +0200801 def test_blocksize_request(self):
802 """Check that request() respects the configured block size."""
803 blocksize = 8 # For easy debugging.
804 conn = client.HTTPConnection('example.com', blocksize=blocksize)
805 sock = FakeSocket(None)
806 conn.sock = sock
807 expected = b"a" * blocksize + b"b"
808 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
809 self.assertEqual(sock.sendall_calls, 3)
810 body = sock.data.split(b"\r\n\r\n", 1)[1]
811 self.assertEqual(body, expected)
812
813 def test_blocksize_send(self):
814 """Check that send() respects the configured block size."""
815 blocksize = 8 # For easy debugging.
816 conn = client.HTTPConnection('example.com', blocksize=blocksize)
817 sock = FakeSocket(None)
818 conn.sock = sock
819 expected = b"a" * blocksize + b"b"
820 conn.send(io.BytesIO(expected))
821 self.assertEqual(sock.sendall_calls, 2)
822 self.assertEqual(sock.data, expected)
823
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800824 def test_send_type_error(self):
825 # See: Issue #12676
826 conn = client.HTTPConnection('example.com')
827 conn.sock = FakeSocket('')
828 with self.assertRaises(TypeError):
829 conn.request('POST', 'test', conn)
830
Christian Heimesa612dc02008-02-24 13:08:18 +0000831 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000832 expected = chunked_expected
833 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000834 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000835 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100836 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000837 resp.close()
838
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100839 # Various read sizes
840 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000841 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100842 resp = client.HTTPResponse(sock, method="GET")
843 resp.begin()
844 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
845 resp.close()
846
Christian Heimesa612dc02008-02-24 13:08:18 +0000847 for x in ('', 'foo\r\n'):
848 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000849 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000850 resp.begin()
851 try:
852 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000853 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100854 self.assertEqual(i.partial, expected)
855 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
856 self.assertEqual(repr(i), expected_message)
857 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000858 else:
859 self.fail('IncompleteRead expected')
860 finally:
861 resp.close()
862
Antoine Pitrou38d96432011-12-06 22:33:57 +0100863 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000864
865 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100866 nexpected = len(expected)
867 b = bytearray(128)
868
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000869 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100870 resp = client.HTTPResponse(sock, method="GET")
871 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100872 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100873 self.assertEqual(b[:nexpected], expected)
874 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100875 resp.close()
876
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100877 # Various read sizes
878 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000879 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100880 resp = client.HTTPResponse(sock, method="GET")
881 resp.begin()
882 m = memoryview(b)
883 i = resp.readinto(m[0:n])
884 i += resp.readinto(m[i:n + i])
885 i += resp.readinto(m[i:])
886 self.assertEqual(b[:nexpected], expected)
887 self.assertEqual(i, nexpected)
888 resp.close()
889
Antoine Pitrou38d96432011-12-06 22:33:57 +0100890 for x in ('', 'foo\r\n'):
891 sock = FakeSocket(chunked_start + x)
892 resp = client.HTTPResponse(sock, method="GET")
893 resp.begin()
894 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100895 n = resp.readinto(b)
896 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100897 self.assertEqual(i.partial, expected)
898 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
899 self.assertEqual(repr(i), expected_message)
900 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100901 else:
902 self.fail('IncompleteRead expected')
903 finally:
904 resp.close()
905
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000906 def test_chunked_head(self):
907 chunked_start = (
908 'HTTP/1.1 200 OK\r\n'
909 'Transfer-Encoding: chunked\r\n\r\n'
910 'a\r\n'
911 'hello world\r\n'
912 '1\r\n'
913 'd\r\n'
914 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000915 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000916 resp = client.HTTPResponse(sock, method="HEAD")
917 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000918 self.assertEqual(resp.read(), b'')
919 self.assertEqual(resp.status, 200)
920 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000921 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200922 self.assertFalse(resp.closed)
923 resp.close()
924 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000925
Antoine Pitrou38d96432011-12-06 22:33:57 +0100926 def test_readinto_chunked_head(self):
927 chunked_start = (
928 'HTTP/1.1 200 OK\r\n'
929 'Transfer-Encoding: chunked\r\n\r\n'
930 'a\r\n'
931 'hello world\r\n'
932 '1\r\n'
933 'd\r\n'
934 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000935 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100936 resp = client.HTTPResponse(sock, method="HEAD")
937 resp.begin()
938 b = bytearray(5)
939 n = resp.readinto(b)
940 self.assertEqual(n, 0)
941 self.assertEqual(bytes(b), b'\x00'*5)
942 self.assertEqual(resp.status, 200)
943 self.assertEqual(resp.reason, 'OK')
944 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200945 self.assertFalse(resp.closed)
946 resp.close()
947 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100948
Christian Heimesa612dc02008-02-24 13:08:18 +0000949 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000950 sock = FakeSocket(
951 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000952 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000953 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000954 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100955 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000956
Benjamin Peterson6accb982009-03-02 22:50:25 +0000957 def test_incomplete_read(self):
958 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000959 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000960 resp.begin()
961 try:
962 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000963 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000964 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000965 self.assertEqual(repr(i),
966 "IncompleteRead(7 bytes read, 3 more expected)")
967 self.assertEqual(str(i),
968 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100969 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000970 else:
971 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000972
Jeremy Hylton636950f2009-03-28 04:34:21 +0000973 def test_epipe(self):
974 sock = EPipeSocket(
975 "HTTP/1.0 401 Authorization Required\r\n"
976 "Content-type: text/html\r\n"
977 "WWW-Authenticate: Basic realm=\"example\"\r\n",
978 b"Content-Length")
979 conn = client.HTTPConnection("example.com")
980 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200981 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000982 lambda: conn.request("PUT", "/url", "body"))
983 resp = conn.getresponse()
984 self.assertEqual(401, resp.status)
985 self.assertEqual("Basic realm=\"example\"",
986 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000987
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000988 # Test lines overflowing the max line size (_MAXLINE in http.client)
989
990 def test_overflowing_status_line(self):
991 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
992 resp = client.HTTPResponse(FakeSocket(body))
993 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
994
995 def test_overflowing_header_line(self):
996 body = (
997 'HTTP/1.1 200 OK\r\n'
998 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
999 )
1000 resp = client.HTTPResponse(FakeSocket(body))
1001 self.assertRaises(client.LineTooLong, resp.begin)
1002
1003 def test_overflowing_chunked_line(self):
1004 body = (
1005 'HTTP/1.1 200 OK\r\n'
1006 'Transfer-Encoding: chunked\r\n\r\n'
1007 + '0' * 65536 + 'a\r\n'
1008 'hello world\r\n'
1009 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001010 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001011 )
1012 resp = client.HTTPResponse(FakeSocket(body))
1013 resp.begin()
1014 self.assertRaises(client.LineTooLong, resp.read)
1015
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001016 def test_early_eof(self):
1017 # Test httpresponse with no \r\n termination,
1018 body = "HTTP/1.1 200 Ok"
1019 sock = FakeSocket(body)
1020 resp = client.HTTPResponse(sock)
1021 resp.begin()
1022 self.assertEqual(resp.read(), b'')
1023 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001024 self.assertFalse(resp.closed)
1025 resp.close()
1026 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001027
Serhiy Storchakab491e052014-12-01 13:07:45 +02001028 def test_error_leak(self):
1029 # Test that the socket is not leaked if getresponse() fails
1030 conn = client.HTTPConnection('example.com')
1031 response = None
1032 class Response(client.HTTPResponse):
1033 def __init__(self, *pos, **kw):
1034 nonlocal response
1035 response = self # Avoid garbage collector closing the socket
1036 client.HTTPResponse.__init__(self, *pos, **kw)
1037 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001038 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001039 conn.request('GET', '/')
1040 self.assertRaises(client.BadStatusLine, conn.getresponse)
1041 self.assertTrue(response.closed)
1042 self.assertTrue(conn.sock.file_closed)
1043
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001044 def test_chunked_extension(self):
1045 extra = '3;foo=bar\r\n' + 'abc\r\n'
1046 expected = chunked_expected + b'abc'
1047
1048 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1049 resp = client.HTTPResponse(sock, method="GET")
1050 resp.begin()
1051 self.assertEqual(resp.read(), expected)
1052 resp.close()
1053
1054 def test_chunked_missing_end(self):
1055 """some servers may serve up a short chunked encoding stream"""
1056 expected = chunked_expected
1057 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1058 resp = client.HTTPResponse(sock, method="GET")
1059 resp.begin()
1060 self.assertEqual(resp.read(), expected)
1061 resp.close()
1062
1063 def test_chunked_trailers(self):
1064 """See that trailers are read and ignored"""
1065 expected = chunked_expected
1066 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1067 resp = client.HTTPResponse(sock, method="GET")
1068 resp.begin()
1069 self.assertEqual(resp.read(), expected)
1070 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001071 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001072 resp.close()
1073
1074 def test_chunked_sync(self):
1075 """Check that we don't read past the end of the chunked-encoding stream"""
1076 expected = chunked_expected
1077 extradata = "extradata"
1078 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1079 resp = client.HTTPResponse(sock, method="GET")
1080 resp.begin()
1081 self.assertEqual(resp.read(), expected)
1082 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001083 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001084 resp.close()
1085
1086 def test_content_length_sync(self):
1087 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001088 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001089 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001090 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 +00001091 resp = client.HTTPResponse(sock, method="GET")
1092 resp.begin()
1093 self.assertEqual(resp.read(), expected)
1094 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001095 self.assertEqual(sock.file.read(), extradata) #we read to the end
1096 resp.close()
1097
1098 def test_readlines_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.readlines(2000), [expected])
1105 # the file should now have our extradata ready to be read
1106 self.assertEqual(sock.file.read(), extradata) #we read to the end
1107 resp.close()
1108
1109 def test_read1_content_length(self):
1110 extradata = b"extradata"
1111 expected = b"Hello123\r\n"
1112 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1113 resp = client.HTTPResponse(sock, method="GET")
1114 resp.begin()
1115 self.assertEqual(resp.read1(2000), expected)
1116 # the file should now have our extradata ready to be read
1117 self.assertEqual(sock.file.read(), extradata) #we read to the end
1118 resp.close()
1119
1120 def test_readline_bound_content_length(self):
1121 extradata = b"extradata"
1122 expected = b"Hello123\r\n"
1123 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1124 resp = client.HTTPResponse(sock, method="GET")
1125 resp.begin()
1126 self.assertEqual(resp.readline(10), expected)
1127 self.assertEqual(resp.readline(10), b"")
1128 # the file should now have our extradata ready to be read
1129 self.assertEqual(sock.file.read(), extradata) #we read to the end
1130 resp.close()
1131
1132 def test_read1_bound_content_length(self):
1133 extradata = b"extradata"
1134 expected = b"Hello123\r\n"
1135 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1136 resp = client.HTTPResponse(sock, method="GET")
1137 resp.begin()
1138 self.assertEqual(resp.read1(20), expected*2)
1139 self.assertEqual(resp.read(), expected)
1140 # the file should now have our extradata ready to be read
1141 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001142 resp.close()
1143
Martin Panterd979b2c2016-04-09 14:03:17 +00001144 def test_response_fileno(self):
1145 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001146 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001147 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001148
1149 result = None
1150 def run_server():
1151 [conn, address] = serv.accept()
1152 with conn, conn.makefile("rb") as reader:
1153 # Read the request header until a blank line
1154 while True:
1155 line = reader.readline()
1156 if not line.rstrip(b"\r\n"):
1157 break
1158 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1159 nonlocal result
1160 result = reader.read()
1161
1162 thread = threading.Thread(target=run_server)
1163 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001164 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001165 conn = client.HTTPConnection(*serv.getsockname())
1166 conn.request("CONNECT", "dummy:1234")
1167 response = conn.getresponse()
1168 try:
1169 self.assertEqual(response.status, client.OK)
1170 s = socket.socket(fileno=response.fileno())
1171 try:
1172 s.sendall(b"proxied data\n")
1173 finally:
1174 s.detach()
1175 finally:
1176 response.close()
1177 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001178 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001179 self.assertEqual(result, b"proxied data\n")
1180
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001181 def test_putrequest_override_domain_validation(self):
Jason R. Coombs7774d782019-09-28 08:32:01 -04001182 """
1183 It should be possible to override the default validation
1184 behavior in putrequest (bpo-38216).
1185 """
1186 class UnsafeHTTPConnection(client.HTTPConnection):
1187 def _validate_path(self, url):
1188 pass
1189
1190 conn = UnsafeHTTPConnection('example.com')
1191 conn.sock = FakeSocket('')
1192 conn.putrequest('GET', '/\x00')
1193
Ashwin Ramaswami9165add2020-03-14 14:56:06 -04001194 def test_putrequest_override_host_validation(self):
1195 class UnsafeHTTPConnection(client.HTTPConnection):
1196 def _validate_host(self, url):
1197 pass
1198
1199 conn = UnsafeHTTPConnection('example.com\r\n')
1200 conn.sock = FakeSocket('')
1201 # set skip_host so a ValueError is not raised upon adding the
1202 # invalid URL as the value of the "Host:" header
1203 conn.putrequest('GET', '/', skip_host=1)
1204
Jason R. Coombs7774d782019-09-28 08:32:01 -04001205 def test_putrequest_override_encoding(self):
1206 """
1207 It should be possible to override the default encoding
1208 to transmit bytes in another encoding even if invalid
1209 (bpo-36274).
1210 """
1211 class UnsafeHTTPConnection(client.HTTPConnection):
1212 def _encode_request(self, str_url):
1213 return str_url.encode('utf-8')
1214
1215 conn = UnsafeHTTPConnection('example.com')
1216 conn.sock = FakeSocket('')
1217 conn.putrequest('GET', '/☃')
1218
1219
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001220class ExtendedReadTest(TestCase):
1221 """
1222 Test peek(), read1(), readline()
1223 """
1224 lines = (
1225 'HTTP/1.1 200 OK\r\n'
1226 '\r\n'
1227 'hello world!\n'
1228 'and now \n'
1229 'for something completely different\n'
1230 'foo'
1231 )
1232 lines_expected = lines[lines.find('hello'):].encode("ascii")
1233 lines_chunked = (
1234 'HTTP/1.1 200 OK\r\n'
1235 'Transfer-Encoding: chunked\r\n\r\n'
1236 'a\r\n'
1237 'hello worl\r\n'
1238 '3\r\n'
1239 'd!\n\r\n'
1240 '9\r\n'
1241 'and now \n\r\n'
1242 '23\r\n'
1243 'for something completely different\n\r\n'
1244 '3\r\n'
1245 'foo\r\n'
1246 '0\r\n' # terminating chunk
1247 '\r\n' # end of trailers
1248 )
1249
1250 def setUp(self):
1251 sock = FakeSocket(self.lines)
1252 resp = client.HTTPResponse(sock, method="GET")
1253 resp.begin()
1254 resp.fp = io.BufferedReader(resp.fp)
1255 self.resp = resp
1256
1257
1258
1259 def test_peek(self):
1260 resp = self.resp
1261 # patch up the buffered peek so that it returns not too much stuff
1262 oldpeek = resp.fp.peek
1263 def mypeek(n=-1):
1264 p = oldpeek(n)
1265 if n >= 0:
1266 return p[:n]
1267 return p[:10]
1268 resp.fp.peek = mypeek
1269
1270 all = []
1271 while True:
1272 # try a short peek
1273 p = resp.peek(3)
1274 if p:
1275 self.assertGreater(len(p), 0)
1276 # then unbounded peek
1277 p2 = resp.peek()
1278 self.assertGreaterEqual(len(p2), len(p))
1279 self.assertTrue(p2.startswith(p))
1280 next = resp.read(len(p2))
1281 self.assertEqual(next, p2)
1282 else:
1283 next = resp.read()
1284 self.assertFalse(next)
1285 all.append(next)
1286 if not next:
1287 break
1288 self.assertEqual(b"".join(all), self.lines_expected)
1289
1290 def test_readline(self):
1291 resp = self.resp
1292 self._verify_readline(self.resp.readline, self.lines_expected)
1293
1294 def _verify_readline(self, readline, expected):
1295 all = []
1296 while True:
1297 # short readlines
1298 line = readline(5)
1299 if line and line != b"foo":
1300 if len(line) < 5:
1301 self.assertTrue(line.endswith(b"\n"))
1302 all.append(line)
1303 if not line:
1304 break
1305 self.assertEqual(b"".join(all), expected)
1306
1307 def test_read1(self):
1308 resp = self.resp
1309 def r():
1310 res = resp.read1(4)
1311 self.assertLessEqual(len(res), 4)
1312 return res
1313 readliner = Readliner(r)
1314 self._verify_readline(readliner.readline, self.lines_expected)
1315
1316 def test_read1_unbounded(self):
1317 resp = self.resp
1318 all = []
1319 while True:
1320 data = resp.read1()
1321 if not data:
1322 break
1323 all.append(data)
1324 self.assertEqual(b"".join(all), self.lines_expected)
1325
1326 def test_read1_bounded(self):
1327 resp = self.resp
1328 all = []
1329 while True:
1330 data = resp.read1(10)
1331 if not data:
1332 break
1333 self.assertLessEqual(len(data), 10)
1334 all.append(data)
1335 self.assertEqual(b"".join(all), self.lines_expected)
1336
1337 def test_read1_0(self):
1338 self.assertEqual(self.resp.read1(0), b"")
1339
1340 def test_peek_0(self):
1341 p = self.resp.peek(0)
1342 self.assertLessEqual(0, len(p))
1343
Jason R. Coombs7774d782019-09-28 08:32:01 -04001344
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001345class ExtendedReadTestChunked(ExtendedReadTest):
1346 """
1347 Test peek(), read1(), readline() in chunked mode
1348 """
1349 lines = (
1350 'HTTP/1.1 200 OK\r\n'
1351 'Transfer-Encoding: chunked\r\n\r\n'
1352 'a\r\n'
1353 'hello worl\r\n'
1354 '3\r\n'
1355 'd!\n\r\n'
1356 '9\r\n'
1357 'and now \n\r\n'
1358 '23\r\n'
1359 'for something completely different\n\r\n'
1360 '3\r\n'
1361 'foo\r\n'
1362 '0\r\n' # terminating chunk
1363 '\r\n' # end of trailers
1364 )
1365
1366
1367class Readliner:
1368 """
1369 a simple readline class that uses an arbitrary read function and buffering
1370 """
1371 def __init__(self, readfunc):
1372 self.readfunc = readfunc
1373 self.remainder = b""
1374
1375 def readline(self, limit):
1376 data = []
1377 datalen = 0
1378 read = self.remainder
1379 try:
1380 while True:
1381 idx = read.find(b'\n')
1382 if idx != -1:
1383 break
1384 if datalen + len(read) >= limit:
1385 idx = limit - datalen - 1
1386 # read more data
1387 data.append(read)
1388 read = self.readfunc()
1389 if not read:
1390 idx = 0 #eof condition
1391 break
1392 idx += 1
1393 data.append(read[:idx])
1394 self.remainder = read[idx:]
1395 return b"".join(data)
1396 except:
1397 self.remainder = b"".join(data)
1398 raise
1399
Berker Peksagbabc6882015-02-20 09:39:38 +02001400
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001401class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001402 def test_all(self):
1403 # Documented objects defined in the module should be in __all__
1404 expected = {"responses"} # White-list documented dict() object
1405 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1406 # intentionally omitted for simplicity
1407 blacklist = {"HTTPMessage", "parse_headers"}
1408 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001409 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001410 continue
1411 module_object = getattr(client, name)
1412 if getattr(module_object, "__module__", None) == "http.client":
1413 expected.add(name)
1414 self.assertCountEqual(client.__all__, expected)
1415
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001416 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001417 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001418
Berker Peksagabbf0f42015-02-20 14:57:31 +02001419 def test_client_constants(self):
1420 # Make sure we don't break backward compatibility with 3.4
1421 expected = [
1422 'CONTINUE',
1423 'SWITCHING_PROTOCOLS',
1424 'PROCESSING',
1425 'OK',
1426 'CREATED',
1427 'ACCEPTED',
1428 'NON_AUTHORITATIVE_INFORMATION',
1429 'NO_CONTENT',
1430 'RESET_CONTENT',
1431 'PARTIAL_CONTENT',
1432 'MULTI_STATUS',
1433 'IM_USED',
1434 'MULTIPLE_CHOICES',
1435 'MOVED_PERMANENTLY',
1436 'FOUND',
1437 'SEE_OTHER',
1438 'NOT_MODIFIED',
1439 'USE_PROXY',
1440 'TEMPORARY_REDIRECT',
1441 'BAD_REQUEST',
1442 'UNAUTHORIZED',
1443 'PAYMENT_REQUIRED',
1444 'FORBIDDEN',
1445 'NOT_FOUND',
1446 'METHOD_NOT_ALLOWED',
1447 'NOT_ACCEPTABLE',
1448 'PROXY_AUTHENTICATION_REQUIRED',
1449 'REQUEST_TIMEOUT',
1450 'CONFLICT',
1451 'GONE',
1452 'LENGTH_REQUIRED',
1453 'PRECONDITION_FAILED',
1454 'REQUEST_ENTITY_TOO_LARGE',
1455 'REQUEST_URI_TOO_LONG',
1456 'UNSUPPORTED_MEDIA_TYPE',
1457 'REQUESTED_RANGE_NOT_SATISFIABLE',
1458 'EXPECTATION_FAILED',
Ross61ac6122020-03-15 12:24:23 +00001459 'IM_A_TEAPOT',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001460 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001461 'UNPROCESSABLE_ENTITY',
1462 'LOCKED',
1463 'FAILED_DEPENDENCY',
1464 'UPGRADE_REQUIRED',
1465 'PRECONDITION_REQUIRED',
1466 'TOO_MANY_REQUESTS',
1467 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Raymond Hettinger8f080b02019-08-23 10:19:15 -07001468 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001469 'INTERNAL_SERVER_ERROR',
1470 'NOT_IMPLEMENTED',
1471 'BAD_GATEWAY',
1472 'SERVICE_UNAVAILABLE',
1473 'GATEWAY_TIMEOUT',
1474 'HTTP_VERSION_NOT_SUPPORTED',
1475 'INSUFFICIENT_STORAGE',
1476 'NOT_EXTENDED',
1477 'NETWORK_AUTHENTICATION_REQUIRED',
Dong-hee Nada52be42020-03-14 23:12:01 +09001478 'EARLY_HINTS',
1479 'TOO_EARLY'
Berker Peksagabbf0f42015-02-20 14:57:31 +02001480 ]
1481 for const in expected:
1482 with self.subTest(constant=const):
1483 self.assertTrue(hasattr(client, const))
1484
Gregory P. Smithb4066372010-01-03 03:28:29 +00001485
1486class SourceAddressTest(TestCase):
1487 def setUp(self):
1488 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001489 self.port = socket_helper.bind_port(self.serv)
1490 self.source_port = socket_helper.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001491 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001492 self.conn = None
1493
1494 def tearDown(self):
1495 if self.conn:
1496 self.conn.close()
1497 self.conn = None
1498 self.serv.close()
1499 self.serv = None
1500
1501 def testHTTPConnectionSourceAddress(self):
1502 self.conn = client.HTTPConnection(HOST, self.port,
1503 source_address=('', self.source_port))
1504 self.conn.connect()
1505 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1506
1507 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1508 'http.client.HTTPSConnection not defined')
1509 def testHTTPSConnectionSourceAddress(self):
1510 self.conn = client.HTTPSConnection(HOST, self.port,
1511 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001512 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001513 # this code doesn't deal with setting up an active running SSL server
1514 # for an ssl_wrapped connect() to actually return from.
1515
1516
Guido van Rossumd8faa362007-04-27 19:54:29 +00001517class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001518 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001519
1520 def setUp(self):
1521 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Serhiy Storchaka16994912020-04-25 10:06:29 +03001522 TimeoutTest.PORT = socket_helper.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001523 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001524
1525 def tearDown(self):
1526 self.serv.close()
1527 self.serv = None
1528
1529 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001530 # This will prove that the timeout gets through HTTPConnection
1531 # and into the socket.
1532
Georg Brandlf78e02b2008-06-10 17:40:04 +00001533 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001534 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001535 socket.setdefaulttimeout(30)
1536 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001537 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001538 httpConn.connect()
1539 finally:
1540 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001541 self.assertEqual(httpConn.sock.gettimeout(), 30)
1542 httpConn.close()
1543
Georg Brandlf78e02b2008-06-10 17:40:04 +00001544 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001545 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546 socket.setdefaulttimeout(30)
1547 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001548 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001549 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001550 httpConn.connect()
1551 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001552 socket.setdefaulttimeout(None)
1553 self.assertEqual(httpConn.sock.gettimeout(), None)
1554 httpConn.close()
1555
1556 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001557 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001558 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001559 self.assertEqual(httpConn.sock.gettimeout(), 30)
1560 httpConn.close()
1561
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001562
R David Murraycae7bdb2015-04-05 19:26:29 -04001563class PersistenceTest(TestCase):
1564
1565 def test_reuse_reconnect(self):
1566 # Should reuse or reconnect depending on header from server
1567 tests = (
1568 ('1.0', '', False),
1569 ('1.0', 'Connection: keep-alive\r\n', True),
1570 ('1.1', '', True),
1571 ('1.1', 'Connection: close\r\n', False),
1572 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1573 ('1.1', 'Connection: cloSE\r\n', False),
1574 )
1575 for version, header, reuse in tests:
1576 with self.subTest(version=version, header=header):
1577 msg = (
1578 'HTTP/{} 200 OK\r\n'
1579 '{}'
1580 'Content-Length: 12\r\n'
1581 '\r\n'
1582 'Dummy body\r\n'
1583 ).format(version, header)
1584 conn = FakeSocketHTTPConnection(msg)
1585 self.assertIsNone(conn.sock)
1586 conn.request('GET', '/open-connection')
1587 with conn.getresponse() as response:
1588 self.assertEqual(conn.sock is None, not reuse)
1589 response.read()
1590 self.assertEqual(conn.sock is None, not reuse)
1591 self.assertEqual(conn.connections, 1)
1592 conn.request('GET', '/subsequent-request')
1593 self.assertEqual(conn.connections, 1 if reuse else 2)
1594
1595 def test_disconnected(self):
1596
1597 def make_reset_reader(text):
1598 """Return BufferedReader that raises ECONNRESET at EOF"""
1599 stream = io.BytesIO(text)
1600 def readinto(buffer):
1601 size = io.BytesIO.readinto(stream, buffer)
1602 if size == 0:
1603 raise ConnectionResetError()
1604 return size
1605 stream.readinto = readinto
1606 return io.BufferedReader(stream)
1607
1608 tests = (
1609 (io.BytesIO, client.RemoteDisconnected),
1610 (make_reset_reader, ConnectionResetError),
1611 )
1612 for stream_factory, exception in tests:
1613 with self.subTest(exception=exception):
1614 conn = FakeSocketHTTPConnection(b'', stream_factory)
1615 conn.request('GET', '/eof-response')
1616 self.assertRaises(exception, conn.getresponse)
1617 self.assertIsNone(conn.sock)
1618 # HTTPConnection.connect() should be automatically invoked
1619 conn.request('GET', '/reconnect')
1620 self.assertEqual(conn.connections, 2)
1621
1622 def test_100_close(self):
1623 conn = FakeSocketHTTPConnection(
1624 b'HTTP/1.1 100 Continue\r\n'
1625 b'\r\n'
1626 # Missing final response
1627 )
1628 conn.request('GET', '/', headers={'Expect': '100-continue'})
1629 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1630 self.assertIsNone(conn.sock)
1631 conn.request('GET', '/reconnect')
1632 self.assertEqual(conn.connections, 2)
1633
1634
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001635class HTTPSTest(TestCase):
1636
1637 def setUp(self):
1638 if not hasattr(client, 'HTTPSConnection'):
1639 self.skipTest('ssl support required')
1640
1641 def make_server(self, certfile):
1642 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001643 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001644
1645 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001646 # simple test to check it's storing the timeout
1647 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1648 self.assertEqual(h.timeout, 30)
1649
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001650 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001651 # Default settings: requires a valid cert from a trusted CA
1652 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001653 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001654 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001655 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1656 with self.assertRaises(ssl.SSLError) as exc_info:
1657 h.request('GET', '/')
1658 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1659
1660 def test_networked_noverification(self):
1661 # Switch off cert verification
1662 import ssl
1663 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001664 with socket_helper.transient_internet('self-signed.pythontest.net'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001665 context = ssl._create_unverified_context()
1666 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1667 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001668 h.request('GET', '/')
1669 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001670 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001671 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001672 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001673
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001674 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001675 def test_networked_trusted_by_default_cert(self):
1676 # Default settings: requires a valid cert from a trusted CA
1677 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001678 with socket_helper.transient_internet('www.python.org'):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001679 h = client.HTTPSConnection('www.python.org', 443)
1680 h.request('GET', '/')
1681 resp = h.getresponse()
1682 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001683 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001684 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001685 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001686
1687 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001688 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001689 import ssl
1690 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001691 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001692 with socket_helper.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001693 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1694 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1695 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001696 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001697 try:
1698 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1699 context=context)
1700 h.request('GET', '/')
1701 resp = h.getresponse()
1702 except ssl.SSLError as ssl_err:
1703 ssl_err_str = str(ssl_err)
1704 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1705 # modern Linux distros (Debian Buster, etc) default OpenSSL
1706 # configurations it'll fail saying "key too weak" until we
1707 # address https://bugs.python.org/issue36816 to use a proper
1708 # key size on self-signed.pythontest.net.
1709 if re.search(r'(?i)key.too.weak', ssl_err_str):
1710 raise unittest.SkipTest(
1711 f'Got {ssl_err_str} trying to connect '
1712 f'to {selfsigned_pythontestdotnet}. '
1713 'See https://bugs.python.org/issue36816.')
1714 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001715 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001716 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001717 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001718 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001719
1720 def test_networked_bad_cert(self):
1721 # We feed a "CA" cert that is unrelated to the server's cert
1722 import ssl
1723 support.requires('network')
Serhiy Storchakabfb1cf42020-04-29 10:36:20 +03001724 with socket_helper.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001725 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001726 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001727 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1728 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001729 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001730 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1731
1732 def test_local_unknown_cert(self):
1733 # The custom cert isn't known to the default trust bundle
1734 import ssl
1735 server = self.make_server(CERT_localhost)
1736 h = client.HTTPSConnection('localhost', server.port)
1737 with self.assertRaises(ssl.SSLError) as exc_info:
1738 h.request('GET', '/')
1739 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001740
1741 def test_local_good_hostname(self):
1742 # The (valid) cert validates the HTTP hostname
1743 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001744 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001745 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001746 context.load_verify_locations(CERT_localhost)
1747 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001748 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001749 h.request('GET', '/nonexistent')
1750 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001751 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001752 self.assertEqual(resp.status, 404)
1753
1754 def test_local_bad_hostname(self):
1755 # The (valid) cert doesn't validate the HTTP hostname
1756 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001757 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001758 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001759 context.load_verify_locations(CERT_fakehostname)
1760 h = client.HTTPSConnection('localhost', server.port, context=context)
1761 with self.assertRaises(ssl.CertificateError):
1762 h.request('GET', '/')
1763 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001764 with support.check_warnings(('', DeprecationWarning)):
1765 h = client.HTTPSConnection('localhost', server.port,
1766 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001767 with self.assertRaises(ssl.CertificateError):
1768 h.request('GET', '/')
1769 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001770 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001771 with support.check_warnings(('', DeprecationWarning)):
1772 h = client.HTTPSConnection('localhost', server.port,
1773 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001774 h.request('GET', '/nonexistent')
1775 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001776 resp.close()
1777 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001778 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001779 # The context's check_hostname setting is used if one isn't passed to
1780 # HTTPSConnection.
1781 context.check_hostname = False
1782 h = client.HTTPSConnection('localhost', server.port, context=context)
1783 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001784 resp = h.getresponse()
1785 self.assertEqual(resp.status, 404)
1786 resp.close()
1787 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001788 # Passing check_hostname to HTTPSConnection should override the
1789 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001790 with support.check_warnings(('', DeprecationWarning)):
1791 h = client.HTTPSConnection('localhost', server.port,
1792 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001793 with self.assertRaises(ssl.CertificateError):
1794 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001795
Petri Lehtinene119c402011-10-26 21:29:15 +03001796 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1797 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001798 def test_host_port(self):
1799 # Check invalid host_port
1800
1801 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1802 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1803
1804 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1805 "fe80::207:e9ff:fe9b", 8000),
1806 ("www.python.org:443", "www.python.org", 443),
1807 ("www.python.org:", "www.python.org", 443),
1808 ("www.python.org", "www.python.org", 443),
1809 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1810 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1811 443)):
1812 c = client.HTTPSConnection(hp)
1813 self.assertEqual(h, c.host)
1814 self.assertEqual(p, c.port)
1815
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001816 def test_tls13_pha(self):
1817 import ssl
1818 if not ssl.HAS_TLSv1_3:
1819 self.skipTest('TLS 1.3 support required')
1820 # just check status of PHA flag
1821 h = client.HTTPSConnection('localhost', 443)
1822 self.assertTrue(h._context.post_handshake_auth)
1823
1824 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1825 self.assertFalse(context.post_handshake_auth)
1826 h = client.HTTPSConnection('localhost', 443, context=context)
1827 self.assertIs(h._context, context)
1828 self.assertFalse(h._context.post_handshake_auth)
1829
Pablo Galindoaa542c22019-08-08 23:25:46 +01001830 with warnings.catch_warnings():
1831 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1832 DeprecationWarning)
1833 h = client.HTTPSConnection('localhost', 443, context=context,
1834 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001835 self.assertTrue(h._context.post_handshake_auth)
1836
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001837
Jeremy Hylton236654b2009-03-27 20:24:34 +00001838class RequestBodyTest(TestCase):
1839 """Test cases where a request includes a message body."""
1840
1841 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001842 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001843 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001844 self.conn.sock = self.sock
1845
1846 def get_headers_and_fp(self):
1847 f = io.BytesIO(self.sock.data)
1848 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001849 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001850 return message, f
1851
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001852 def test_list_body(self):
1853 # Note that no content-length is automatically calculated for
1854 # an iterable. The request will fall back to send chunked
1855 # transfer encoding.
1856 cases = (
1857 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1858 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1859 )
1860 for body, expected in cases:
1861 with self.subTest(body):
1862 self.conn = client.HTTPConnection('example.com')
1863 self.conn.sock = self.sock = FakeSocket('')
1864
1865 self.conn.request('PUT', '/url', body)
1866 msg, f = self.get_headers_and_fp()
1867 self.assertNotIn('Content-Type', msg)
1868 self.assertNotIn('Content-Length', msg)
1869 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1870 self.assertEqual(expected, f.read())
1871
Jeremy Hylton236654b2009-03-27 20:24:34 +00001872 def test_manual_content_length(self):
1873 # Set an incorrect content-length so that we can verify that
1874 # it will not be over-ridden by the library.
1875 self.conn.request("PUT", "/url", "body",
1876 {"Content-Length": "42"})
1877 message, f = self.get_headers_and_fp()
1878 self.assertEqual("42", message.get("content-length"))
1879 self.assertEqual(4, len(f.read()))
1880
1881 def test_ascii_body(self):
1882 self.conn.request("PUT", "/url", "body")
1883 message, f = self.get_headers_and_fp()
1884 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001885 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001886 self.assertEqual("4", message.get("content-length"))
1887 self.assertEqual(b'body', f.read())
1888
1889 def test_latin1_body(self):
1890 self.conn.request("PUT", "/url", "body\xc1")
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("5", message.get("content-length"))
1895 self.assertEqual(b'body\xc1', f.read())
1896
1897 def test_bytes_body(self):
1898 self.conn.request("PUT", "/url", b"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
Martin Panteref91bb22016-08-27 01:39:26 +00001905 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001906 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001907 with open(support.TESTFN, "w") as f:
1908 f.write("body")
1909 with open(support.TESTFN) as f:
1910 self.conn.request("PUT", "/url", f)
1911 message, f = self.get_headers_and_fp()
1912 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001913 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001914 # No content-length will be determined for files; the body
1915 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001916 self.assertIsNone(message.get("content-length"))
1917 self.assertEqual("chunked", message.get("transfer-encoding"))
1918 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001919
1920 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001921 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001922 with open(support.TESTFN, "wb") as f:
1923 f.write(b"body\xc1")
1924 with open(support.TESTFN, "rb") as f:
1925 self.conn.request("PUT", "/url", f)
1926 message, f = self.get_headers_and_fp()
1927 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001928 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001929 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1930 self.assertNotIn("Content-Length", message)
1931 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001932
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001933
1934class HTTPResponseTest(TestCase):
1935
1936 def setUp(self):
1937 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1938 second-value\r\n\r\nText"
1939 sock = FakeSocket(body)
1940 self.resp = client.HTTPResponse(sock)
1941 self.resp.begin()
1942
1943 def test_getting_header(self):
1944 header = self.resp.getheader('My-Header')
1945 self.assertEqual(header, 'first-value, second-value')
1946
1947 header = self.resp.getheader('My-Header', 'some default')
1948 self.assertEqual(header, 'first-value, second-value')
1949
1950 def test_getting_nonexistent_header_with_string_default(self):
1951 header = self.resp.getheader('No-Such-Header', 'default-value')
1952 self.assertEqual(header, 'default-value')
1953
1954 def test_getting_nonexistent_header_with_iterable_default(self):
1955 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1956 self.assertEqual(header, 'default, values')
1957
1958 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1959 self.assertEqual(header, 'default, values')
1960
1961 def test_getting_nonexistent_header_without_default(self):
1962 header = self.resp.getheader('No-Such-Header')
1963 self.assertEqual(header, None)
1964
1965 def test_getting_header_defaultint(self):
1966 header = self.resp.getheader('No-Such-Header',default=42)
1967 self.assertEqual(header, 42)
1968
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001969class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001970 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001971 response_text = (
1972 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1973 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1974 'Content-Length: 42\r\n\r\n'
1975 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001976 self.host = 'proxy.com'
1977 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001978 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001979
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001980 def tearDown(self):
1981 self.conn.close()
1982
Berker Peksagab53ab02015-02-03 12:22:11 +02001983 def _create_connection(self, response_text):
1984 def create_connection(address, timeout=None, source_address=None):
1985 return FakeSocket(response_text, host=address[0], port=address[1])
1986 return create_connection
1987
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001988 def test_set_tunnel_host_port_headers(self):
1989 tunnel_host = 'destination.com'
1990 tunnel_port = 8888
1991 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1992 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1993 headers=tunnel_headers)
1994 self.conn.request('HEAD', '/', '')
1995 self.assertEqual(self.conn.sock.host, self.host)
1996 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1997 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1998 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1999 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
2000
2001 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002002 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002003 self.conn.connect()
2004 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002005 'destination.com')
2006
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002007 def test_connect_with_tunnel(self):
2008 self.conn.set_tunnel('destination.com')
2009 self.conn.request('HEAD', '/', '')
2010 self.assertEqual(self.conn.sock.host, self.host)
2011 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2012 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002013 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002014 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2015 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002016
2017 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002018 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002019
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002020 def test_connect_put_request(self):
2021 self.conn.set_tunnel('destination.com')
2022 self.conn.request('PUT', '/', '')
2023 self.assertEqual(self.conn.sock.host, self.host)
2024 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2025 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2026 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2027
Berker Peksagab53ab02015-02-03 12:22:11 +02002028 def test_tunnel_debuglog(self):
2029 expected_header = 'X-Dummy: 1'
2030 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2031
2032 self.conn.set_debuglevel(1)
2033 self.conn._create_connection = self._create_connection(response_text)
2034 self.conn.set_tunnel('destination.com')
2035
2036 with support.captured_stdout() as output:
2037 self.conn.request('PUT', '/', '')
2038 lines = output.getvalue().splitlines()
2039 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002040
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002041
Thomas Wouters89f507f2006-12-13 04:49:30 +00002042if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002043 unittest.main(verbosity=2)