blob: 65914616c7b5a93e22835100afab8ce7228f8f63 [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
Guido van Rossumd8faa362007-04-27 19:54:29 +00007import socket
Antoine Pitrou88c60c92017-09-18 23:50:44 +02008import threading
Jeremy Hylton121d34a2003-07-08 12:36:58 +00009
Gregory P. Smithb4066372010-01-03 03:28:29 +000010import unittest
11TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000012
Benjamin Petersonee8712c2008-05-20 21:35:26 +000013from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000014
Antoine Pitrou803e6d62010-10-13 10:36:15 +000015here = os.path.dirname(__file__)
16# Self-signed cert file for 'localhost'
17CERT_localhost = os.path.join(here, 'keycert.pem')
18# Self-signed cert file for 'fakehostname'
19CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010020# Self-signed cert file for self-signed.pythontest.net
21CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000022
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000023# constants for testing chunked encoding
24chunked_start = (
25 'HTTP/1.1 200 OK\r\n'
26 'Transfer-Encoding: chunked\r\n\r\n'
27 'a\r\n'
28 'hello worl\r\n'
29 '3\r\n'
30 'd! \r\n'
31 '8\r\n'
32 'and now \r\n'
33 '22\r\n'
34 'for something completely different\r\n'
35)
36chunked_expected = b'hello world! and now for something completely different'
37chunk_extension = ";foo=bar"
38last_chunk = "0\r\n"
39last_chunk_extended = "0" + chunk_extension + "\r\n"
40trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
41chunked_end = "\r\n"
42
Benjamin Petersonee8712c2008-05-20 21:35:26 +000043HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000044
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000045class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040046 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000047 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000048 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000049 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000050 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000051 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010052 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020053 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040054 self.host = host
55 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000056
Jeremy Hylton2c178252004-08-07 16:28:14 +000057 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010058 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000059 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000060
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000061 def makefile(self, mode, bufsize=None):
62 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000063 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000064 # keep the file around so we can check how much was read from it
65 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020066 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000067 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000068
Serhiy Storchakab491e052014-12-01 13:07:45 +020069 def file_close(self):
70 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000071
Senthil Kumaran9da047b2014-04-14 13:07:56 -040072 def close(self):
73 pass
74
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050075 def setsockopt(self, level, optname, value):
76 pass
77
Jeremy Hylton636950f2009-03-28 04:34:21 +000078class EPipeSocket(FakeSocket):
79
80 def __init__(self, text, pipe_trigger):
81 # When sendall() is called with pipe_trigger, raise EPIPE.
82 FakeSocket.__init__(self, text)
83 self.pipe_trigger = pipe_trigger
84
85 def sendall(self, data):
86 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020087 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000088 self.data += data
89
90 def close(self):
91 pass
92
Serhiy Storchaka50254c52013-08-29 11:35:43 +030093class NoEOFBytesIO(io.BytesIO):
94 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000095
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000096 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000097 more from the underlying file than it should.
98 """
99 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000100 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000101 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000102 raise AssertionError('caller tried to read past EOF')
103 return data
104
105 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000106 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000107 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000108 raise AssertionError('caller tried to read past EOF')
109 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000110
R David Murraycae7bdb2015-04-05 19:26:29 -0400111class FakeSocketHTTPConnection(client.HTTPConnection):
112 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
113
114 def __init__(self, *args):
115 self.connections = 0
116 super().__init__('example.com')
117 self.fake_socket_args = args
118 self._create_connection = self.create_connection
119
120 def connect(self):
121 """Count the number of times connect() is invoked"""
122 self.connections += 1
123 return super().connect()
124
125 def create_connection(self, *pos, **kw):
126 return FakeSocket(*self.fake_socket_args)
127
Jeremy Hylton2c178252004-08-07 16:28:14 +0000128class HeaderTests(TestCase):
129 def test_auto_headers(self):
130 # Some headers are added automatically, but should not be added by
131 # .request() if they are explicitly set.
132
Jeremy Hylton2c178252004-08-07 16:28:14 +0000133 class HeaderCountingBuffer(list):
134 def __init__(self):
135 self.count = {}
136 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000137 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000138 if len(kv) > 1:
139 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000140 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000141 self.count.setdefault(lcKey, 0)
142 self.count[lcKey] += 1
143 list.append(self, item)
144
145 for explicit_header in True, False:
146 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000147 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000148 conn.sock = FakeSocket('blahblahblah')
149 conn._buffer = HeaderCountingBuffer()
150
151 body = 'spamspamspam'
152 headers = {}
153 if explicit_header:
154 headers[header] = str(len(body))
155 conn.request('POST', '/', body, headers)
156 self.assertEqual(conn._buffer.count[header.lower()], 1)
157
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800158 def test_content_length_0(self):
159
160 class ContentLengthChecker(list):
161 def __init__(self):
162 list.__init__(self)
163 self.content_length = None
164 def append(self, item):
165 kv = item.split(b':', 1)
166 if len(kv) > 1 and kv[0].lower() == b'content-length':
167 self.content_length = kv[1].strip()
168 list.append(self, item)
169
R David Murraybeed8402015-03-22 15:18:23 -0400170 # Here, we're testing that methods expecting a body get a
171 # content-length set to zero if the body is empty (either None or '')
172 bodies = (None, '')
173 methods_with_body = ('PUT', 'POST', 'PATCH')
174 for method, body in itertools.product(methods_with_body, bodies):
175 conn = client.HTTPConnection('example.com')
176 conn.sock = FakeSocket(None)
177 conn._buffer = ContentLengthChecker()
178 conn.request(method, '/', body)
179 self.assertEqual(
180 conn._buffer.content_length, b'0',
181 'Header Content-Length incorrect on {}'.format(method)
182 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800183
R David Murraybeed8402015-03-22 15:18:23 -0400184 # For these methods, we make sure that content-length is not set when
185 # the body is None because it might cause unexpected behaviour on the
186 # server.
187 methods_without_body = (
188 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
189 )
190 for method in methods_without_body:
191 conn = client.HTTPConnection('example.com')
192 conn.sock = FakeSocket(None)
193 conn._buffer = ContentLengthChecker()
194 conn.request(method, '/', None)
195 self.assertEqual(
196 conn._buffer.content_length, None,
197 'Header Content-Length set for empty body on {}'.format(method)
198 )
199
200 # If the body is set to '', that's considered to be "present but
201 # empty" rather than "missing", so content length would be set, even
202 # for methods that don't expect a body.
203 for method in methods_without_body:
204 conn = client.HTTPConnection('example.com')
205 conn.sock = FakeSocket(None)
206 conn._buffer = ContentLengthChecker()
207 conn.request(method, '/', '')
208 self.assertEqual(
209 conn._buffer.content_length, b'0',
210 'Header Content-Length incorrect on {}'.format(method)
211 )
212
213 # If the body is set, make sure Content-Length is set.
214 for method in itertools.chain(methods_without_body, methods_with_body):
215 conn = client.HTTPConnection('example.com')
216 conn.sock = FakeSocket(None)
217 conn._buffer = ContentLengthChecker()
218 conn.request(method, '/', ' ')
219 self.assertEqual(
220 conn._buffer.content_length, b'1',
221 'Header Content-Length incorrect on {}'.format(method)
222 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800223
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000224 def test_putheader(self):
225 conn = client.HTTPConnection('example.com')
226 conn.sock = FakeSocket(None)
227 conn.putrequest('GET','/')
228 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200229 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000230
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200231 conn.putheader('Foo', ' bar ')
232 self.assertIn(b'Foo: bar ', conn._buffer)
233 conn.putheader('Bar', '\tbaz\t')
234 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
235 conn.putheader('Authorization', 'Bearer mytoken')
236 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
237 conn.putheader('IterHeader', 'IterA', 'IterB')
238 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
239 conn.putheader('LatinHeader', b'\xFF')
240 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
241 conn.putheader('Utf8Header', b'\xc3\x80')
242 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
243 conn.putheader('C1-Control', b'next\x85line')
244 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
245 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
246 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
247 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
248 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
249 conn.putheader('Key Space', 'value')
250 self.assertIn(b'Key Space: value', conn._buffer)
251 conn.putheader('KeySpace ', 'value')
252 self.assertIn(b'KeySpace : value', conn._buffer)
253 conn.putheader(b'Nonbreak\xa0Space', 'value')
254 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
255 conn.putheader(b'\xa0NonbreakSpace', 'value')
256 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
257
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000258 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000259 # Default host header on IPv6 transaction should be wrapped by [] if
260 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000261 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
262 b'Accept-Encoding: identity\r\n\r\n'
263 conn = client.HTTPConnection('[2001::]:81')
264 sock = FakeSocket('')
265 conn.sock = sock
266 conn.request('GET', '/foo')
267 self.assertTrue(sock.data.startswith(expected))
268
269 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
270 b'Accept-Encoding: identity\r\n\r\n'
271 conn = client.HTTPConnection('[2001:102A::]')
272 sock = FakeSocket('')
273 conn.sock = sock
274 conn.request('GET', '/foo')
275 self.assertTrue(sock.data.startswith(expected))
276
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500277 def test_malformed_headers_coped_with(self):
278 # Issue 19996
279 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
280 sock = FakeSocket(body)
281 resp = client.HTTPResponse(sock)
282 resp.begin()
283
284 self.assertEqual(resp.getheader('First'), 'val')
285 self.assertEqual(resp.getheader('Second'), 'val')
286
R David Murraydc1650c2016-09-07 17:44:34 -0400287 def test_parse_all_octets(self):
288 # Ensure no valid header field octet breaks the parser
289 body = (
290 b'HTTP/1.1 200 OK\r\n'
291 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
292 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
293 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
294 b'obs-fold: text\r\n'
295 b' folded with space\r\n'
296 b'\tfolded with tab\r\n'
297 b'Content-Length: 0\r\n'
298 b'\r\n'
299 )
300 sock = FakeSocket(body)
301 resp = client.HTTPResponse(sock)
302 resp.begin()
303 self.assertEqual(resp.getheader('Content-Length'), '0')
304 self.assertEqual(resp.msg['Content-Length'], '0')
305 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
306 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
307 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
308 self.assertEqual(resp.getheader('VCHAR'), vchar)
309 self.assertEqual(resp.msg['VCHAR'], vchar)
310 self.assertIsNotNone(resp.getheader('obs-text'))
311 self.assertIn('obs-text', resp.msg)
312 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
313 self.assertTrue(folded.startswith('text'))
314 self.assertIn(' folded with space', folded)
315 self.assertTrue(folded.endswith('folded with tab'))
316
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200317 def test_invalid_headers(self):
318 conn = client.HTTPConnection('example.com')
319 conn.sock = FakeSocket('')
320 conn.putrequest('GET', '/')
321
322 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
323 # longer allowed in header names
324 cases = (
325 (b'Invalid\r\nName', b'ValidValue'),
326 (b'Invalid\rName', b'ValidValue'),
327 (b'Invalid\nName', b'ValidValue'),
328 (b'\r\nInvalidName', b'ValidValue'),
329 (b'\rInvalidName', b'ValidValue'),
330 (b'\nInvalidName', b'ValidValue'),
331 (b' InvalidName', b'ValidValue'),
332 (b'\tInvalidName', b'ValidValue'),
333 (b'Invalid:Name', b'ValidValue'),
334 (b':InvalidName', b'ValidValue'),
335 (b'ValidName', b'Invalid\r\nValue'),
336 (b'ValidName', b'Invalid\rValue'),
337 (b'ValidName', b'Invalid\nValue'),
338 (b'ValidName', b'InvalidValue\r\n'),
339 (b'ValidName', b'InvalidValue\r'),
340 (b'ValidName', b'InvalidValue\n'),
341 )
342 for name, value in cases:
343 with self.subTest((name, value)):
344 with self.assertRaisesRegex(ValueError, 'Invalid header'):
345 conn.putheader(name, value)
346
Marco Strigl936f03e2018-06-19 15:20:58 +0200347 def test_headers_debuglevel(self):
348 body = (
349 b'HTTP/1.1 200 OK\r\n'
350 b'First: val\r\n'
Matt Houglum461c4162019-04-03 21:36:47 -0700351 b'Second: val1\r\n'
352 b'Second: val2\r\n'
Marco Strigl936f03e2018-06-19 15:20:58 +0200353 )
354 sock = FakeSocket(body)
355 resp = client.HTTPResponse(sock, debuglevel=1)
356 with support.captured_stdout() as output:
357 resp.begin()
358 lines = output.getvalue().splitlines()
359 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
360 self.assertEqual(lines[1], "header: First: val")
Matt Houglum461c4162019-04-03 21:36:47 -0700361 self.assertEqual(lines[2], "header: Second: val1")
362 self.assertEqual(lines[3], "header: Second: val2")
Marco Strigl936f03e2018-06-19 15:20:58 +0200363
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000364
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000365class TransferEncodingTest(TestCase):
366 expected_body = b"It's just a flesh wound"
367
368 def test_endheaders_chunked(self):
369 conn = client.HTTPConnection('example.com')
370 conn.sock = FakeSocket(b'')
371 conn.putrequest('POST', '/')
372 conn.endheaders(self._make_body(), encode_chunked=True)
373
374 _, _, body = self._parse_request(conn.sock.data)
375 body = self._parse_chunked(body)
376 self.assertEqual(body, self.expected_body)
377
378 def test_explicit_headers(self):
379 # explicit chunked
380 conn = client.HTTPConnection('example.com')
381 conn.sock = FakeSocket(b'')
382 # this shouldn't actually be automatically chunk-encoded because the
383 # calling code has explicitly stated that it's taking care of it
384 conn.request(
385 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
386
387 _, headers, body = self._parse_request(conn.sock.data)
388 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
389 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
390 self.assertEqual(body, self.expected_body)
391
392 # explicit chunked, string body
393 conn = client.HTTPConnection('example.com')
394 conn.sock = FakeSocket(b'')
395 conn.request(
396 'POST', '/', self.expected_body.decode('latin-1'),
397 {'Transfer-Encoding': 'chunked'})
398
399 _, headers, body = self._parse_request(conn.sock.data)
400 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
401 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
402 self.assertEqual(body, self.expected_body)
403
404 # User-specified TE, but request() does the chunk encoding
405 conn = client.HTTPConnection('example.com')
406 conn.sock = FakeSocket(b'')
407 conn.request('POST', '/',
408 headers={'Transfer-Encoding': 'gzip, chunked'},
409 encode_chunked=True,
410 body=self._make_body())
411 _, headers, body = self._parse_request(conn.sock.data)
412 self.assertNotIn('content-length', [k.lower() for k in headers])
413 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
414 self.assertEqual(self._parse_chunked(body), self.expected_body)
415
416 def test_request(self):
417 for empty_lines in (False, True,):
418 conn = client.HTTPConnection('example.com')
419 conn.sock = FakeSocket(b'')
420 conn.request(
421 'POST', '/', self._make_body(empty_lines=empty_lines))
422
423 _, headers, body = self._parse_request(conn.sock.data)
424 body = self._parse_chunked(body)
425 self.assertEqual(body, self.expected_body)
426 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
427
428 # Content-Length and Transfer-Encoding SHOULD not be sent in the
429 # same request
430 self.assertNotIn('content-length', [k.lower() for k in headers])
431
Martin Panteref91bb22016-08-27 01:39:26 +0000432 def test_empty_body(self):
433 # Zero-length iterable should be treated like any other iterable
434 conn = client.HTTPConnection('example.com')
435 conn.sock = FakeSocket(b'')
436 conn.request('POST', '/', ())
437 _, headers, body = self._parse_request(conn.sock.data)
438 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
439 self.assertNotIn('content-length', [k.lower() for k in headers])
440 self.assertEqual(body, b"0\r\n\r\n")
441
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000442 def _make_body(self, empty_lines=False):
443 lines = self.expected_body.split(b' ')
444 for idx, line in enumerate(lines):
445 # for testing handling empty lines
446 if empty_lines and idx % 2:
447 yield b''
448 if idx < len(lines) - 1:
449 yield line + b' '
450 else:
451 yield line
452
453 def _parse_request(self, data):
454 lines = data.split(b'\r\n')
455 request = lines[0]
456 headers = {}
457 n = 1
458 while n < len(lines) and len(lines[n]) > 0:
459 key, val = lines[n].split(b':')
460 key = key.decode('latin-1').strip()
461 headers[key] = val.decode('latin-1').strip()
462 n += 1
463
464 return request, headers, b'\r\n'.join(lines[n + 1:])
465
466 def _parse_chunked(self, data):
467 body = []
468 trailers = {}
469 n = 0
470 lines = data.split(b'\r\n')
471 # parse body
472 while True:
473 size, chunk = lines[n:n+2]
474 size = int(size, 16)
475
476 if size == 0:
477 n += 1
478 break
479
480 self.assertEqual(size, len(chunk))
481 body.append(chunk)
482
483 n += 2
484 # we /should/ hit the end chunk, but check against the size of
485 # lines so we're not stuck in an infinite loop should we get
486 # malformed data
487 if n > len(lines):
488 break
489
490 return b''.join(body)
491
492
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493class BasicTest(TestCase):
494 def test_status_lines(self):
495 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000496
Thomas Wouters89f507f2006-12-13 04:49:30 +0000497 body = "HTTP/1.1 200 Ok\r\n\r\nText"
498 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000499 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000500 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200501 self.assertEqual(resp.read(0), b'') # Issue #20007
502 self.assertFalse(resp.isclosed())
503 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000504 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000505 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200506 self.assertFalse(resp.closed)
507 resp.close()
508 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000509
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
511 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000512 resp = client.HTTPResponse(sock)
513 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000514
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000515 def test_bad_status_repr(self):
516 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200517 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000518
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000519 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000520 # if we have Content-Length, HTTPResponse knows when to close itself,
521 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000522 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
523 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000524 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000525 resp.begin()
526 self.assertEqual(resp.read(2), b'Te')
527 self.assertFalse(resp.isclosed())
528 self.assertEqual(resp.read(2), b'xt')
529 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200530 self.assertFalse(resp.closed)
531 resp.close()
532 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000533
Martin Panterce911c32016-03-17 06:42:48 +0000534 def test_mixed_reads(self):
535 # readline() should update the remaining length, so that read() knows
536 # how much data is left and does not raise IncompleteRead
537 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
538 sock = FakeSocket(body)
539 resp = client.HTTPResponse(sock)
540 resp.begin()
541 self.assertEqual(resp.readline(), b'Text\r\n')
542 self.assertFalse(resp.isclosed())
543 self.assertEqual(resp.read(), b'Another')
544 self.assertTrue(resp.isclosed())
545 self.assertFalse(resp.closed)
546 resp.close()
547 self.assertTrue(resp.closed)
548
Antoine Pitrou38d96432011-12-06 22:33:57 +0100549 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000550 # if we have Content-Length, HTTPResponse knows when to close itself,
551 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100552 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
553 sock = FakeSocket(body)
554 resp = client.HTTPResponse(sock)
555 resp.begin()
556 b = bytearray(2)
557 n = resp.readinto(b)
558 self.assertEqual(n, 2)
559 self.assertEqual(bytes(b), b'Te')
560 self.assertFalse(resp.isclosed())
561 n = resp.readinto(b)
562 self.assertEqual(n, 2)
563 self.assertEqual(bytes(b), b'xt')
564 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200565 self.assertFalse(resp.closed)
566 resp.close()
567 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100568
Antoine Pitrou084daa22012-12-15 19:11:54 +0100569 def test_partial_reads_no_content_length(self):
570 # when no length is present, the socket should be gracefully closed when
571 # all data was read
572 body = "HTTP/1.1 200 Ok\r\n\r\nText"
573 sock = FakeSocket(body)
574 resp = client.HTTPResponse(sock)
575 resp.begin()
576 self.assertEqual(resp.read(2), b'Te')
577 self.assertFalse(resp.isclosed())
578 self.assertEqual(resp.read(2), b'xt')
579 self.assertEqual(resp.read(1), b'')
580 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200581 self.assertFalse(resp.closed)
582 resp.close()
583 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100584
Antoine Pitroud20e7742012-12-15 19:22:30 +0100585 def test_partial_readintos_no_content_length(self):
586 # when no length is present, the socket should be gracefully closed when
587 # all data was read
588 body = "HTTP/1.1 200 Ok\r\n\r\nText"
589 sock = FakeSocket(body)
590 resp = client.HTTPResponse(sock)
591 resp.begin()
592 b = bytearray(2)
593 n = resp.readinto(b)
594 self.assertEqual(n, 2)
595 self.assertEqual(bytes(b), b'Te')
596 self.assertFalse(resp.isclosed())
597 n = resp.readinto(b)
598 self.assertEqual(n, 2)
599 self.assertEqual(bytes(b), b'xt')
600 n = resp.readinto(b)
601 self.assertEqual(n, 0)
602 self.assertTrue(resp.isclosed())
603
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100604 def test_partial_reads_incomplete_body(self):
605 # if the server shuts down the connection before the whole
606 # content-length is delivered, the socket is gracefully closed
607 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
608 sock = FakeSocket(body)
609 resp = client.HTTPResponse(sock)
610 resp.begin()
611 self.assertEqual(resp.read(2), b'Te')
612 self.assertFalse(resp.isclosed())
613 self.assertEqual(resp.read(2), b'xt')
614 self.assertEqual(resp.read(1), b'')
615 self.assertTrue(resp.isclosed())
616
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100617 def test_partial_readintos_incomplete_body(self):
618 # if the server shuts down the connection before the whole
619 # content-length is delivered, the socket is gracefully closed
620 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
621 sock = FakeSocket(body)
622 resp = client.HTTPResponse(sock)
623 resp.begin()
624 b = bytearray(2)
625 n = resp.readinto(b)
626 self.assertEqual(n, 2)
627 self.assertEqual(bytes(b), b'Te')
628 self.assertFalse(resp.isclosed())
629 n = resp.readinto(b)
630 self.assertEqual(n, 2)
631 self.assertEqual(bytes(b), b'xt')
632 n = resp.readinto(b)
633 self.assertEqual(n, 0)
634 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200635 self.assertFalse(resp.closed)
636 resp.close()
637 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100638
Thomas Wouters89f507f2006-12-13 04:49:30 +0000639 def test_host_port(self):
640 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000641
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200642 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000643 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000644
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000645 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
646 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000647 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200648 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000649 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200650 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
651 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000652 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000653 self.assertEqual(h, c.host)
654 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000655
Thomas Wouters89f507f2006-12-13 04:49:30 +0000656 def test_response_headers(self):
657 # test response with multiple message headers with the same field name.
658 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000659 'Set-Cookie: Customer="WILE_E_COYOTE"; '
660 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000661 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
662 ' Path="/acme"\r\n'
663 '\r\n'
664 'No body\r\n')
665 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
666 ', '
667 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
668 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000669 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000670 r.begin()
671 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000672 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000673
Thomas Wouters89f507f2006-12-13 04:49:30 +0000674 def test_read_head(self):
675 # Test that the library doesn't attempt to read any data
676 # from a HEAD request. (Tickles SF bug #622042.)
677 sock = FakeSocket(
678 'HTTP/1.1 200 OK\r\n'
679 'Content-Length: 14432\r\n'
680 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300681 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000682 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000683 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000684 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000685 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000686
Antoine Pitrou38d96432011-12-06 22:33:57 +0100687 def test_readinto_head(self):
688 # Test that the library doesn't attempt to read any data
689 # from a HEAD request. (Tickles SF bug #622042.)
690 sock = FakeSocket(
691 'HTTP/1.1 200 OK\r\n'
692 'Content-Length: 14432\r\n'
693 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300694 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100695 resp = client.HTTPResponse(sock, method="HEAD")
696 resp.begin()
697 b = bytearray(5)
698 if resp.readinto(b) != 0:
699 self.fail("Did not expect response from HEAD request")
700 self.assertEqual(bytes(b), b'\x00'*5)
701
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100702 def test_too_many_headers(self):
703 headers = '\r\n'.join('Header%d: foo' % i
704 for i in range(client._MAXHEADERS + 1)) + '\r\n'
705 text = ('HTTP/1.1 200 OK\r\n' + headers)
706 s = FakeSocket(text)
707 r = client.HTTPResponse(s)
708 self.assertRaisesRegex(client.HTTPException,
709 r"got more than \d+ headers", r.begin)
710
Thomas Wouters89f507f2006-12-13 04:49:30 +0000711 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000712 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000713 b'Accept-Encoding: identity\r\n'
714 b'Transfer-Encoding: chunked\r\n'
715 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000716
Brett Cannon77b7de62010-10-29 23:31:11 +0000717 with open(__file__, 'rb') as body:
718 conn = client.HTTPConnection('example.com')
719 sock = FakeSocket(body)
720 conn.sock = sock
721 conn.request('GET', '/foo', body)
722 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
723 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000724
Antoine Pitrouead1d622009-09-29 18:44:53 +0000725 def test_send(self):
726 expected = b'this is a test this is only a test'
727 conn = client.HTTPConnection('example.com')
728 sock = FakeSocket(None)
729 conn.sock = sock
730 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000731 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000732 sock.data = b''
733 conn.send(array.array('b', 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(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000737 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000738
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300739 def test_send_updating_file(self):
740 def data():
741 yield 'data'
742 yield None
743 yield 'data_two'
744
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000745 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300746 mode = 'r'
747 d = data()
748 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000749 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300750
751 expected = b'data'
752
753 conn = client.HTTPConnection('example.com')
754 sock = FakeSocket("")
755 conn.sock = sock
756 conn.send(UpdatingFile())
757 self.assertEqual(sock.data, expected)
758
759
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000760 def test_send_iter(self):
761 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
762 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
763 b'\r\nonetwothree'
764
765 def body():
766 yield b"one"
767 yield b"two"
768 yield b"three"
769
770 conn = client.HTTPConnection('example.com')
771 sock = FakeSocket("")
772 conn.sock = sock
773 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000774 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000775
Nir Sofferad455cd2017-11-06 23:16:37 +0200776 def test_blocksize_request(self):
777 """Check that request() respects the configured block size."""
778 blocksize = 8 # For easy debugging.
779 conn = client.HTTPConnection('example.com', blocksize=blocksize)
780 sock = FakeSocket(None)
781 conn.sock = sock
782 expected = b"a" * blocksize + b"b"
783 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
784 self.assertEqual(sock.sendall_calls, 3)
785 body = sock.data.split(b"\r\n\r\n", 1)[1]
786 self.assertEqual(body, expected)
787
788 def test_blocksize_send(self):
789 """Check that send() respects the configured block size."""
790 blocksize = 8 # For easy debugging.
791 conn = client.HTTPConnection('example.com', blocksize=blocksize)
792 sock = FakeSocket(None)
793 conn.sock = sock
794 expected = b"a" * blocksize + b"b"
795 conn.send(io.BytesIO(expected))
796 self.assertEqual(sock.sendall_calls, 2)
797 self.assertEqual(sock.data, expected)
798
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800799 def test_send_type_error(self):
800 # See: Issue #12676
801 conn = client.HTTPConnection('example.com')
802 conn.sock = FakeSocket('')
803 with self.assertRaises(TypeError):
804 conn.request('POST', 'test', conn)
805
Christian Heimesa612dc02008-02-24 13:08:18 +0000806 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000807 expected = chunked_expected
808 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000809 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000810 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100811 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000812 resp.close()
813
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100814 # Various read sizes
815 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000816 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100817 resp = client.HTTPResponse(sock, method="GET")
818 resp.begin()
819 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
820 resp.close()
821
Christian Heimesa612dc02008-02-24 13:08:18 +0000822 for x in ('', 'foo\r\n'):
823 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000824 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000825 resp.begin()
826 try:
827 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000828 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100829 self.assertEqual(i.partial, expected)
830 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
831 self.assertEqual(repr(i), expected_message)
832 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000833 else:
834 self.fail('IncompleteRead expected')
835 finally:
836 resp.close()
837
Antoine Pitrou38d96432011-12-06 22:33:57 +0100838 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000839
840 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100841 nexpected = len(expected)
842 b = bytearray(128)
843
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000844 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100845 resp = client.HTTPResponse(sock, method="GET")
846 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100847 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100848 self.assertEqual(b[:nexpected], expected)
849 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100850 resp.close()
851
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100852 # Various read sizes
853 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000854 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100855 resp = client.HTTPResponse(sock, method="GET")
856 resp.begin()
857 m = memoryview(b)
858 i = resp.readinto(m[0:n])
859 i += resp.readinto(m[i:n + i])
860 i += resp.readinto(m[i:])
861 self.assertEqual(b[:nexpected], expected)
862 self.assertEqual(i, nexpected)
863 resp.close()
864
Antoine Pitrou38d96432011-12-06 22:33:57 +0100865 for x in ('', 'foo\r\n'):
866 sock = FakeSocket(chunked_start + x)
867 resp = client.HTTPResponse(sock, method="GET")
868 resp.begin()
869 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100870 n = resp.readinto(b)
871 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100872 self.assertEqual(i.partial, expected)
873 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
874 self.assertEqual(repr(i), expected_message)
875 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100876 else:
877 self.fail('IncompleteRead expected')
878 finally:
879 resp.close()
880
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000881 def test_chunked_head(self):
882 chunked_start = (
883 'HTTP/1.1 200 OK\r\n'
884 'Transfer-Encoding: chunked\r\n\r\n'
885 'a\r\n'
886 'hello world\r\n'
887 '1\r\n'
888 'd\r\n'
889 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000890 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000891 resp = client.HTTPResponse(sock, method="HEAD")
892 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000893 self.assertEqual(resp.read(), b'')
894 self.assertEqual(resp.status, 200)
895 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000896 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200897 self.assertFalse(resp.closed)
898 resp.close()
899 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000900
Antoine Pitrou38d96432011-12-06 22:33:57 +0100901 def test_readinto_chunked_head(self):
902 chunked_start = (
903 'HTTP/1.1 200 OK\r\n'
904 'Transfer-Encoding: chunked\r\n\r\n'
905 'a\r\n'
906 'hello world\r\n'
907 '1\r\n'
908 'd\r\n'
909 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000910 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100911 resp = client.HTTPResponse(sock, method="HEAD")
912 resp.begin()
913 b = bytearray(5)
914 n = resp.readinto(b)
915 self.assertEqual(n, 0)
916 self.assertEqual(bytes(b), b'\x00'*5)
917 self.assertEqual(resp.status, 200)
918 self.assertEqual(resp.reason, 'OK')
919 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200920 self.assertFalse(resp.closed)
921 resp.close()
922 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100923
Christian Heimesa612dc02008-02-24 13:08:18 +0000924 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000925 sock = FakeSocket(
926 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000927 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000928 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000929 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100930 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000931
Benjamin Peterson6accb982009-03-02 22:50:25 +0000932 def test_incomplete_read(self):
933 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000934 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000935 resp.begin()
936 try:
937 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000938 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000939 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000940 self.assertEqual(repr(i),
941 "IncompleteRead(7 bytes read, 3 more expected)")
942 self.assertEqual(str(i),
943 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100944 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000945 else:
946 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000947
Jeremy Hylton636950f2009-03-28 04:34:21 +0000948 def test_epipe(self):
949 sock = EPipeSocket(
950 "HTTP/1.0 401 Authorization Required\r\n"
951 "Content-type: text/html\r\n"
952 "WWW-Authenticate: Basic realm=\"example\"\r\n",
953 b"Content-Length")
954 conn = client.HTTPConnection("example.com")
955 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200956 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000957 lambda: conn.request("PUT", "/url", "body"))
958 resp = conn.getresponse()
959 self.assertEqual(401, resp.status)
960 self.assertEqual("Basic realm=\"example\"",
961 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000962
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000963 # Test lines overflowing the max line size (_MAXLINE in http.client)
964
965 def test_overflowing_status_line(self):
966 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
967 resp = client.HTTPResponse(FakeSocket(body))
968 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
969
970 def test_overflowing_header_line(self):
971 body = (
972 'HTTP/1.1 200 OK\r\n'
973 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
974 )
975 resp = client.HTTPResponse(FakeSocket(body))
976 self.assertRaises(client.LineTooLong, resp.begin)
977
978 def test_overflowing_chunked_line(self):
979 body = (
980 'HTTP/1.1 200 OK\r\n'
981 'Transfer-Encoding: chunked\r\n\r\n'
982 + '0' * 65536 + 'a\r\n'
983 'hello world\r\n'
984 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000985 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000986 )
987 resp = client.HTTPResponse(FakeSocket(body))
988 resp.begin()
989 self.assertRaises(client.LineTooLong, resp.read)
990
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800991 def test_early_eof(self):
992 # Test httpresponse with no \r\n termination,
993 body = "HTTP/1.1 200 Ok"
994 sock = FakeSocket(body)
995 resp = client.HTTPResponse(sock)
996 resp.begin()
997 self.assertEqual(resp.read(), b'')
998 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200999 self.assertFalse(resp.closed)
1000 resp.close()
1001 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001002
Serhiy Storchakab491e052014-12-01 13:07:45 +02001003 def test_error_leak(self):
1004 # Test that the socket is not leaked if getresponse() fails
1005 conn = client.HTTPConnection('example.com')
1006 response = None
1007 class Response(client.HTTPResponse):
1008 def __init__(self, *pos, **kw):
1009 nonlocal response
1010 response = self # Avoid garbage collector closing the socket
1011 client.HTTPResponse.__init__(self, *pos, **kw)
1012 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001013 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001014 conn.request('GET', '/')
1015 self.assertRaises(client.BadStatusLine, conn.getresponse)
1016 self.assertTrue(response.closed)
1017 self.assertTrue(conn.sock.file_closed)
1018
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001019 def test_chunked_extension(self):
1020 extra = '3;foo=bar\r\n' + 'abc\r\n'
1021 expected = chunked_expected + b'abc'
1022
1023 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1024 resp = client.HTTPResponse(sock, method="GET")
1025 resp.begin()
1026 self.assertEqual(resp.read(), expected)
1027 resp.close()
1028
1029 def test_chunked_missing_end(self):
1030 """some servers may serve up a short chunked encoding stream"""
1031 expected = chunked_expected
1032 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1033 resp = client.HTTPResponse(sock, method="GET")
1034 resp.begin()
1035 self.assertEqual(resp.read(), expected)
1036 resp.close()
1037
1038 def test_chunked_trailers(self):
1039 """See that trailers are read and ignored"""
1040 expected = chunked_expected
1041 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1042 resp = client.HTTPResponse(sock, method="GET")
1043 resp.begin()
1044 self.assertEqual(resp.read(), expected)
1045 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001046 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001047 resp.close()
1048
1049 def test_chunked_sync(self):
1050 """Check that we don't read past the end of the chunked-encoding stream"""
1051 expected = chunked_expected
1052 extradata = "extradata"
1053 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1054 resp = client.HTTPResponse(sock, method="GET")
1055 resp.begin()
1056 self.assertEqual(resp.read(), expected)
1057 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001058 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001059 resp.close()
1060
1061 def test_content_length_sync(self):
1062 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001063 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001064 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001065 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 +00001066 resp = client.HTTPResponse(sock, method="GET")
1067 resp.begin()
1068 self.assertEqual(resp.read(), expected)
1069 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001070 self.assertEqual(sock.file.read(), extradata) #we read to the end
1071 resp.close()
1072
1073 def test_readlines_content_length(self):
1074 extradata = b"extradata"
1075 expected = b"Hello123\r\n"
1076 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1077 resp = client.HTTPResponse(sock, method="GET")
1078 resp.begin()
1079 self.assertEqual(resp.readlines(2000), [expected])
1080 # the file should now have our extradata ready to be read
1081 self.assertEqual(sock.file.read(), extradata) #we read to the end
1082 resp.close()
1083
1084 def test_read1_content_length(self):
1085 extradata = b"extradata"
1086 expected = b"Hello123\r\n"
1087 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1088 resp = client.HTTPResponse(sock, method="GET")
1089 resp.begin()
1090 self.assertEqual(resp.read1(2000), expected)
1091 # the file should now have our extradata ready to be read
1092 self.assertEqual(sock.file.read(), extradata) #we read to the end
1093 resp.close()
1094
1095 def test_readline_bound_content_length(self):
1096 extradata = b"extradata"
1097 expected = b"Hello123\r\n"
1098 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1099 resp = client.HTTPResponse(sock, method="GET")
1100 resp.begin()
1101 self.assertEqual(resp.readline(10), expected)
1102 self.assertEqual(resp.readline(10), b"")
1103 # the file should now have our extradata ready to be read
1104 self.assertEqual(sock.file.read(), extradata) #we read to the end
1105 resp.close()
1106
1107 def test_read1_bound_content_length(self):
1108 extradata = b"extradata"
1109 expected = b"Hello123\r\n"
1110 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1111 resp = client.HTTPResponse(sock, method="GET")
1112 resp.begin()
1113 self.assertEqual(resp.read1(20), expected*2)
1114 self.assertEqual(resp.read(), expected)
1115 # the file should now have our extradata ready to be read
1116 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001117 resp.close()
1118
Martin Panterd979b2c2016-04-09 14:03:17 +00001119 def test_response_fileno(self):
1120 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001121 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001122 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001123
1124 result = None
1125 def run_server():
1126 [conn, address] = serv.accept()
1127 with conn, conn.makefile("rb") as reader:
1128 # Read the request header until a blank line
1129 while True:
1130 line = reader.readline()
1131 if not line.rstrip(b"\r\n"):
1132 break
1133 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1134 nonlocal result
1135 result = reader.read()
1136
1137 thread = threading.Thread(target=run_server)
1138 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001139 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001140 conn = client.HTTPConnection(*serv.getsockname())
1141 conn.request("CONNECT", "dummy:1234")
1142 response = conn.getresponse()
1143 try:
1144 self.assertEqual(response.status, client.OK)
1145 s = socket.socket(fileno=response.fileno())
1146 try:
1147 s.sendall(b"proxied data\n")
1148 finally:
1149 s.detach()
1150 finally:
1151 response.close()
1152 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001153 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001154 self.assertEqual(result, b"proxied data\n")
1155
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001156class ExtendedReadTest(TestCase):
1157 """
1158 Test peek(), read1(), readline()
1159 """
1160 lines = (
1161 'HTTP/1.1 200 OK\r\n'
1162 '\r\n'
1163 'hello world!\n'
1164 'and now \n'
1165 'for something completely different\n'
1166 'foo'
1167 )
1168 lines_expected = lines[lines.find('hello'):].encode("ascii")
1169 lines_chunked = (
1170 'HTTP/1.1 200 OK\r\n'
1171 'Transfer-Encoding: chunked\r\n\r\n'
1172 'a\r\n'
1173 'hello worl\r\n'
1174 '3\r\n'
1175 'd!\n\r\n'
1176 '9\r\n'
1177 'and now \n\r\n'
1178 '23\r\n'
1179 'for something completely different\n\r\n'
1180 '3\r\n'
1181 'foo\r\n'
1182 '0\r\n' # terminating chunk
1183 '\r\n' # end of trailers
1184 )
1185
1186 def setUp(self):
1187 sock = FakeSocket(self.lines)
1188 resp = client.HTTPResponse(sock, method="GET")
1189 resp.begin()
1190 resp.fp = io.BufferedReader(resp.fp)
1191 self.resp = resp
1192
1193
1194
1195 def test_peek(self):
1196 resp = self.resp
1197 # patch up the buffered peek so that it returns not too much stuff
1198 oldpeek = resp.fp.peek
1199 def mypeek(n=-1):
1200 p = oldpeek(n)
1201 if n >= 0:
1202 return p[:n]
1203 return p[:10]
1204 resp.fp.peek = mypeek
1205
1206 all = []
1207 while True:
1208 # try a short peek
1209 p = resp.peek(3)
1210 if p:
1211 self.assertGreater(len(p), 0)
1212 # then unbounded peek
1213 p2 = resp.peek()
1214 self.assertGreaterEqual(len(p2), len(p))
1215 self.assertTrue(p2.startswith(p))
1216 next = resp.read(len(p2))
1217 self.assertEqual(next, p2)
1218 else:
1219 next = resp.read()
1220 self.assertFalse(next)
1221 all.append(next)
1222 if not next:
1223 break
1224 self.assertEqual(b"".join(all), self.lines_expected)
1225
1226 def test_readline(self):
1227 resp = self.resp
1228 self._verify_readline(self.resp.readline, self.lines_expected)
1229
1230 def _verify_readline(self, readline, expected):
1231 all = []
1232 while True:
1233 # short readlines
1234 line = readline(5)
1235 if line and line != b"foo":
1236 if len(line) < 5:
1237 self.assertTrue(line.endswith(b"\n"))
1238 all.append(line)
1239 if not line:
1240 break
1241 self.assertEqual(b"".join(all), expected)
1242
1243 def test_read1(self):
1244 resp = self.resp
1245 def r():
1246 res = resp.read1(4)
1247 self.assertLessEqual(len(res), 4)
1248 return res
1249 readliner = Readliner(r)
1250 self._verify_readline(readliner.readline, self.lines_expected)
1251
1252 def test_read1_unbounded(self):
1253 resp = self.resp
1254 all = []
1255 while True:
1256 data = resp.read1()
1257 if not data:
1258 break
1259 all.append(data)
1260 self.assertEqual(b"".join(all), self.lines_expected)
1261
1262 def test_read1_bounded(self):
1263 resp = self.resp
1264 all = []
1265 while True:
1266 data = resp.read1(10)
1267 if not data:
1268 break
1269 self.assertLessEqual(len(data), 10)
1270 all.append(data)
1271 self.assertEqual(b"".join(all), self.lines_expected)
1272
1273 def test_read1_0(self):
1274 self.assertEqual(self.resp.read1(0), b"")
1275
1276 def test_peek_0(self):
1277 p = self.resp.peek(0)
1278 self.assertLessEqual(0, len(p))
1279
1280class ExtendedReadTestChunked(ExtendedReadTest):
1281 """
1282 Test peek(), read1(), readline() in chunked mode
1283 """
1284 lines = (
1285 'HTTP/1.1 200 OK\r\n'
1286 'Transfer-Encoding: chunked\r\n\r\n'
1287 'a\r\n'
1288 'hello worl\r\n'
1289 '3\r\n'
1290 'd!\n\r\n'
1291 '9\r\n'
1292 'and now \n\r\n'
1293 '23\r\n'
1294 'for something completely different\n\r\n'
1295 '3\r\n'
1296 'foo\r\n'
1297 '0\r\n' # terminating chunk
1298 '\r\n' # end of trailers
1299 )
1300
1301
1302class Readliner:
1303 """
1304 a simple readline class that uses an arbitrary read function and buffering
1305 """
1306 def __init__(self, readfunc):
1307 self.readfunc = readfunc
1308 self.remainder = b""
1309
1310 def readline(self, limit):
1311 data = []
1312 datalen = 0
1313 read = self.remainder
1314 try:
1315 while True:
1316 idx = read.find(b'\n')
1317 if idx != -1:
1318 break
1319 if datalen + len(read) >= limit:
1320 idx = limit - datalen - 1
1321 # read more data
1322 data.append(read)
1323 read = self.readfunc()
1324 if not read:
1325 idx = 0 #eof condition
1326 break
1327 idx += 1
1328 data.append(read[:idx])
1329 self.remainder = read[idx:]
1330 return b"".join(data)
1331 except:
1332 self.remainder = b"".join(data)
1333 raise
1334
Berker Peksagbabc6882015-02-20 09:39:38 +02001335
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001336class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001337 def test_all(self):
1338 # Documented objects defined in the module should be in __all__
1339 expected = {"responses"} # White-list documented dict() object
1340 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1341 # intentionally omitted for simplicity
1342 blacklist = {"HTTPMessage", "parse_headers"}
1343 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001344 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001345 continue
1346 module_object = getattr(client, name)
1347 if getattr(module_object, "__module__", None) == "http.client":
1348 expected.add(name)
1349 self.assertCountEqual(client.__all__, expected)
1350
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001351 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001352 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001353
Berker Peksagabbf0f42015-02-20 14:57:31 +02001354 def test_client_constants(self):
1355 # Make sure we don't break backward compatibility with 3.4
1356 expected = [
1357 'CONTINUE',
1358 'SWITCHING_PROTOCOLS',
1359 'PROCESSING',
1360 'OK',
1361 'CREATED',
1362 'ACCEPTED',
1363 'NON_AUTHORITATIVE_INFORMATION',
1364 'NO_CONTENT',
1365 'RESET_CONTENT',
1366 'PARTIAL_CONTENT',
1367 'MULTI_STATUS',
1368 'IM_USED',
1369 'MULTIPLE_CHOICES',
1370 'MOVED_PERMANENTLY',
1371 'FOUND',
1372 'SEE_OTHER',
1373 'NOT_MODIFIED',
1374 'USE_PROXY',
1375 'TEMPORARY_REDIRECT',
1376 'BAD_REQUEST',
1377 'UNAUTHORIZED',
1378 'PAYMENT_REQUIRED',
1379 'FORBIDDEN',
1380 'NOT_FOUND',
1381 'METHOD_NOT_ALLOWED',
1382 'NOT_ACCEPTABLE',
1383 'PROXY_AUTHENTICATION_REQUIRED',
1384 'REQUEST_TIMEOUT',
1385 'CONFLICT',
1386 'GONE',
1387 'LENGTH_REQUIRED',
1388 'PRECONDITION_FAILED',
1389 'REQUEST_ENTITY_TOO_LARGE',
1390 'REQUEST_URI_TOO_LONG',
1391 'UNSUPPORTED_MEDIA_TYPE',
1392 'REQUESTED_RANGE_NOT_SATISFIABLE',
1393 'EXPECTATION_FAILED',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001394 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001395 'UNPROCESSABLE_ENTITY',
1396 'LOCKED',
1397 'FAILED_DEPENDENCY',
1398 'UPGRADE_REQUIRED',
1399 'PRECONDITION_REQUIRED',
1400 'TOO_MANY_REQUESTS',
1401 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1402 'INTERNAL_SERVER_ERROR',
1403 'NOT_IMPLEMENTED',
1404 'BAD_GATEWAY',
1405 'SERVICE_UNAVAILABLE',
1406 'GATEWAY_TIMEOUT',
1407 'HTTP_VERSION_NOT_SUPPORTED',
1408 'INSUFFICIENT_STORAGE',
1409 'NOT_EXTENDED',
1410 'NETWORK_AUTHENTICATION_REQUIRED',
1411 ]
1412 for const in expected:
1413 with self.subTest(constant=const):
1414 self.assertTrue(hasattr(client, const))
1415
Gregory P. Smithb4066372010-01-03 03:28:29 +00001416
1417class SourceAddressTest(TestCase):
1418 def setUp(self):
1419 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1420 self.port = support.bind_port(self.serv)
1421 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001422 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001423 self.conn = None
1424
1425 def tearDown(self):
1426 if self.conn:
1427 self.conn.close()
1428 self.conn = None
1429 self.serv.close()
1430 self.serv = None
1431
1432 def testHTTPConnectionSourceAddress(self):
1433 self.conn = client.HTTPConnection(HOST, self.port,
1434 source_address=('', self.source_port))
1435 self.conn.connect()
1436 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1437
1438 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1439 'http.client.HTTPSConnection not defined')
1440 def testHTTPSConnectionSourceAddress(self):
1441 self.conn = client.HTTPSConnection(HOST, self.port,
1442 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001443 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001444 # this code doesn't deal with setting up an active running SSL server
1445 # for an ssl_wrapped connect() to actually return from.
1446
1447
Guido van Rossumd8faa362007-04-27 19:54:29 +00001448class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001449 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001450
1451 def setUp(self):
1452 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001453 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001454 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001455
1456 def tearDown(self):
1457 self.serv.close()
1458 self.serv = None
1459
1460 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001461 # This will prove that the timeout gets through HTTPConnection
1462 # and into the socket.
1463
Georg Brandlf78e02b2008-06-10 17:40:04 +00001464 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001465 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001466 socket.setdefaulttimeout(30)
1467 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001468 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001469 httpConn.connect()
1470 finally:
1471 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001472 self.assertEqual(httpConn.sock.gettimeout(), 30)
1473 httpConn.close()
1474
Georg Brandlf78e02b2008-06-10 17:40:04 +00001475 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001476 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001477 socket.setdefaulttimeout(30)
1478 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001479 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001480 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481 httpConn.connect()
1482 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001483 socket.setdefaulttimeout(None)
1484 self.assertEqual(httpConn.sock.gettimeout(), None)
1485 httpConn.close()
1486
1487 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001488 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001489 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001490 self.assertEqual(httpConn.sock.gettimeout(), 30)
1491 httpConn.close()
1492
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001493
R David Murraycae7bdb2015-04-05 19:26:29 -04001494class PersistenceTest(TestCase):
1495
1496 def test_reuse_reconnect(self):
1497 # Should reuse or reconnect depending on header from server
1498 tests = (
1499 ('1.0', '', False),
1500 ('1.0', 'Connection: keep-alive\r\n', True),
1501 ('1.1', '', True),
1502 ('1.1', 'Connection: close\r\n', False),
1503 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1504 ('1.1', 'Connection: cloSE\r\n', False),
1505 )
1506 for version, header, reuse in tests:
1507 with self.subTest(version=version, header=header):
1508 msg = (
1509 'HTTP/{} 200 OK\r\n'
1510 '{}'
1511 'Content-Length: 12\r\n'
1512 '\r\n'
1513 'Dummy body\r\n'
1514 ).format(version, header)
1515 conn = FakeSocketHTTPConnection(msg)
1516 self.assertIsNone(conn.sock)
1517 conn.request('GET', '/open-connection')
1518 with conn.getresponse() as response:
1519 self.assertEqual(conn.sock is None, not reuse)
1520 response.read()
1521 self.assertEqual(conn.sock is None, not reuse)
1522 self.assertEqual(conn.connections, 1)
1523 conn.request('GET', '/subsequent-request')
1524 self.assertEqual(conn.connections, 1 if reuse else 2)
1525
1526 def test_disconnected(self):
1527
1528 def make_reset_reader(text):
1529 """Return BufferedReader that raises ECONNRESET at EOF"""
1530 stream = io.BytesIO(text)
1531 def readinto(buffer):
1532 size = io.BytesIO.readinto(stream, buffer)
1533 if size == 0:
1534 raise ConnectionResetError()
1535 return size
1536 stream.readinto = readinto
1537 return io.BufferedReader(stream)
1538
1539 tests = (
1540 (io.BytesIO, client.RemoteDisconnected),
1541 (make_reset_reader, ConnectionResetError),
1542 )
1543 for stream_factory, exception in tests:
1544 with self.subTest(exception=exception):
1545 conn = FakeSocketHTTPConnection(b'', stream_factory)
1546 conn.request('GET', '/eof-response')
1547 self.assertRaises(exception, conn.getresponse)
1548 self.assertIsNone(conn.sock)
1549 # HTTPConnection.connect() should be automatically invoked
1550 conn.request('GET', '/reconnect')
1551 self.assertEqual(conn.connections, 2)
1552
1553 def test_100_close(self):
1554 conn = FakeSocketHTTPConnection(
1555 b'HTTP/1.1 100 Continue\r\n'
1556 b'\r\n'
1557 # Missing final response
1558 )
1559 conn.request('GET', '/', headers={'Expect': '100-continue'})
1560 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1561 self.assertIsNone(conn.sock)
1562 conn.request('GET', '/reconnect')
1563 self.assertEqual(conn.connections, 2)
1564
1565
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001566class HTTPSTest(TestCase):
1567
1568 def setUp(self):
1569 if not hasattr(client, 'HTTPSConnection'):
1570 self.skipTest('ssl support required')
1571
1572 def make_server(self, certfile):
1573 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001574 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001575
1576 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001577 # simple test to check it's storing the timeout
1578 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1579 self.assertEqual(h.timeout, 30)
1580
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001581 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001582 # Default settings: requires a valid cert from a trusted CA
1583 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001584 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001585 with support.transient_internet('self-signed.pythontest.net'):
1586 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1587 with self.assertRaises(ssl.SSLError) as exc_info:
1588 h.request('GET', '/')
1589 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1590
1591 def test_networked_noverification(self):
1592 # Switch off cert verification
1593 import ssl
1594 support.requires('network')
1595 with support.transient_internet('self-signed.pythontest.net'):
1596 context = ssl._create_unverified_context()
1597 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1598 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001599 h.request('GET', '/')
1600 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001601 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001602 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001603 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001604
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001605 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001606 def test_networked_trusted_by_default_cert(self):
1607 # Default settings: requires a valid cert from a trusted CA
1608 support.requires('network')
1609 with support.transient_internet('www.python.org'):
1610 h = client.HTTPSConnection('www.python.org', 443)
1611 h.request('GET', '/')
1612 resp = h.getresponse()
1613 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001614 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001615 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001616 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001617
1618 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001619 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001620 import ssl
1621 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +01001622 with support.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001623 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1624 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1625 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001626 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
1627 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001628 h.request('GET', '/')
1629 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001630 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001631 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001632 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001633 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001634
1635 def test_networked_bad_cert(self):
1636 # We feed a "CA" cert that is unrelated to the server's cert
1637 import ssl
1638 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001639 with support.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001640 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001641 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001642 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1643 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001644 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001645 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1646
1647 def test_local_unknown_cert(self):
1648 # The custom cert isn't known to the default trust bundle
1649 import ssl
1650 server = self.make_server(CERT_localhost)
1651 h = client.HTTPSConnection('localhost', server.port)
1652 with self.assertRaises(ssl.SSLError) as exc_info:
1653 h.request('GET', '/')
1654 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001655
1656 def test_local_good_hostname(self):
1657 # The (valid) cert validates the HTTP hostname
1658 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001659 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001660 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001661 context.load_verify_locations(CERT_localhost)
1662 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001663 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001664 h.request('GET', '/nonexistent')
1665 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001666 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001667 self.assertEqual(resp.status, 404)
1668
1669 def test_local_bad_hostname(self):
1670 # The (valid) cert doesn't validate the HTTP hostname
1671 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001672 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001673 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001674 context.load_verify_locations(CERT_fakehostname)
1675 h = client.HTTPSConnection('localhost', server.port, context=context)
1676 with self.assertRaises(ssl.CertificateError):
1677 h.request('GET', '/')
1678 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001679 with support.check_warnings(('', DeprecationWarning)):
1680 h = client.HTTPSConnection('localhost', server.port,
1681 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001682 with self.assertRaises(ssl.CertificateError):
1683 h.request('GET', '/')
1684 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001685 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001686 with support.check_warnings(('', DeprecationWarning)):
1687 h = client.HTTPSConnection('localhost', server.port,
1688 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001689 h.request('GET', '/nonexistent')
1690 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001691 resp.close()
1692 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001693 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001694 # The context's check_hostname setting is used if one isn't passed to
1695 # HTTPSConnection.
1696 context.check_hostname = False
1697 h = client.HTTPSConnection('localhost', server.port, context=context)
1698 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001699 resp = h.getresponse()
1700 self.assertEqual(resp.status, 404)
1701 resp.close()
1702 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001703 # Passing check_hostname to HTTPSConnection should override the
1704 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001705 with support.check_warnings(('', DeprecationWarning)):
1706 h = client.HTTPSConnection('localhost', server.port,
1707 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001708 with self.assertRaises(ssl.CertificateError):
1709 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001710
Petri Lehtinene119c402011-10-26 21:29:15 +03001711 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1712 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001713 def test_host_port(self):
1714 # Check invalid host_port
1715
1716 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1717 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1718
1719 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1720 "fe80::207:e9ff:fe9b", 8000),
1721 ("www.python.org:443", "www.python.org", 443),
1722 ("www.python.org:", "www.python.org", 443),
1723 ("www.python.org", "www.python.org", 443),
1724 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1725 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1726 443)):
1727 c = client.HTTPSConnection(hp)
1728 self.assertEqual(h, c.host)
1729 self.assertEqual(p, c.port)
1730
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001731
Jeremy Hylton236654b2009-03-27 20:24:34 +00001732class RequestBodyTest(TestCase):
1733 """Test cases where a request includes a message body."""
1734
1735 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001736 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001737 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001738 self.conn.sock = self.sock
1739
1740 def get_headers_and_fp(self):
1741 f = io.BytesIO(self.sock.data)
1742 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001743 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001744 return message, f
1745
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001746 def test_list_body(self):
1747 # Note that no content-length is automatically calculated for
1748 # an iterable. The request will fall back to send chunked
1749 # transfer encoding.
1750 cases = (
1751 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1752 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1753 )
1754 for body, expected in cases:
1755 with self.subTest(body):
1756 self.conn = client.HTTPConnection('example.com')
1757 self.conn.sock = self.sock = FakeSocket('')
1758
1759 self.conn.request('PUT', '/url', body)
1760 msg, f = self.get_headers_and_fp()
1761 self.assertNotIn('Content-Type', msg)
1762 self.assertNotIn('Content-Length', msg)
1763 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1764 self.assertEqual(expected, f.read())
1765
Jeremy Hylton236654b2009-03-27 20:24:34 +00001766 def test_manual_content_length(self):
1767 # Set an incorrect content-length so that we can verify that
1768 # it will not be over-ridden by the library.
1769 self.conn.request("PUT", "/url", "body",
1770 {"Content-Length": "42"})
1771 message, f = self.get_headers_and_fp()
1772 self.assertEqual("42", message.get("content-length"))
1773 self.assertEqual(4, len(f.read()))
1774
1775 def test_ascii_body(self):
1776 self.conn.request("PUT", "/url", "body")
1777 message, f = self.get_headers_and_fp()
1778 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001779 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001780 self.assertEqual("4", message.get("content-length"))
1781 self.assertEqual(b'body', f.read())
1782
1783 def test_latin1_body(self):
1784 self.conn.request("PUT", "/url", "body\xc1")
1785 message, f = self.get_headers_and_fp()
1786 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001787 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001788 self.assertEqual("5", message.get("content-length"))
1789 self.assertEqual(b'body\xc1', f.read())
1790
1791 def test_bytes_body(self):
1792 self.conn.request("PUT", "/url", b"body\xc1")
1793 message, f = self.get_headers_and_fp()
1794 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001795 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001796 self.assertEqual("5", message.get("content-length"))
1797 self.assertEqual(b'body\xc1', f.read())
1798
Martin Panteref91bb22016-08-27 01:39:26 +00001799 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001800 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001801 with open(support.TESTFN, "w") as f:
1802 f.write("body")
1803 with open(support.TESTFN) as f:
1804 self.conn.request("PUT", "/url", f)
1805 message, f = self.get_headers_and_fp()
1806 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001807 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001808 # No content-length will be determined for files; the body
1809 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001810 self.assertIsNone(message.get("content-length"))
1811 self.assertEqual("chunked", message.get("transfer-encoding"))
1812 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001813
1814 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001815 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001816 with open(support.TESTFN, "wb") as f:
1817 f.write(b"body\xc1")
1818 with open(support.TESTFN, "rb") as f:
1819 self.conn.request("PUT", "/url", f)
1820 message, f = self.get_headers_and_fp()
1821 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001822 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001823 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1824 self.assertNotIn("Content-Length", message)
1825 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001826
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001827
1828class HTTPResponseTest(TestCase):
1829
1830 def setUp(self):
1831 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1832 second-value\r\n\r\nText"
1833 sock = FakeSocket(body)
1834 self.resp = client.HTTPResponse(sock)
1835 self.resp.begin()
1836
1837 def test_getting_header(self):
1838 header = self.resp.getheader('My-Header')
1839 self.assertEqual(header, 'first-value, second-value')
1840
1841 header = self.resp.getheader('My-Header', 'some default')
1842 self.assertEqual(header, 'first-value, second-value')
1843
1844 def test_getting_nonexistent_header_with_string_default(self):
1845 header = self.resp.getheader('No-Such-Header', 'default-value')
1846 self.assertEqual(header, 'default-value')
1847
1848 def test_getting_nonexistent_header_with_iterable_default(self):
1849 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1850 self.assertEqual(header, 'default, values')
1851
1852 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1853 self.assertEqual(header, 'default, values')
1854
1855 def test_getting_nonexistent_header_without_default(self):
1856 header = self.resp.getheader('No-Such-Header')
1857 self.assertEqual(header, None)
1858
1859 def test_getting_header_defaultint(self):
1860 header = self.resp.getheader('No-Such-Header',default=42)
1861 self.assertEqual(header, 42)
1862
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001863class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001864 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001865 response_text = (
1866 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1867 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1868 'Content-Length: 42\r\n\r\n'
1869 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001870 self.host = 'proxy.com'
1871 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001872 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001873
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001874 def tearDown(self):
1875 self.conn.close()
1876
Berker Peksagab53ab02015-02-03 12:22:11 +02001877 def _create_connection(self, response_text):
1878 def create_connection(address, timeout=None, source_address=None):
1879 return FakeSocket(response_text, host=address[0], port=address[1])
1880 return create_connection
1881
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001882 def test_set_tunnel_host_port_headers(self):
1883 tunnel_host = 'destination.com'
1884 tunnel_port = 8888
1885 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1886 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1887 headers=tunnel_headers)
1888 self.conn.request('HEAD', '/', '')
1889 self.assertEqual(self.conn.sock.host, self.host)
1890 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1891 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1892 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1893 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1894
1895 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001896 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001897 self.conn.connect()
1898 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001899 'destination.com')
1900
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001901 def test_connect_with_tunnel(self):
1902 self.conn.set_tunnel('destination.com')
1903 self.conn.request('HEAD', '/', '')
1904 self.assertEqual(self.conn.sock.host, self.host)
1905 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1906 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001907 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001908 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1909 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001910
1911 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001912 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001913
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001914 def test_connect_put_request(self):
1915 self.conn.set_tunnel('destination.com')
1916 self.conn.request('PUT', '/', '')
1917 self.assertEqual(self.conn.sock.host, self.host)
1918 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1919 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1920 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1921
Berker Peksagab53ab02015-02-03 12:22:11 +02001922 def test_tunnel_debuglog(self):
1923 expected_header = 'X-Dummy: 1'
1924 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1925
1926 self.conn.set_debuglevel(1)
1927 self.conn._create_connection = self._create_connection(response_text)
1928 self.conn.set_tunnel('destination.com')
1929
1930 with support.captured_stdout() as output:
1931 self.conn.request('PUT', '/', '')
1932 lines = output.getvalue().splitlines()
1933 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001934
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001935
Thomas Wouters89f507f2006-12-13 04:49:30 +00001936if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04001937 unittest.main(verbosity=2)