blob: 656932fbaab7a43dde5912faf192c954d915bc70 [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
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000016
Antoine Pitrou803e6d62010-10-13 10:36:15 +000017here = os.path.dirname(__file__)
18# Self-signed cert file for 'localhost'
19CERT_localhost = os.path.join(here, 'keycert.pem')
20# Self-signed cert file for 'fakehostname'
21CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010022# Self-signed cert file for self-signed.pythontest.net
23CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000024
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000025# constants for testing chunked encoding
26chunked_start = (
27 'HTTP/1.1 200 OK\r\n'
28 'Transfer-Encoding: chunked\r\n\r\n'
29 'a\r\n'
30 'hello worl\r\n'
31 '3\r\n'
32 'd! \r\n'
33 '8\r\n'
34 'and now \r\n'
35 '22\r\n'
36 'for something completely different\r\n'
37)
38chunked_expected = b'hello world! and now for something completely different'
39chunk_extension = ";foo=bar"
40last_chunk = "0\r\n"
41last_chunk_extended = "0" + chunk_extension + "\r\n"
42trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
43chunked_end = "\r\n"
44
Benjamin Petersonee8712c2008-05-20 21:35:26 +000045HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000046
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000047class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040048 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000049 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000050 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000051 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000052 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000053 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010054 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020055 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040056 self.host = host
57 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000058
Jeremy Hylton2c178252004-08-07 16:28:14 +000059 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010060 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000061 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000062
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000063 def makefile(self, mode, bufsize=None):
64 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000065 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000066 # keep the file around so we can check how much was read from it
67 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020068 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000069 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000070
Serhiy Storchakab491e052014-12-01 13:07:45 +020071 def file_close(self):
72 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000073
Senthil Kumaran9da047b2014-04-14 13:07:56 -040074 def close(self):
75 pass
76
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050077 def setsockopt(self, level, optname, value):
78 pass
79
Jeremy Hylton636950f2009-03-28 04:34:21 +000080class EPipeSocket(FakeSocket):
81
82 def __init__(self, text, pipe_trigger):
83 # When sendall() is called with pipe_trigger, raise EPIPE.
84 FakeSocket.__init__(self, text)
85 self.pipe_trigger = pipe_trigger
86
87 def sendall(self, data):
88 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020089 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000090 self.data += data
91
92 def close(self):
93 pass
94
Serhiy Storchaka50254c52013-08-29 11:35:43 +030095class NoEOFBytesIO(io.BytesIO):
96 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000097
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000098 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000099 more from the underlying file than it should.
100 """
101 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000102 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000103 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000104 raise AssertionError('caller tried to read past EOF')
105 return data
106
107 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000108 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000109 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000110 raise AssertionError('caller tried to read past EOF')
111 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000112
R David Murraycae7bdb2015-04-05 19:26:29 -0400113class FakeSocketHTTPConnection(client.HTTPConnection):
114 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
115
116 def __init__(self, *args):
117 self.connections = 0
118 super().__init__('example.com')
119 self.fake_socket_args = args
120 self._create_connection = self.create_connection
121
122 def connect(self):
123 """Count the number of times connect() is invoked"""
124 self.connections += 1
125 return super().connect()
126
127 def create_connection(self, *pos, **kw):
128 return FakeSocket(*self.fake_socket_args)
129
Jeremy Hylton2c178252004-08-07 16:28:14 +0000130class HeaderTests(TestCase):
131 def test_auto_headers(self):
132 # Some headers are added automatically, but should not be added by
133 # .request() if they are explicitly set.
134
Jeremy Hylton2c178252004-08-07 16:28:14 +0000135 class HeaderCountingBuffer(list):
136 def __init__(self):
137 self.count = {}
138 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000139 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000140 if len(kv) > 1:
141 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000142 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000143 self.count.setdefault(lcKey, 0)
144 self.count[lcKey] += 1
145 list.append(self, item)
146
147 for explicit_header in True, False:
148 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000149 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000150 conn.sock = FakeSocket('blahblahblah')
151 conn._buffer = HeaderCountingBuffer()
152
153 body = 'spamspamspam'
154 headers = {}
155 if explicit_header:
156 headers[header] = str(len(body))
157 conn.request('POST', '/', body, headers)
158 self.assertEqual(conn._buffer.count[header.lower()], 1)
159
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800160 def test_content_length_0(self):
161
162 class ContentLengthChecker(list):
163 def __init__(self):
164 list.__init__(self)
165 self.content_length = None
166 def append(self, item):
167 kv = item.split(b':', 1)
168 if len(kv) > 1 and kv[0].lower() == b'content-length':
169 self.content_length = kv[1].strip()
170 list.append(self, item)
171
R David Murraybeed8402015-03-22 15:18:23 -0400172 # Here, we're testing that methods expecting a body get a
173 # content-length set to zero if the body is empty (either None or '')
174 bodies = (None, '')
175 methods_with_body = ('PUT', 'POST', 'PATCH')
176 for method, body in itertools.product(methods_with_body, bodies):
177 conn = client.HTTPConnection('example.com')
178 conn.sock = FakeSocket(None)
179 conn._buffer = ContentLengthChecker()
180 conn.request(method, '/', body)
181 self.assertEqual(
182 conn._buffer.content_length, b'0',
183 'Header Content-Length incorrect on {}'.format(method)
184 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800185
R David Murraybeed8402015-03-22 15:18:23 -0400186 # For these methods, we make sure that content-length is not set when
187 # the body is None because it might cause unexpected behaviour on the
188 # server.
189 methods_without_body = (
190 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
191 )
192 for method in methods_without_body:
193 conn = client.HTTPConnection('example.com')
194 conn.sock = FakeSocket(None)
195 conn._buffer = ContentLengthChecker()
196 conn.request(method, '/', None)
197 self.assertEqual(
198 conn._buffer.content_length, None,
199 'Header Content-Length set for empty body on {}'.format(method)
200 )
201
202 # If the body is set to '', that's considered to be "present but
203 # empty" rather than "missing", so content length would be set, even
204 # for methods that don't expect a body.
205 for method in methods_without_body:
206 conn = client.HTTPConnection('example.com')
207 conn.sock = FakeSocket(None)
208 conn._buffer = ContentLengthChecker()
209 conn.request(method, '/', '')
210 self.assertEqual(
211 conn._buffer.content_length, b'0',
212 'Header Content-Length incorrect on {}'.format(method)
213 )
214
215 # If the body is set, make sure Content-Length is set.
216 for method in itertools.chain(methods_without_body, methods_with_body):
217 conn = client.HTTPConnection('example.com')
218 conn.sock = FakeSocket(None)
219 conn._buffer = ContentLengthChecker()
220 conn.request(method, '/', ' ')
221 self.assertEqual(
222 conn._buffer.content_length, b'1',
223 'Header Content-Length incorrect on {}'.format(method)
224 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800225
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000226 def test_putheader(self):
227 conn = client.HTTPConnection('example.com')
228 conn.sock = FakeSocket(None)
229 conn.putrequest('GET','/')
230 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200231 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000232
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200233 conn.putheader('Foo', ' bar ')
234 self.assertIn(b'Foo: bar ', conn._buffer)
235 conn.putheader('Bar', '\tbaz\t')
236 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
237 conn.putheader('Authorization', 'Bearer mytoken')
238 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
239 conn.putheader('IterHeader', 'IterA', 'IterB')
240 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
241 conn.putheader('LatinHeader', b'\xFF')
242 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
243 conn.putheader('Utf8Header', b'\xc3\x80')
244 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
245 conn.putheader('C1-Control', b'next\x85line')
246 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
247 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
248 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
249 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
250 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
251 conn.putheader('Key Space', 'value')
252 self.assertIn(b'Key Space: value', conn._buffer)
253 conn.putheader('KeySpace ', 'value')
254 self.assertIn(b'KeySpace : value', conn._buffer)
255 conn.putheader(b'Nonbreak\xa0Space', 'value')
256 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
257 conn.putheader(b'\xa0NonbreakSpace', 'value')
258 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
259
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000260 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000261 # Default host header on IPv6 transaction should be wrapped by [] if
262 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000263 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
264 b'Accept-Encoding: identity\r\n\r\n'
265 conn = client.HTTPConnection('[2001::]:81')
266 sock = FakeSocket('')
267 conn.sock = sock
268 conn.request('GET', '/foo')
269 self.assertTrue(sock.data.startswith(expected))
270
271 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
272 b'Accept-Encoding: identity\r\n\r\n'
273 conn = client.HTTPConnection('[2001:102A::]')
274 sock = FakeSocket('')
275 conn.sock = sock
276 conn.request('GET', '/foo')
277 self.assertTrue(sock.data.startswith(expected))
278
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500279 def test_malformed_headers_coped_with(self):
280 # Issue 19996
281 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
282 sock = FakeSocket(body)
283 resp = client.HTTPResponse(sock)
284 resp.begin()
285
286 self.assertEqual(resp.getheader('First'), 'val')
287 self.assertEqual(resp.getheader('Second'), 'val')
288
R David Murraydc1650c2016-09-07 17:44:34 -0400289 def test_parse_all_octets(self):
290 # Ensure no valid header field octet breaks the parser
291 body = (
292 b'HTTP/1.1 200 OK\r\n'
293 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
294 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
295 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
296 b'obs-fold: text\r\n'
297 b' folded with space\r\n'
298 b'\tfolded with tab\r\n'
299 b'Content-Length: 0\r\n'
300 b'\r\n'
301 )
302 sock = FakeSocket(body)
303 resp = client.HTTPResponse(sock)
304 resp.begin()
305 self.assertEqual(resp.getheader('Content-Length'), '0')
306 self.assertEqual(resp.msg['Content-Length'], '0')
307 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
308 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
309 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
310 self.assertEqual(resp.getheader('VCHAR'), vchar)
311 self.assertEqual(resp.msg['VCHAR'], vchar)
312 self.assertIsNotNone(resp.getheader('obs-text'))
313 self.assertIn('obs-text', resp.msg)
314 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
315 self.assertTrue(folded.startswith('text'))
316 self.assertIn(' folded with space', folded)
317 self.assertTrue(folded.endswith('folded with tab'))
318
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200319 def test_invalid_headers(self):
320 conn = client.HTTPConnection('example.com')
321 conn.sock = FakeSocket('')
322 conn.putrequest('GET', '/')
323
324 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
325 # longer allowed in header names
326 cases = (
327 (b'Invalid\r\nName', b'ValidValue'),
328 (b'Invalid\rName', b'ValidValue'),
329 (b'Invalid\nName', b'ValidValue'),
330 (b'\r\nInvalidName', b'ValidValue'),
331 (b'\rInvalidName', b'ValidValue'),
332 (b'\nInvalidName', b'ValidValue'),
333 (b' InvalidName', b'ValidValue'),
334 (b'\tInvalidName', b'ValidValue'),
335 (b'Invalid:Name', b'ValidValue'),
336 (b':InvalidName', b'ValidValue'),
337 (b'ValidName', b'Invalid\r\nValue'),
338 (b'ValidName', b'Invalid\rValue'),
339 (b'ValidName', b'Invalid\nValue'),
340 (b'ValidName', b'InvalidValue\r\n'),
341 (b'ValidName', b'InvalidValue\r'),
342 (b'ValidName', b'InvalidValue\n'),
343 )
344 for name, value in cases:
345 with self.subTest((name, value)):
346 with self.assertRaisesRegex(ValueError, 'Invalid header'):
347 conn.putheader(name, value)
348
Marco Strigl936f03e2018-06-19 15:20:58 +0200349 def test_headers_debuglevel(self):
350 body = (
351 b'HTTP/1.1 200 OK\r\n'
352 b'First: val\r\n'
Matt Houglum461c4162019-04-03 21:36:47 -0700353 b'Second: val1\r\n'
354 b'Second: val2\r\n'
Marco Strigl936f03e2018-06-19 15:20:58 +0200355 )
356 sock = FakeSocket(body)
357 resp = client.HTTPResponse(sock, debuglevel=1)
358 with support.captured_stdout() as output:
359 resp.begin()
360 lines = output.getvalue().splitlines()
361 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
362 self.assertEqual(lines[1], "header: First: val")
Matt Houglum461c4162019-04-03 21:36:47 -0700363 self.assertEqual(lines[2], "header: Second: val1")
364 self.assertEqual(lines[3], "header: Second: val2")
Marco Strigl936f03e2018-06-19 15:20:58 +0200365
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000366
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000367class TransferEncodingTest(TestCase):
368 expected_body = b"It's just a flesh wound"
369
370 def test_endheaders_chunked(self):
371 conn = client.HTTPConnection('example.com')
372 conn.sock = FakeSocket(b'')
373 conn.putrequest('POST', '/')
374 conn.endheaders(self._make_body(), encode_chunked=True)
375
376 _, _, body = self._parse_request(conn.sock.data)
377 body = self._parse_chunked(body)
378 self.assertEqual(body, self.expected_body)
379
380 def test_explicit_headers(self):
381 # explicit chunked
382 conn = client.HTTPConnection('example.com')
383 conn.sock = FakeSocket(b'')
384 # this shouldn't actually be automatically chunk-encoded because the
385 # calling code has explicitly stated that it's taking care of it
386 conn.request(
387 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
388
389 _, headers, body = self._parse_request(conn.sock.data)
390 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
391 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
392 self.assertEqual(body, self.expected_body)
393
394 # explicit chunked, string body
395 conn = client.HTTPConnection('example.com')
396 conn.sock = FakeSocket(b'')
397 conn.request(
398 'POST', '/', self.expected_body.decode('latin-1'),
399 {'Transfer-Encoding': 'chunked'})
400
401 _, headers, body = self._parse_request(conn.sock.data)
402 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
403 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
404 self.assertEqual(body, self.expected_body)
405
406 # User-specified TE, but request() does the chunk encoding
407 conn = client.HTTPConnection('example.com')
408 conn.sock = FakeSocket(b'')
409 conn.request('POST', '/',
410 headers={'Transfer-Encoding': 'gzip, chunked'},
411 encode_chunked=True,
412 body=self._make_body())
413 _, headers, body = self._parse_request(conn.sock.data)
414 self.assertNotIn('content-length', [k.lower() for k in headers])
415 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
416 self.assertEqual(self._parse_chunked(body), self.expected_body)
417
418 def test_request(self):
419 for empty_lines in (False, True,):
420 conn = client.HTTPConnection('example.com')
421 conn.sock = FakeSocket(b'')
422 conn.request(
423 'POST', '/', self._make_body(empty_lines=empty_lines))
424
425 _, headers, body = self._parse_request(conn.sock.data)
426 body = self._parse_chunked(body)
427 self.assertEqual(body, self.expected_body)
428 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
429
430 # Content-Length and Transfer-Encoding SHOULD not be sent in the
431 # same request
432 self.assertNotIn('content-length', [k.lower() for k in headers])
433
Martin Panteref91bb22016-08-27 01:39:26 +0000434 def test_empty_body(self):
435 # Zero-length iterable should be treated like any other iterable
436 conn = client.HTTPConnection('example.com')
437 conn.sock = FakeSocket(b'')
438 conn.request('POST', '/', ())
439 _, headers, body = self._parse_request(conn.sock.data)
440 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
441 self.assertNotIn('content-length', [k.lower() for k in headers])
442 self.assertEqual(body, b"0\r\n\r\n")
443
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000444 def _make_body(self, empty_lines=False):
445 lines = self.expected_body.split(b' ')
446 for idx, line in enumerate(lines):
447 # for testing handling empty lines
448 if empty_lines and idx % 2:
449 yield b''
450 if idx < len(lines) - 1:
451 yield line + b' '
452 else:
453 yield line
454
455 def _parse_request(self, data):
456 lines = data.split(b'\r\n')
457 request = lines[0]
458 headers = {}
459 n = 1
460 while n < len(lines) and len(lines[n]) > 0:
461 key, val = lines[n].split(b':')
462 key = key.decode('latin-1').strip()
463 headers[key] = val.decode('latin-1').strip()
464 n += 1
465
466 return request, headers, b'\r\n'.join(lines[n + 1:])
467
468 def _parse_chunked(self, data):
469 body = []
470 trailers = {}
471 n = 0
472 lines = data.split(b'\r\n')
473 # parse body
474 while True:
475 size, chunk = lines[n:n+2]
476 size = int(size, 16)
477
478 if size == 0:
479 n += 1
480 break
481
482 self.assertEqual(size, len(chunk))
483 body.append(chunk)
484
485 n += 2
486 # we /should/ hit the end chunk, but check against the size of
487 # lines so we're not stuck in an infinite loop should we get
488 # malformed data
489 if n > len(lines):
490 break
491
492 return b''.join(body)
493
494
Thomas Wouters89f507f2006-12-13 04:49:30 +0000495class BasicTest(TestCase):
496 def test_status_lines(self):
497 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000498
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 body = "HTTP/1.1 200 Ok\r\n\r\nText"
500 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000501 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000502 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200503 self.assertEqual(resp.read(0), b'') # Issue #20007
504 self.assertFalse(resp.isclosed())
505 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000506 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000507 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200508 self.assertFalse(resp.closed)
509 resp.close()
510 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000511
Thomas Wouters89f507f2006-12-13 04:49:30 +0000512 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
513 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000514 resp = client.HTTPResponse(sock)
515 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000516
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000517 def test_bad_status_repr(self):
518 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200519 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000520
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000521 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000522 # if we have Content-Length, HTTPResponse knows when to close itself,
523 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000524 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
525 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000526 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000527 resp.begin()
528 self.assertEqual(resp.read(2), b'Te')
529 self.assertFalse(resp.isclosed())
530 self.assertEqual(resp.read(2), b'xt')
531 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200532 self.assertFalse(resp.closed)
533 resp.close()
534 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000535
Martin Panterce911c32016-03-17 06:42:48 +0000536 def test_mixed_reads(self):
537 # readline() should update the remaining length, so that read() knows
538 # how much data is left and does not raise IncompleteRead
539 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
540 sock = FakeSocket(body)
541 resp = client.HTTPResponse(sock)
542 resp.begin()
543 self.assertEqual(resp.readline(), b'Text\r\n')
544 self.assertFalse(resp.isclosed())
545 self.assertEqual(resp.read(), b'Another')
546 self.assertTrue(resp.isclosed())
547 self.assertFalse(resp.closed)
548 resp.close()
549 self.assertTrue(resp.closed)
550
Antoine Pitrou38d96432011-12-06 22:33:57 +0100551 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000552 # if we have Content-Length, HTTPResponse knows when to close itself,
553 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100554 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
555 sock = FakeSocket(body)
556 resp = client.HTTPResponse(sock)
557 resp.begin()
558 b = bytearray(2)
559 n = resp.readinto(b)
560 self.assertEqual(n, 2)
561 self.assertEqual(bytes(b), b'Te')
562 self.assertFalse(resp.isclosed())
563 n = resp.readinto(b)
564 self.assertEqual(n, 2)
565 self.assertEqual(bytes(b), b'xt')
566 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200567 self.assertFalse(resp.closed)
568 resp.close()
569 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100570
Antoine Pitrou084daa22012-12-15 19:11:54 +0100571 def test_partial_reads_no_content_length(self):
572 # when no length is present, the socket should be gracefully closed when
573 # all data was read
574 body = "HTTP/1.1 200 Ok\r\n\r\nText"
575 sock = FakeSocket(body)
576 resp = client.HTTPResponse(sock)
577 resp.begin()
578 self.assertEqual(resp.read(2), b'Te')
579 self.assertFalse(resp.isclosed())
580 self.assertEqual(resp.read(2), b'xt')
581 self.assertEqual(resp.read(1), b'')
582 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200583 self.assertFalse(resp.closed)
584 resp.close()
585 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100586
Antoine Pitroud20e7742012-12-15 19:22:30 +0100587 def test_partial_readintos_no_content_length(self):
588 # when no length is present, the socket should be gracefully closed when
589 # all data was read
590 body = "HTTP/1.1 200 Ok\r\n\r\nText"
591 sock = FakeSocket(body)
592 resp = client.HTTPResponse(sock)
593 resp.begin()
594 b = bytearray(2)
595 n = resp.readinto(b)
596 self.assertEqual(n, 2)
597 self.assertEqual(bytes(b), b'Te')
598 self.assertFalse(resp.isclosed())
599 n = resp.readinto(b)
600 self.assertEqual(n, 2)
601 self.assertEqual(bytes(b), b'xt')
602 n = resp.readinto(b)
603 self.assertEqual(n, 0)
604 self.assertTrue(resp.isclosed())
605
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100606 def test_partial_reads_incomplete_body(self):
607 # if the server shuts down the connection before the whole
608 # content-length is delivered, the socket is gracefully closed
609 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
610 sock = FakeSocket(body)
611 resp = client.HTTPResponse(sock)
612 resp.begin()
613 self.assertEqual(resp.read(2), b'Te')
614 self.assertFalse(resp.isclosed())
615 self.assertEqual(resp.read(2), b'xt')
616 self.assertEqual(resp.read(1), b'')
617 self.assertTrue(resp.isclosed())
618
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100619 def test_partial_readintos_incomplete_body(self):
620 # if the server shuts down the connection before the whole
621 # content-length is delivered, the socket is gracefully closed
622 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
623 sock = FakeSocket(body)
624 resp = client.HTTPResponse(sock)
625 resp.begin()
626 b = bytearray(2)
627 n = resp.readinto(b)
628 self.assertEqual(n, 2)
629 self.assertEqual(bytes(b), b'Te')
630 self.assertFalse(resp.isclosed())
631 n = resp.readinto(b)
632 self.assertEqual(n, 2)
633 self.assertEqual(bytes(b), b'xt')
634 n = resp.readinto(b)
635 self.assertEqual(n, 0)
636 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200637 self.assertFalse(resp.closed)
638 resp.close()
639 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100640
Thomas Wouters89f507f2006-12-13 04:49:30 +0000641 def test_host_port(self):
642 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000643
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200644 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000645 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000646
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000647 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
648 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000649 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200650 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000651 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200652 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
653 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000654 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000655 self.assertEqual(h, c.host)
656 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000657
Thomas Wouters89f507f2006-12-13 04:49:30 +0000658 def test_response_headers(self):
659 # test response with multiple message headers with the same field name.
660 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000661 'Set-Cookie: Customer="WILE_E_COYOTE"; '
662 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000663 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
664 ' Path="/acme"\r\n'
665 '\r\n'
666 'No body\r\n')
667 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
668 ', '
669 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
670 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000671 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000672 r.begin()
673 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000674 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000675
Thomas Wouters89f507f2006-12-13 04:49:30 +0000676 def test_read_head(self):
677 # Test that the library doesn't attempt to read any data
678 # from a HEAD request. (Tickles SF bug #622042.)
679 sock = FakeSocket(
680 'HTTP/1.1 200 OK\r\n'
681 'Content-Length: 14432\r\n'
682 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300683 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000684 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000685 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000686 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000687 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000688
Antoine Pitrou38d96432011-12-06 22:33:57 +0100689 def test_readinto_head(self):
690 # Test that the library doesn't attempt to read any data
691 # from a HEAD request. (Tickles SF bug #622042.)
692 sock = FakeSocket(
693 'HTTP/1.1 200 OK\r\n'
694 'Content-Length: 14432\r\n'
695 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300696 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100697 resp = client.HTTPResponse(sock, method="HEAD")
698 resp.begin()
699 b = bytearray(5)
700 if resp.readinto(b) != 0:
701 self.fail("Did not expect response from HEAD request")
702 self.assertEqual(bytes(b), b'\x00'*5)
703
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100704 def test_too_many_headers(self):
705 headers = '\r\n'.join('Header%d: foo' % i
706 for i in range(client._MAXHEADERS + 1)) + '\r\n'
707 text = ('HTTP/1.1 200 OK\r\n' + headers)
708 s = FakeSocket(text)
709 r = client.HTTPResponse(s)
710 self.assertRaisesRegex(client.HTTPException,
711 r"got more than \d+ headers", r.begin)
712
Thomas Wouters89f507f2006-12-13 04:49:30 +0000713 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000714 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000715 b'Accept-Encoding: identity\r\n'
716 b'Transfer-Encoding: chunked\r\n'
717 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000718
Brett Cannon77b7de62010-10-29 23:31:11 +0000719 with open(__file__, 'rb') as body:
720 conn = client.HTTPConnection('example.com')
721 sock = FakeSocket(body)
722 conn.sock = sock
723 conn.request('GET', '/foo', body)
724 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
725 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000726
Antoine Pitrouead1d622009-09-29 18:44:53 +0000727 def test_send(self):
728 expected = b'this is a test this is only a test'
729 conn = client.HTTPConnection('example.com')
730 sock = FakeSocket(None)
731 conn.sock = sock
732 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000733 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000734 sock.data = b''
735 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000736 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000737 sock.data = b''
738 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000739 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000740
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300741 def test_send_updating_file(self):
742 def data():
743 yield 'data'
744 yield None
745 yield 'data_two'
746
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000747 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300748 mode = 'r'
749 d = data()
750 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000751 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300752
753 expected = b'data'
754
755 conn = client.HTTPConnection('example.com')
756 sock = FakeSocket("")
757 conn.sock = sock
758 conn.send(UpdatingFile())
759 self.assertEqual(sock.data, expected)
760
761
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000762 def test_send_iter(self):
763 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
764 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
765 b'\r\nonetwothree'
766
767 def body():
768 yield b"one"
769 yield b"two"
770 yield b"three"
771
772 conn = client.HTTPConnection('example.com')
773 sock = FakeSocket("")
774 conn.sock = sock
775 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000776 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000777
Nir Sofferad455cd2017-11-06 23:16:37 +0200778 def test_blocksize_request(self):
779 """Check that request() respects the configured block size."""
780 blocksize = 8 # For easy debugging.
781 conn = client.HTTPConnection('example.com', blocksize=blocksize)
782 sock = FakeSocket(None)
783 conn.sock = sock
784 expected = b"a" * blocksize + b"b"
785 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
786 self.assertEqual(sock.sendall_calls, 3)
787 body = sock.data.split(b"\r\n\r\n", 1)[1]
788 self.assertEqual(body, expected)
789
790 def test_blocksize_send(self):
791 """Check that send() respects the configured block size."""
792 blocksize = 8 # For easy debugging.
793 conn = client.HTTPConnection('example.com', blocksize=blocksize)
794 sock = FakeSocket(None)
795 conn.sock = sock
796 expected = b"a" * blocksize + b"b"
797 conn.send(io.BytesIO(expected))
798 self.assertEqual(sock.sendall_calls, 2)
799 self.assertEqual(sock.data, expected)
800
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800801 def test_send_type_error(self):
802 # See: Issue #12676
803 conn = client.HTTPConnection('example.com')
804 conn.sock = FakeSocket('')
805 with self.assertRaises(TypeError):
806 conn.request('POST', 'test', conn)
807
Christian Heimesa612dc02008-02-24 13:08:18 +0000808 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000809 expected = chunked_expected
810 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000811 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000812 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100813 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000814 resp.close()
815
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100816 # Various read sizes
817 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000818 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100819 resp = client.HTTPResponse(sock, method="GET")
820 resp.begin()
821 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
822 resp.close()
823
Christian Heimesa612dc02008-02-24 13:08:18 +0000824 for x in ('', 'foo\r\n'):
825 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000826 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000827 resp.begin()
828 try:
829 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000830 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100831 self.assertEqual(i.partial, expected)
832 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
833 self.assertEqual(repr(i), expected_message)
834 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000835 else:
836 self.fail('IncompleteRead expected')
837 finally:
838 resp.close()
839
Antoine Pitrou38d96432011-12-06 22:33:57 +0100840 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000841
842 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100843 nexpected = len(expected)
844 b = bytearray(128)
845
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000846 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100847 resp = client.HTTPResponse(sock, method="GET")
848 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100849 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100850 self.assertEqual(b[:nexpected], expected)
851 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100852 resp.close()
853
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100854 # Various read sizes
855 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000856 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100857 resp = client.HTTPResponse(sock, method="GET")
858 resp.begin()
859 m = memoryview(b)
860 i = resp.readinto(m[0:n])
861 i += resp.readinto(m[i:n + i])
862 i += resp.readinto(m[i:])
863 self.assertEqual(b[:nexpected], expected)
864 self.assertEqual(i, nexpected)
865 resp.close()
866
Antoine Pitrou38d96432011-12-06 22:33:57 +0100867 for x in ('', 'foo\r\n'):
868 sock = FakeSocket(chunked_start + x)
869 resp = client.HTTPResponse(sock, method="GET")
870 resp.begin()
871 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100872 n = resp.readinto(b)
873 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100874 self.assertEqual(i.partial, expected)
875 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
876 self.assertEqual(repr(i), expected_message)
877 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100878 else:
879 self.fail('IncompleteRead expected')
880 finally:
881 resp.close()
882
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000883 def test_chunked_head(self):
884 chunked_start = (
885 'HTTP/1.1 200 OK\r\n'
886 'Transfer-Encoding: chunked\r\n\r\n'
887 'a\r\n'
888 'hello world\r\n'
889 '1\r\n'
890 'd\r\n'
891 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000892 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000893 resp = client.HTTPResponse(sock, method="HEAD")
894 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000895 self.assertEqual(resp.read(), b'')
896 self.assertEqual(resp.status, 200)
897 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000898 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200899 self.assertFalse(resp.closed)
900 resp.close()
901 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000902
Antoine Pitrou38d96432011-12-06 22:33:57 +0100903 def test_readinto_chunked_head(self):
904 chunked_start = (
905 'HTTP/1.1 200 OK\r\n'
906 'Transfer-Encoding: chunked\r\n\r\n'
907 'a\r\n'
908 'hello world\r\n'
909 '1\r\n'
910 'd\r\n'
911 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000912 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100913 resp = client.HTTPResponse(sock, method="HEAD")
914 resp.begin()
915 b = bytearray(5)
916 n = resp.readinto(b)
917 self.assertEqual(n, 0)
918 self.assertEqual(bytes(b), b'\x00'*5)
919 self.assertEqual(resp.status, 200)
920 self.assertEqual(resp.reason, 'OK')
921 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200922 self.assertFalse(resp.closed)
923 resp.close()
924 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100925
Christian Heimesa612dc02008-02-24 13:08:18 +0000926 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000927 sock = FakeSocket(
928 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000929 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000930 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000931 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100932 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000933
Benjamin Peterson6accb982009-03-02 22:50:25 +0000934 def test_incomplete_read(self):
935 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000936 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000937 resp.begin()
938 try:
939 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000940 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000941 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000942 self.assertEqual(repr(i),
943 "IncompleteRead(7 bytes read, 3 more expected)")
944 self.assertEqual(str(i),
945 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100946 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000947 else:
948 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000949
Jeremy Hylton636950f2009-03-28 04:34:21 +0000950 def test_epipe(self):
951 sock = EPipeSocket(
952 "HTTP/1.0 401 Authorization Required\r\n"
953 "Content-type: text/html\r\n"
954 "WWW-Authenticate: Basic realm=\"example\"\r\n",
955 b"Content-Length")
956 conn = client.HTTPConnection("example.com")
957 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200958 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000959 lambda: conn.request("PUT", "/url", "body"))
960 resp = conn.getresponse()
961 self.assertEqual(401, resp.status)
962 self.assertEqual("Basic realm=\"example\"",
963 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000964
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000965 # Test lines overflowing the max line size (_MAXLINE in http.client)
966
967 def test_overflowing_status_line(self):
968 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
969 resp = client.HTTPResponse(FakeSocket(body))
970 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
971
972 def test_overflowing_header_line(self):
973 body = (
974 'HTTP/1.1 200 OK\r\n'
975 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
976 )
977 resp = client.HTTPResponse(FakeSocket(body))
978 self.assertRaises(client.LineTooLong, resp.begin)
979
980 def test_overflowing_chunked_line(self):
981 body = (
982 'HTTP/1.1 200 OK\r\n'
983 'Transfer-Encoding: chunked\r\n\r\n'
984 + '0' * 65536 + 'a\r\n'
985 'hello world\r\n'
986 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000987 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000988 )
989 resp = client.HTTPResponse(FakeSocket(body))
990 resp.begin()
991 self.assertRaises(client.LineTooLong, resp.read)
992
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800993 def test_early_eof(self):
994 # Test httpresponse with no \r\n termination,
995 body = "HTTP/1.1 200 Ok"
996 sock = FakeSocket(body)
997 resp = client.HTTPResponse(sock)
998 resp.begin()
999 self.assertEqual(resp.read(), b'')
1000 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001001 self.assertFalse(resp.closed)
1002 resp.close()
1003 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001004
Serhiy Storchakab491e052014-12-01 13:07:45 +02001005 def test_error_leak(self):
1006 # Test that the socket is not leaked if getresponse() fails
1007 conn = client.HTTPConnection('example.com')
1008 response = None
1009 class Response(client.HTTPResponse):
1010 def __init__(self, *pos, **kw):
1011 nonlocal response
1012 response = self # Avoid garbage collector closing the socket
1013 client.HTTPResponse.__init__(self, *pos, **kw)
1014 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001015 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001016 conn.request('GET', '/')
1017 self.assertRaises(client.BadStatusLine, conn.getresponse)
1018 self.assertTrue(response.closed)
1019 self.assertTrue(conn.sock.file_closed)
1020
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001021 def test_chunked_extension(self):
1022 extra = '3;foo=bar\r\n' + 'abc\r\n'
1023 expected = chunked_expected + b'abc'
1024
1025 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1026 resp = client.HTTPResponse(sock, method="GET")
1027 resp.begin()
1028 self.assertEqual(resp.read(), expected)
1029 resp.close()
1030
1031 def test_chunked_missing_end(self):
1032 """some servers may serve up a short chunked encoding stream"""
1033 expected = chunked_expected
1034 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1035 resp = client.HTTPResponse(sock, method="GET")
1036 resp.begin()
1037 self.assertEqual(resp.read(), expected)
1038 resp.close()
1039
1040 def test_chunked_trailers(self):
1041 """See that trailers are read and ignored"""
1042 expected = chunked_expected
1043 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1044 resp = client.HTTPResponse(sock, method="GET")
1045 resp.begin()
1046 self.assertEqual(resp.read(), expected)
1047 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001048 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001049 resp.close()
1050
1051 def test_chunked_sync(self):
1052 """Check that we don't read past the end of the chunked-encoding stream"""
1053 expected = chunked_expected
1054 extradata = "extradata"
1055 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1056 resp = client.HTTPResponse(sock, method="GET")
1057 resp.begin()
1058 self.assertEqual(resp.read(), expected)
1059 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001060 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001061 resp.close()
1062
1063 def test_content_length_sync(self):
1064 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001065 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001066 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001067 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 +00001068 resp = client.HTTPResponse(sock, method="GET")
1069 resp.begin()
1070 self.assertEqual(resp.read(), expected)
1071 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001072 self.assertEqual(sock.file.read(), extradata) #we read to the end
1073 resp.close()
1074
1075 def test_readlines_content_length(self):
1076 extradata = b"extradata"
1077 expected = b"Hello123\r\n"
1078 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1079 resp = client.HTTPResponse(sock, method="GET")
1080 resp.begin()
1081 self.assertEqual(resp.readlines(2000), [expected])
1082 # the file should now have our extradata ready to be read
1083 self.assertEqual(sock.file.read(), extradata) #we read to the end
1084 resp.close()
1085
1086 def test_read1_content_length(self):
1087 extradata = b"extradata"
1088 expected = b"Hello123\r\n"
1089 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1090 resp = client.HTTPResponse(sock, method="GET")
1091 resp.begin()
1092 self.assertEqual(resp.read1(2000), expected)
1093 # the file should now have our extradata ready to be read
1094 self.assertEqual(sock.file.read(), extradata) #we read to the end
1095 resp.close()
1096
1097 def test_readline_bound_content_length(self):
1098 extradata = b"extradata"
1099 expected = b"Hello123\r\n"
1100 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1101 resp = client.HTTPResponse(sock, method="GET")
1102 resp.begin()
1103 self.assertEqual(resp.readline(10), expected)
1104 self.assertEqual(resp.readline(10), b"")
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_bound_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: 30\r\n\r\n' + expected*3 + extradata)
1113 resp = client.HTTPResponse(sock, method="GET")
1114 resp.begin()
1115 self.assertEqual(resp.read1(20), expected*2)
1116 self.assertEqual(resp.read(), expected)
1117 # the file should now have our extradata ready to be read
1118 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001119 resp.close()
1120
Martin Panterd979b2c2016-04-09 14:03:17 +00001121 def test_response_fileno(self):
1122 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001123 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001124 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001125
1126 result = None
1127 def run_server():
1128 [conn, address] = serv.accept()
1129 with conn, conn.makefile("rb") as reader:
1130 # Read the request header until a blank line
1131 while True:
1132 line = reader.readline()
1133 if not line.rstrip(b"\r\n"):
1134 break
1135 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1136 nonlocal result
1137 result = reader.read()
1138
1139 thread = threading.Thread(target=run_server)
1140 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001141 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001142 conn = client.HTTPConnection(*serv.getsockname())
1143 conn.request("CONNECT", "dummy:1234")
1144 response = conn.getresponse()
1145 try:
1146 self.assertEqual(response.status, client.OK)
1147 s = socket.socket(fileno=response.fileno())
1148 try:
1149 s.sendall(b"proxied data\n")
1150 finally:
1151 s.detach()
1152 finally:
1153 response.close()
1154 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001155 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001156 self.assertEqual(result, b"proxied data\n")
1157
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001158class ExtendedReadTest(TestCase):
1159 """
1160 Test peek(), read1(), readline()
1161 """
1162 lines = (
1163 'HTTP/1.1 200 OK\r\n'
1164 '\r\n'
1165 'hello world!\n'
1166 'and now \n'
1167 'for something completely different\n'
1168 'foo'
1169 )
1170 lines_expected = lines[lines.find('hello'):].encode("ascii")
1171 lines_chunked = (
1172 'HTTP/1.1 200 OK\r\n'
1173 'Transfer-Encoding: chunked\r\n\r\n'
1174 'a\r\n'
1175 'hello worl\r\n'
1176 '3\r\n'
1177 'd!\n\r\n'
1178 '9\r\n'
1179 'and now \n\r\n'
1180 '23\r\n'
1181 'for something completely different\n\r\n'
1182 '3\r\n'
1183 'foo\r\n'
1184 '0\r\n' # terminating chunk
1185 '\r\n' # end of trailers
1186 )
1187
1188 def setUp(self):
1189 sock = FakeSocket(self.lines)
1190 resp = client.HTTPResponse(sock, method="GET")
1191 resp.begin()
1192 resp.fp = io.BufferedReader(resp.fp)
1193 self.resp = resp
1194
1195
1196
1197 def test_peek(self):
1198 resp = self.resp
1199 # patch up the buffered peek so that it returns not too much stuff
1200 oldpeek = resp.fp.peek
1201 def mypeek(n=-1):
1202 p = oldpeek(n)
1203 if n >= 0:
1204 return p[:n]
1205 return p[:10]
1206 resp.fp.peek = mypeek
1207
1208 all = []
1209 while True:
1210 # try a short peek
1211 p = resp.peek(3)
1212 if p:
1213 self.assertGreater(len(p), 0)
1214 # then unbounded peek
1215 p2 = resp.peek()
1216 self.assertGreaterEqual(len(p2), len(p))
1217 self.assertTrue(p2.startswith(p))
1218 next = resp.read(len(p2))
1219 self.assertEqual(next, p2)
1220 else:
1221 next = resp.read()
1222 self.assertFalse(next)
1223 all.append(next)
1224 if not next:
1225 break
1226 self.assertEqual(b"".join(all), self.lines_expected)
1227
1228 def test_readline(self):
1229 resp = self.resp
1230 self._verify_readline(self.resp.readline, self.lines_expected)
1231
1232 def _verify_readline(self, readline, expected):
1233 all = []
1234 while True:
1235 # short readlines
1236 line = readline(5)
1237 if line and line != b"foo":
1238 if len(line) < 5:
1239 self.assertTrue(line.endswith(b"\n"))
1240 all.append(line)
1241 if not line:
1242 break
1243 self.assertEqual(b"".join(all), expected)
1244
1245 def test_read1(self):
1246 resp = self.resp
1247 def r():
1248 res = resp.read1(4)
1249 self.assertLessEqual(len(res), 4)
1250 return res
1251 readliner = Readliner(r)
1252 self._verify_readline(readliner.readline, self.lines_expected)
1253
1254 def test_read1_unbounded(self):
1255 resp = self.resp
1256 all = []
1257 while True:
1258 data = resp.read1()
1259 if not data:
1260 break
1261 all.append(data)
1262 self.assertEqual(b"".join(all), self.lines_expected)
1263
1264 def test_read1_bounded(self):
1265 resp = self.resp
1266 all = []
1267 while True:
1268 data = resp.read1(10)
1269 if not data:
1270 break
1271 self.assertLessEqual(len(data), 10)
1272 all.append(data)
1273 self.assertEqual(b"".join(all), self.lines_expected)
1274
1275 def test_read1_0(self):
1276 self.assertEqual(self.resp.read1(0), b"")
1277
1278 def test_peek_0(self):
1279 p = self.resp.peek(0)
1280 self.assertLessEqual(0, len(p))
1281
1282class ExtendedReadTestChunked(ExtendedReadTest):
1283 """
1284 Test peek(), read1(), readline() in chunked mode
1285 """
1286 lines = (
1287 'HTTP/1.1 200 OK\r\n'
1288 'Transfer-Encoding: chunked\r\n\r\n'
1289 'a\r\n'
1290 'hello worl\r\n'
1291 '3\r\n'
1292 'd!\n\r\n'
1293 '9\r\n'
1294 'and now \n\r\n'
1295 '23\r\n'
1296 'for something completely different\n\r\n'
1297 '3\r\n'
1298 'foo\r\n'
1299 '0\r\n' # terminating chunk
1300 '\r\n' # end of trailers
1301 )
1302
1303
1304class Readliner:
1305 """
1306 a simple readline class that uses an arbitrary read function and buffering
1307 """
1308 def __init__(self, readfunc):
1309 self.readfunc = readfunc
1310 self.remainder = b""
1311
1312 def readline(self, limit):
1313 data = []
1314 datalen = 0
1315 read = self.remainder
1316 try:
1317 while True:
1318 idx = read.find(b'\n')
1319 if idx != -1:
1320 break
1321 if datalen + len(read) >= limit:
1322 idx = limit - datalen - 1
1323 # read more data
1324 data.append(read)
1325 read = self.readfunc()
1326 if not read:
1327 idx = 0 #eof condition
1328 break
1329 idx += 1
1330 data.append(read[:idx])
1331 self.remainder = read[idx:]
1332 return b"".join(data)
1333 except:
1334 self.remainder = b"".join(data)
1335 raise
1336
Berker Peksagbabc6882015-02-20 09:39:38 +02001337
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001338class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001339 def test_all(self):
1340 # Documented objects defined in the module should be in __all__
1341 expected = {"responses"} # White-list documented dict() object
1342 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1343 # intentionally omitted for simplicity
1344 blacklist = {"HTTPMessage", "parse_headers"}
1345 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001346 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001347 continue
1348 module_object = getattr(client, name)
1349 if getattr(module_object, "__module__", None) == "http.client":
1350 expected.add(name)
1351 self.assertCountEqual(client.__all__, expected)
1352
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001353 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001354 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001355
Berker Peksagabbf0f42015-02-20 14:57:31 +02001356 def test_client_constants(self):
1357 # Make sure we don't break backward compatibility with 3.4
1358 expected = [
1359 'CONTINUE',
1360 'SWITCHING_PROTOCOLS',
1361 'PROCESSING',
1362 'OK',
1363 'CREATED',
1364 'ACCEPTED',
1365 'NON_AUTHORITATIVE_INFORMATION',
1366 'NO_CONTENT',
1367 'RESET_CONTENT',
1368 'PARTIAL_CONTENT',
1369 'MULTI_STATUS',
1370 'IM_USED',
1371 'MULTIPLE_CHOICES',
1372 'MOVED_PERMANENTLY',
1373 'FOUND',
1374 'SEE_OTHER',
1375 'NOT_MODIFIED',
1376 'USE_PROXY',
1377 'TEMPORARY_REDIRECT',
1378 'BAD_REQUEST',
1379 'UNAUTHORIZED',
1380 'PAYMENT_REQUIRED',
1381 'FORBIDDEN',
1382 'NOT_FOUND',
1383 'METHOD_NOT_ALLOWED',
1384 'NOT_ACCEPTABLE',
1385 'PROXY_AUTHENTICATION_REQUIRED',
1386 'REQUEST_TIMEOUT',
1387 'CONFLICT',
1388 'GONE',
1389 'LENGTH_REQUIRED',
1390 'PRECONDITION_FAILED',
1391 'REQUEST_ENTITY_TOO_LARGE',
1392 'REQUEST_URI_TOO_LONG',
1393 'UNSUPPORTED_MEDIA_TYPE',
1394 'REQUESTED_RANGE_NOT_SATISFIABLE',
1395 'EXPECTATION_FAILED',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001396 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001397 'UNPROCESSABLE_ENTITY',
1398 'LOCKED',
1399 'FAILED_DEPENDENCY',
1400 'UPGRADE_REQUIRED',
1401 'PRECONDITION_REQUIRED',
1402 'TOO_MANY_REQUESTS',
1403 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1404 'INTERNAL_SERVER_ERROR',
1405 'NOT_IMPLEMENTED',
1406 'BAD_GATEWAY',
1407 'SERVICE_UNAVAILABLE',
1408 'GATEWAY_TIMEOUT',
1409 'HTTP_VERSION_NOT_SUPPORTED',
1410 'INSUFFICIENT_STORAGE',
1411 'NOT_EXTENDED',
1412 'NETWORK_AUTHENTICATION_REQUIRED',
1413 ]
1414 for const in expected:
1415 with self.subTest(constant=const):
1416 self.assertTrue(hasattr(client, const))
1417
Gregory P. Smithb4066372010-01-03 03:28:29 +00001418
1419class SourceAddressTest(TestCase):
1420 def setUp(self):
1421 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1422 self.port = support.bind_port(self.serv)
1423 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001424 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001425 self.conn = None
1426
1427 def tearDown(self):
1428 if self.conn:
1429 self.conn.close()
1430 self.conn = None
1431 self.serv.close()
1432 self.serv = None
1433
1434 def testHTTPConnectionSourceAddress(self):
1435 self.conn = client.HTTPConnection(HOST, self.port,
1436 source_address=('', self.source_port))
1437 self.conn.connect()
1438 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1439
1440 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1441 'http.client.HTTPSConnection not defined')
1442 def testHTTPSConnectionSourceAddress(self):
1443 self.conn = client.HTTPSConnection(HOST, self.port,
1444 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001445 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001446 # this code doesn't deal with setting up an active running SSL server
1447 # for an ssl_wrapped connect() to actually return from.
1448
1449
Guido van Rossumd8faa362007-04-27 19:54:29 +00001450class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001451 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001452
1453 def setUp(self):
1454 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001455 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001456 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001457
1458 def tearDown(self):
1459 self.serv.close()
1460 self.serv = None
1461
1462 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001463 # This will prove that the timeout gets through HTTPConnection
1464 # and into the socket.
1465
Georg Brandlf78e02b2008-06-10 17:40:04 +00001466 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001467 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001468 socket.setdefaulttimeout(30)
1469 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001470 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001471 httpConn.connect()
1472 finally:
1473 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001474 self.assertEqual(httpConn.sock.gettimeout(), 30)
1475 httpConn.close()
1476
Georg Brandlf78e02b2008-06-10 17:40:04 +00001477 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001478 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001479 socket.setdefaulttimeout(30)
1480 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001481 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001482 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001483 httpConn.connect()
1484 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001485 socket.setdefaulttimeout(None)
1486 self.assertEqual(httpConn.sock.gettimeout(), None)
1487 httpConn.close()
1488
1489 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001490 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001491 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001492 self.assertEqual(httpConn.sock.gettimeout(), 30)
1493 httpConn.close()
1494
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001495
R David Murraycae7bdb2015-04-05 19:26:29 -04001496class PersistenceTest(TestCase):
1497
1498 def test_reuse_reconnect(self):
1499 # Should reuse or reconnect depending on header from server
1500 tests = (
1501 ('1.0', '', False),
1502 ('1.0', 'Connection: keep-alive\r\n', True),
1503 ('1.1', '', True),
1504 ('1.1', 'Connection: close\r\n', False),
1505 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1506 ('1.1', 'Connection: cloSE\r\n', False),
1507 )
1508 for version, header, reuse in tests:
1509 with self.subTest(version=version, header=header):
1510 msg = (
1511 'HTTP/{} 200 OK\r\n'
1512 '{}'
1513 'Content-Length: 12\r\n'
1514 '\r\n'
1515 'Dummy body\r\n'
1516 ).format(version, header)
1517 conn = FakeSocketHTTPConnection(msg)
1518 self.assertIsNone(conn.sock)
1519 conn.request('GET', '/open-connection')
1520 with conn.getresponse() as response:
1521 self.assertEqual(conn.sock is None, not reuse)
1522 response.read()
1523 self.assertEqual(conn.sock is None, not reuse)
1524 self.assertEqual(conn.connections, 1)
1525 conn.request('GET', '/subsequent-request')
1526 self.assertEqual(conn.connections, 1 if reuse else 2)
1527
1528 def test_disconnected(self):
1529
1530 def make_reset_reader(text):
1531 """Return BufferedReader that raises ECONNRESET at EOF"""
1532 stream = io.BytesIO(text)
1533 def readinto(buffer):
1534 size = io.BytesIO.readinto(stream, buffer)
1535 if size == 0:
1536 raise ConnectionResetError()
1537 return size
1538 stream.readinto = readinto
1539 return io.BufferedReader(stream)
1540
1541 tests = (
1542 (io.BytesIO, client.RemoteDisconnected),
1543 (make_reset_reader, ConnectionResetError),
1544 )
1545 for stream_factory, exception in tests:
1546 with self.subTest(exception=exception):
1547 conn = FakeSocketHTTPConnection(b'', stream_factory)
1548 conn.request('GET', '/eof-response')
1549 self.assertRaises(exception, conn.getresponse)
1550 self.assertIsNone(conn.sock)
1551 # HTTPConnection.connect() should be automatically invoked
1552 conn.request('GET', '/reconnect')
1553 self.assertEqual(conn.connections, 2)
1554
1555 def test_100_close(self):
1556 conn = FakeSocketHTTPConnection(
1557 b'HTTP/1.1 100 Continue\r\n'
1558 b'\r\n'
1559 # Missing final response
1560 )
1561 conn.request('GET', '/', headers={'Expect': '100-continue'})
1562 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1563 self.assertIsNone(conn.sock)
1564 conn.request('GET', '/reconnect')
1565 self.assertEqual(conn.connections, 2)
1566
1567
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001568class HTTPSTest(TestCase):
1569
1570 def setUp(self):
1571 if not hasattr(client, 'HTTPSConnection'):
1572 self.skipTest('ssl support required')
1573
1574 def make_server(self, certfile):
1575 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001576 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001577
1578 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001579 # simple test to check it's storing the timeout
1580 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1581 self.assertEqual(h.timeout, 30)
1582
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001583 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001584 # Default settings: requires a valid cert from a trusted CA
1585 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001586 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001587 with support.transient_internet('self-signed.pythontest.net'):
1588 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1589 with self.assertRaises(ssl.SSLError) as exc_info:
1590 h.request('GET', '/')
1591 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1592
1593 def test_networked_noverification(self):
1594 # Switch off cert verification
1595 import ssl
1596 support.requires('network')
1597 with support.transient_internet('self-signed.pythontest.net'):
1598 context = ssl._create_unverified_context()
1599 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1600 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001601 h.request('GET', '/')
1602 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001603 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001604 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001605 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001606
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001607 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001608 def test_networked_trusted_by_default_cert(self):
1609 # Default settings: requires a valid cert from a trusted CA
1610 support.requires('network')
1611 with support.transient_internet('www.python.org'):
1612 h = client.HTTPSConnection('www.python.org', 443)
1613 h.request('GET', '/')
1614 resp = h.getresponse()
1615 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001616 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001617 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001618 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001619
1620 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001621 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001622 import ssl
1623 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001624 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
1625 with support.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001626 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1627 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1628 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001629 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001630 try:
1631 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1632 context=context)
1633 h.request('GET', '/')
1634 resp = h.getresponse()
1635 except ssl.SSLError as ssl_err:
1636 ssl_err_str = str(ssl_err)
1637 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1638 # modern Linux distros (Debian Buster, etc) default OpenSSL
1639 # configurations it'll fail saying "key too weak" until we
1640 # address https://bugs.python.org/issue36816 to use a proper
1641 # key size on self-signed.pythontest.net.
1642 if re.search(r'(?i)key.too.weak', ssl_err_str):
1643 raise unittest.SkipTest(
1644 f'Got {ssl_err_str} trying to connect '
1645 f'to {selfsigned_pythontestdotnet}. '
1646 'See https://bugs.python.org/issue36816.')
1647 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001648 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001649 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001650 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001651 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001652
1653 def test_networked_bad_cert(self):
1654 # We feed a "CA" cert that is unrelated to the server's cert
1655 import ssl
1656 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001657 with support.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001658 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001659 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001660 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1661 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001662 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001663 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1664
1665 def test_local_unknown_cert(self):
1666 # The custom cert isn't known to the default trust bundle
1667 import ssl
1668 server = self.make_server(CERT_localhost)
1669 h = client.HTTPSConnection('localhost', server.port)
1670 with self.assertRaises(ssl.SSLError) as exc_info:
1671 h.request('GET', '/')
1672 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001673
1674 def test_local_good_hostname(self):
1675 # The (valid) cert validates the HTTP hostname
1676 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001677 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001678 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001679 context.load_verify_locations(CERT_localhost)
1680 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001681 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001682 h.request('GET', '/nonexistent')
1683 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001684 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001685 self.assertEqual(resp.status, 404)
1686
1687 def test_local_bad_hostname(self):
1688 # The (valid) cert doesn't validate the HTTP hostname
1689 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001690 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001691 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001692 context.load_verify_locations(CERT_fakehostname)
1693 h = client.HTTPSConnection('localhost', server.port, context=context)
1694 with self.assertRaises(ssl.CertificateError):
1695 h.request('GET', '/')
1696 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001697 with support.check_warnings(('', DeprecationWarning)):
1698 h = client.HTTPSConnection('localhost', server.port,
1699 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001700 with self.assertRaises(ssl.CertificateError):
1701 h.request('GET', '/')
1702 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001703 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001704 with support.check_warnings(('', DeprecationWarning)):
1705 h = client.HTTPSConnection('localhost', server.port,
1706 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001707 h.request('GET', '/nonexistent')
1708 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001709 resp.close()
1710 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001711 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001712 # The context's check_hostname setting is used if one isn't passed to
1713 # HTTPSConnection.
1714 context.check_hostname = False
1715 h = client.HTTPSConnection('localhost', server.port, context=context)
1716 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001717 resp = h.getresponse()
1718 self.assertEqual(resp.status, 404)
1719 resp.close()
1720 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001721 # Passing check_hostname to HTTPSConnection should override the
1722 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001723 with support.check_warnings(('', DeprecationWarning)):
1724 h = client.HTTPSConnection('localhost', server.port,
1725 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001726 with self.assertRaises(ssl.CertificateError):
1727 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001728
Petri Lehtinene119c402011-10-26 21:29:15 +03001729 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1730 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001731 def test_host_port(self):
1732 # Check invalid host_port
1733
1734 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1735 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1736
1737 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1738 "fe80::207:e9ff:fe9b", 8000),
1739 ("www.python.org:443", "www.python.org", 443),
1740 ("www.python.org:", "www.python.org", 443),
1741 ("www.python.org", "www.python.org", 443),
1742 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1743 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1744 443)):
1745 c = client.HTTPSConnection(hp)
1746 self.assertEqual(h, c.host)
1747 self.assertEqual(p, c.port)
1748
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001749 def test_tls13_pha(self):
1750 import ssl
1751 if not ssl.HAS_TLSv1_3:
1752 self.skipTest('TLS 1.3 support required')
1753 # just check status of PHA flag
1754 h = client.HTTPSConnection('localhost', 443)
1755 self.assertTrue(h._context.post_handshake_auth)
1756
1757 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1758 self.assertFalse(context.post_handshake_auth)
1759 h = client.HTTPSConnection('localhost', 443, context=context)
1760 self.assertIs(h._context, context)
1761 self.assertFalse(h._context.post_handshake_auth)
1762
Pablo Galindoaa542c22019-08-08 23:25:46 +01001763 with warnings.catch_warnings():
1764 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1765 DeprecationWarning)
1766 h = client.HTTPSConnection('localhost', 443, context=context,
1767 cert_file=CERT_localhost)
Christian Heimesd1bd6e72019-07-01 08:32:24 +02001768 self.assertTrue(h._context.post_handshake_auth)
1769
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001770
Jeremy Hylton236654b2009-03-27 20:24:34 +00001771class RequestBodyTest(TestCase):
1772 """Test cases where a request includes a message body."""
1773
1774 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001775 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001776 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001777 self.conn.sock = self.sock
1778
1779 def get_headers_and_fp(self):
1780 f = io.BytesIO(self.sock.data)
1781 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001782 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001783 return message, f
1784
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001785 def test_list_body(self):
1786 # Note that no content-length is automatically calculated for
1787 # an iterable. The request will fall back to send chunked
1788 # transfer encoding.
1789 cases = (
1790 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1791 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1792 )
1793 for body, expected in cases:
1794 with self.subTest(body):
1795 self.conn = client.HTTPConnection('example.com')
1796 self.conn.sock = self.sock = FakeSocket('')
1797
1798 self.conn.request('PUT', '/url', body)
1799 msg, f = self.get_headers_and_fp()
1800 self.assertNotIn('Content-Type', msg)
1801 self.assertNotIn('Content-Length', msg)
1802 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1803 self.assertEqual(expected, f.read())
1804
Jeremy Hylton236654b2009-03-27 20:24:34 +00001805 def test_manual_content_length(self):
1806 # Set an incorrect content-length so that we can verify that
1807 # it will not be over-ridden by the library.
1808 self.conn.request("PUT", "/url", "body",
1809 {"Content-Length": "42"})
1810 message, f = self.get_headers_and_fp()
1811 self.assertEqual("42", message.get("content-length"))
1812 self.assertEqual(4, len(f.read()))
1813
1814 def test_ascii_body(self):
1815 self.conn.request("PUT", "/url", "body")
1816 message, f = self.get_headers_and_fp()
1817 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001818 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001819 self.assertEqual("4", message.get("content-length"))
1820 self.assertEqual(b'body', f.read())
1821
1822 def test_latin1_body(self):
1823 self.conn.request("PUT", "/url", "body\xc1")
1824 message, f = self.get_headers_and_fp()
1825 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001826 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001827 self.assertEqual("5", message.get("content-length"))
1828 self.assertEqual(b'body\xc1', f.read())
1829
1830 def test_bytes_body(self):
1831 self.conn.request("PUT", "/url", b"body\xc1")
1832 message, f = self.get_headers_and_fp()
1833 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001834 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001835 self.assertEqual("5", message.get("content-length"))
1836 self.assertEqual(b'body\xc1', f.read())
1837
Martin Panteref91bb22016-08-27 01:39:26 +00001838 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001839 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001840 with open(support.TESTFN, "w") as f:
1841 f.write("body")
1842 with open(support.TESTFN) as f:
1843 self.conn.request("PUT", "/url", f)
1844 message, f = self.get_headers_and_fp()
1845 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001846 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001847 # No content-length will be determined for files; the body
1848 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001849 self.assertIsNone(message.get("content-length"))
1850 self.assertEqual("chunked", message.get("transfer-encoding"))
1851 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001852
1853 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001854 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001855 with open(support.TESTFN, "wb") as f:
1856 f.write(b"body\xc1")
1857 with open(support.TESTFN, "rb") as f:
1858 self.conn.request("PUT", "/url", f)
1859 message, f = self.get_headers_and_fp()
1860 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001861 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001862 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1863 self.assertNotIn("Content-Length", message)
1864 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001865
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001866
1867class HTTPResponseTest(TestCase):
1868
1869 def setUp(self):
1870 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1871 second-value\r\n\r\nText"
1872 sock = FakeSocket(body)
1873 self.resp = client.HTTPResponse(sock)
1874 self.resp.begin()
1875
1876 def test_getting_header(self):
1877 header = self.resp.getheader('My-Header')
1878 self.assertEqual(header, 'first-value, second-value')
1879
1880 header = self.resp.getheader('My-Header', 'some default')
1881 self.assertEqual(header, 'first-value, second-value')
1882
1883 def test_getting_nonexistent_header_with_string_default(self):
1884 header = self.resp.getheader('No-Such-Header', 'default-value')
1885 self.assertEqual(header, 'default-value')
1886
1887 def test_getting_nonexistent_header_with_iterable_default(self):
1888 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1889 self.assertEqual(header, 'default, values')
1890
1891 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1892 self.assertEqual(header, 'default, values')
1893
1894 def test_getting_nonexistent_header_without_default(self):
1895 header = self.resp.getheader('No-Such-Header')
1896 self.assertEqual(header, None)
1897
1898 def test_getting_header_defaultint(self):
1899 header = self.resp.getheader('No-Such-Header',default=42)
1900 self.assertEqual(header, 42)
1901
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001902class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001903 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001904 response_text = (
1905 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1906 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1907 'Content-Length: 42\r\n\r\n'
1908 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001909 self.host = 'proxy.com'
1910 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001911 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001912
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001913 def tearDown(self):
1914 self.conn.close()
1915
Berker Peksagab53ab02015-02-03 12:22:11 +02001916 def _create_connection(self, response_text):
1917 def create_connection(address, timeout=None, source_address=None):
1918 return FakeSocket(response_text, host=address[0], port=address[1])
1919 return create_connection
1920
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001921 def test_set_tunnel_host_port_headers(self):
1922 tunnel_host = 'destination.com'
1923 tunnel_port = 8888
1924 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1925 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1926 headers=tunnel_headers)
1927 self.conn.request('HEAD', '/', '')
1928 self.assertEqual(self.conn.sock.host, self.host)
1929 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1930 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1931 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1932 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1933
1934 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001935 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001936 self.conn.connect()
1937 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001938 'destination.com')
1939
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001940 def test_connect_with_tunnel(self):
1941 self.conn.set_tunnel('destination.com')
1942 self.conn.request('HEAD', '/', '')
1943 self.assertEqual(self.conn.sock.host, self.host)
1944 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1945 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001946 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001947 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1948 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001949
1950 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001951 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001952
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001953 def test_connect_put_request(self):
1954 self.conn.set_tunnel('destination.com')
1955 self.conn.request('PUT', '/', '')
1956 self.assertEqual(self.conn.sock.host, self.host)
1957 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1958 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1959 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1960
Berker Peksagab53ab02015-02-03 12:22:11 +02001961 def test_tunnel_debuglog(self):
1962 expected_header = 'X-Dummy: 1'
1963 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1964
1965 self.conn.set_debuglevel(1)
1966 self.conn._create_connection = self._create_connection(response_text)
1967 self.conn.set_tunnel('destination.com')
1968
1969 with support.captured_stdout() as output:
1970 self.conn.request('PUT', '/', '')
1971 lines = output.getvalue().splitlines()
1972 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001973
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001974
Thomas Wouters89f507f2006-12-13 04:49:30 +00001975if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04001976 unittest.main(verbosity=2)