blob: 49263a8a3a0dc16051647443dbe14b1b0165d341 [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
Miss Islington (bot)ffa29b52019-05-06 20:51:25 -07007import re
Guido van Rossumd8faa362007-04-27 19:54:29 +00008import socket
Antoine Pitrou88c60c92017-09-18 23:50:44 +02009import threading
Jeremy Hylton121d34a2003-07-08 12:36:58 +000010
Gregory P. Smithb4066372010-01-03 03:28:29 +000011import unittest
12TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000013
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000015
Antoine Pitrou803e6d62010-10-13 10:36:15 +000016here = os.path.dirname(__file__)
17# Self-signed cert file for 'localhost'
18CERT_localhost = os.path.join(here, 'keycert.pem')
19# Self-signed cert file for 'fakehostname'
20CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010021# Self-signed cert file for self-signed.pythontest.net
22CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000023
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000024# constants for testing chunked encoding
25chunked_start = (
26 'HTTP/1.1 200 OK\r\n'
27 'Transfer-Encoding: chunked\r\n\r\n'
28 'a\r\n'
29 'hello worl\r\n'
30 '3\r\n'
31 'd! \r\n'
32 '8\r\n'
33 'and now \r\n'
34 '22\r\n'
35 'for something completely different\r\n'
36)
37chunked_expected = b'hello world! and now for something completely different'
38chunk_extension = ";foo=bar"
39last_chunk = "0\r\n"
40last_chunk_extended = "0" + chunk_extension + "\r\n"
41trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
42chunked_end = "\r\n"
43
Benjamin Petersonee8712c2008-05-20 21:35:26 +000044HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000045
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000046class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040047 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000048 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000049 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000050 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000051 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000052 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010053 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020054 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040055 self.host = host
56 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000057
Jeremy Hylton2c178252004-08-07 16:28:14 +000058 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010059 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000060 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000061
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000062 def makefile(self, mode, bufsize=None):
63 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000064 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000065 # keep the file around so we can check how much was read from it
66 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020067 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000068 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000069
Serhiy Storchakab491e052014-12-01 13:07:45 +020070 def file_close(self):
71 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000072
Senthil Kumaran9da047b2014-04-14 13:07:56 -040073 def close(self):
74 pass
75
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050076 def setsockopt(self, level, optname, value):
77 pass
78
Jeremy Hylton636950f2009-03-28 04:34:21 +000079class EPipeSocket(FakeSocket):
80
81 def __init__(self, text, pipe_trigger):
82 # When sendall() is called with pipe_trigger, raise EPIPE.
83 FakeSocket.__init__(self, text)
84 self.pipe_trigger = pipe_trigger
85
86 def sendall(self, data):
87 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020088 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000089 self.data += data
90
91 def close(self):
92 pass
93
Serhiy Storchaka50254c52013-08-29 11:35:43 +030094class NoEOFBytesIO(io.BytesIO):
95 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000096
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000097 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000098 more from the underlying file than it should.
99 """
100 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000101 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000102 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000103 raise AssertionError('caller tried to read past EOF')
104 return data
105
106 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000107 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000108 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000109 raise AssertionError('caller tried to read past EOF')
110 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000111
R David Murraycae7bdb2015-04-05 19:26:29 -0400112class FakeSocketHTTPConnection(client.HTTPConnection):
113 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
114
115 def __init__(self, *args):
116 self.connections = 0
117 super().__init__('example.com')
118 self.fake_socket_args = args
119 self._create_connection = self.create_connection
120
121 def connect(self):
122 """Count the number of times connect() is invoked"""
123 self.connections += 1
124 return super().connect()
125
126 def create_connection(self, *pos, **kw):
127 return FakeSocket(*self.fake_socket_args)
128
Jeremy Hylton2c178252004-08-07 16:28:14 +0000129class HeaderTests(TestCase):
130 def test_auto_headers(self):
131 # Some headers are added automatically, but should not be added by
132 # .request() if they are explicitly set.
133
Jeremy Hylton2c178252004-08-07 16:28:14 +0000134 class HeaderCountingBuffer(list):
135 def __init__(self):
136 self.count = {}
137 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000138 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000139 if len(kv) > 1:
140 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000141 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000142 self.count.setdefault(lcKey, 0)
143 self.count[lcKey] += 1
144 list.append(self, item)
145
146 for explicit_header in True, False:
147 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000148 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000149 conn.sock = FakeSocket('blahblahblah')
150 conn._buffer = HeaderCountingBuffer()
151
152 body = 'spamspamspam'
153 headers = {}
154 if explicit_header:
155 headers[header] = str(len(body))
156 conn.request('POST', '/', body, headers)
157 self.assertEqual(conn._buffer.count[header.lower()], 1)
158
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800159 def test_content_length_0(self):
160
161 class ContentLengthChecker(list):
162 def __init__(self):
163 list.__init__(self)
164 self.content_length = None
165 def append(self, item):
166 kv = item.split(b':', 1)
167 if len(kv) > 1 and kv[0].lower() == b'content-length':
168 self.content_length = kv[1].strip()
169 list.append(self, item)
170
R David Murraybeed8402015-03-22 15:18:23 -0400171 # Here, we're testing that methods expecting a body get a
172 # content-length set to zero if the body is empty (either None or '')
173 bodies = (None, '')
174 methods_with_body = ('PUT', 'POST', 'PATCH')
175 for method, body in itertools.product(methods_with_body, bodies):
176 conn = client.HTTPConnection('example.com')
177 conn.sock = FakeSocket(None)
178 conn._buffer = ContentLengthChecker()
179 conn.request(method, '/', body)
180 self.assertEqual(
181 conn._buffer.content_length, b'0',
182 'Header Content-Length incorrect on {}'.format(method)
183 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800184
R David Murraybeed8402015-03-22 15:18:23 -0400185 # For these methods, we make sure that content-length is not set when
186 # the body is None because it might cause unexpected behaviour on the
187 # server.
188 methods_without_body = (
189 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
190 )
191 for method in methods_without_body:
192 conn = client.HTTPConnection('example.com')
193 conn.sock = FakeSocket(None)
194 conn._buffer = ContentLengthChecker()
195 conn.request(method, '/', None)
196 self.assertEqual(
197 conn._buffer.content_length, None,
198 'Header Content-Length set for empty body on {}'.format(method)
199 )
200
201 # If the body is set to '', that's considered to be "present but
202 # empty" rather than "missing", so content length would be set, even
203 # for methods that don't expect a body.
204 for method in methods_without_body:
205 conn = client.HTTPConnection('example.com')
206 conn.sock = FakeSocket(None)
207 conn._buffer = ContentLengthChecker()
208 conn.request(method, '/', '')
209 self.assertEqual(
210 conn._buffer.content_length, b'0',
211 'Header Content-Length incorrect on {}'.format(method)
212 )
213
214 # If the body is set, make sure Content-Length is set.
215 for method in itertools.chain(methods_without_body, methods_with_body):
216 conn = client.HTTPConnection('example.com')
217 conn.sock = FakeSocket(None)
218 conn._buffer = ContentLengthChecker()
219 conn.request(method, '/', ' ')
220 self.assertEqual(
221 conn._buffer.content_length, b'1',
222 'Header Content-Length incorrect on {}'.format(method)
223 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800224
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000225 def test_putheader(self):
226 conn = client.HTTPConnection('example.com')
227 conn.sock = FakeSocket(None)
228 conn.putrequest('GET','/')
229 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200230 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000231
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200232 conn.putheader('Foo', ' bar ')
233 self.assertIn(b'Foo: bar ', conn._buffer)
234 conn.putheader('Bar', '\tbaz\t')
235 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
236 conn.putheader('Authorization', 'Bearer mytoken')
237 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
238 conn.putheader('IterHeader', 'IterA', 'IterB')
239 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
240 conn.putheader('LatinHeader', b'\xFF')
241 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
242 conn.putheader('Utf8Header', b'\xc3\x80')
243 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
244 conn.putheader('C1-Control', b'next\x85line')
245 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
246 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
247 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
248 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
249 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
250 conn.putheader('Key Space', 'value')
251 self.assertIn(b'Key Space: value', conn._buffer)
252 conn.putheader('KeySpace ', 'value')
253 self.assertIn(b'KeySpace : value', conn._buffer)
254 conn.putheader(b'Nonbreak\xa0Space', 'value')
255 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
256 conn.putheader(b'\xa0NonbreakSpace', 'value')
257 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
258
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000259 def test_ipv6host_header(self):
Martin Panter8d56c022016-05-29 04:13:35 +0000260 # Default host header on IPv6 transaction should be wrapped by [] if
261 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000262 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
263 b'Accept-Encoding: identity\r\n\r\n'
264 conn = client.HTTPConnection('[2001::]:81')
265 sock = FakeSocket('')
266 conn.sock = sock
267 conn.request('GET', '/foo')
268 self.assertTrue(sock.data.startswith(expected))
269
270 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
271 b'Accept-Encoding: identity\r\n\r\n'
272 conn = client.HTTPConnection('[2001:102A::]')
273 sock = FakeSocket('')
274 conn.sock = sock
275 conn.request('GET', '/foo')
276 self.assertTrue(sock.data.startswith(expected))
277
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500278 def test_malformed_headers_coped_with(self):
279 # Issue 19996
280 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
281 sock = FakeSocket(body)
282 resp = client.HTTPResponse(sock)
283 resp.begin()
284
285 self.assertEqual(resp.getheader('First'), 'val')
286 self.assertEqual(resp.getheader('Second'), 'val')
287
R David Murraydc1650c2016-09-07 17:44:34 -0400288 def test_parse_all_octets(self):
289 # Ensure no valid header field octet breaks the parser
290 body = (
291 b'HTTP/1.1 200 OK\r\n'
292 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
293 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
294 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
295 b'obs-fold: text\r\n'
296 b' folded with space\r\n'
297 b'\tfolded with tab\r\n'
298 b'Content-Length: 0\r\n'
299 b'\r\n'
300 )
301 sock = FakeSocket(body)
302 resp = client.HTTPResponse(sock)
303 resp.begin()
304 self.assertEqual(resp.getheader('Content-Length'), '0')
305 self.assertEqual(resp.msg['Content-Length'], '0')
306 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
307 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
308 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
309 self.assertEqual(resp.getheader('VCHAR'), vchar)
310 self.assertEqual(resp.msg['VCHAR'], vchar)
311 self.assertIsNotNone(resp.getheader('obs-text'))
312 self.assertIn('obs-text', resp.msg)
313 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
314 self.assertTrue(folded.startswith('text'))
315 self.assertIn(' folded with space', folded)
316 self.assertTrue(folded.endswith('folded with tab'))
317
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200318 def test_invalid_headers(self):
319 conn = client.HTTPConnection('example.com')
320 conn.sock = FakeSocket('')
321 conn.putrequest('GET', '/')
322
323 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
324 # longer allowed in header names
325 cases = (
326 (b'Invalid\r\nName', b'ValidValue'),
327 (b'Invalid\rName', b'ValidValue'),
328 (b'Invalid\nName', b'ValidValue'),
329 (b'\r\nInvalidName', b'ValidValue'),
330 (b'\rInvalidName', b'ValidValue'),
331 (b'\nInvalidName', b'ValidValue'),
332 (b' InvalidName', b'ValidValue'),
333 (b'\tInvalidName', b'ValidValue'),
334 (b'Invalid:Name', b'ValidValue'),
335 (b':InvalidName', b'ValidValue'),
336 (b'ValidName', b'Invalid\r\nValue'),
337 (b'ValidName', b'Invalid\rValue'),
338 (b'ValidName', b'Invalid\nValue'),
339 (b'ValidName', b'InvalidValue\r\n'),
340 (b'ValidName', b'InvalidValue\r'),
341 (b'ValidName', b'InvalidValue\n'),
342 )
343 for name, value in cases:
344 with self.subTest((name, value)):
345 with self.assertRaisesRegex(ValueError, 'Invalid header'):
346 conn.putheader(name, value)
347
Miss Islington (bot)2edcf0a2018-06-19 06:52:36 -0700348 def test_headers_debuglevel(self):
349 body = (
350 b'HTTP/1.1 200 OK\r\n'
351 b'First: val\r\n'
Miss Islington (bot)6f9cd142019-04-04 01:25:59 -0700352 b'Second: val1\r\n'
353 b'Second: val2\r\n'
Miss Islington (bot)2edcf0a2018-06-19 06:52:36 -0700354 )
355 sock = FakeSocket(body)
356 resp = client.HTTPResponse(sock, debuglevel=1)
357 with support.captured_stdout() as output:
358 resp.begin()
359 lines = output.getvalue().splitlines()
360 self.assertEqual(lines[0], "reply: 'HTTP/1.1 200 OK\\r\\n'")
361 self.assertEqual(lines[1], "header: First: val")
Miss Islington (bot)6f9cd142019-04-04 01:25:59 -0700362 self.assertEqual(lines[2], "header: Second: val1")
363 self.assertEqual(lines[3], "header: Second: val2")
Miss Islington (bot)2edcf0a2018-06-19 06:52:36 -0700364
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000365
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000366class TransferEncodingTest(TestCase):
367 expected_body = b"It's just a flesh wound"
368
369 def test_endheaders_chunked(self):
370 conn = client.HTTPConnection('example.com')
371 conn.sock = FakeSocket(b'')
372 conn.putrequest('POST', '/')
373 conn.endheaders(self._make_body(), encode_chunked=True)
374
375 _, _, body = self._parse_request(conn.sock.data)
376 body = self._parse_chunked(body)
377 self.assertEqual(body, self.expected_body)
378
379 def test_explicit_headers(self):
380 # explicit chunked
381 conn = client.HTTPConnection('example.com')
382 conn.sock = FakeSocket(b'')
383 # this shouldn't actually be automatically chunk-encoded because the
384 # calling code has explicitly stated that it's taking care of it
385 conn.request(
386 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
387
388 _, headers, body = self._parse_request(conn.sock.data)
389 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
390 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
391 self.assertEqual(body, self.expected_body)
392
393 # explicit chunked, string body
394 conn = client.HTTPConnection('example.com')
395 conn.sock = FakeSocket(b'')
396 conn.request(
397 'POST', '/', self.expected_body.decode('latin-1'),
398 {'Transfer-Encoding': 'chunked'})
399
400 _, headers, body = self._parse_request(conn.sock.data)
401 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
402 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
403 self.assertEqual(body, self.expected_body)
404
405 # User-specified TE, but request() does the chunk encoding
406 conn = client.HTTPConnection('example.com')
407 conn.sock = FakeSocket(b'')
408 conn.request('POST', '/',
409 headers={'Transfer-Encoding': 'gzip, chunked'},
410 encode_chunked=True,
411 body=self._make_body())
412 _, headers, body = self._parse_request(conn.sock.data)
413 self.assertNotIn('content-length', [k.lower() for k in headers])
414 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
415 self.assertEqual(self._parse_chunked(body), self.expected_body)
416
417 def test_request(self):
418 for empty_lines in (False, True,):
419 conn = client.HTTPConnection('example.com')
420 conn.sock = FakeSocket(b'')
421 conn.request(
422 'POST', '/', self._make_body(empty_lines=empty_lines))
423
424 _, headers, body = self._parse_request(conn.sock.data)
425 body = self._parse_chunked(body)
426 self.assertEqual(body, self.expected_body)
427 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
428
429 # Content-Length and Transfer-Encoding SHOULD not be sent in the
430 # same request
431 self.assertNotIn('content-length', [k.lower() for k in headers])
432
Martin Panteref91bb22016-08-27 01:39:26 +0000433 def test_empty_body(self):
434 # Zero-length iterable should be treated like any other iterable
435 conn = client.HTTPConnection('example.com')
436 conn.sock = FakeSocket(b'')
437 conn.request('POST', '/', ())
438 _, headers, body = self._parse_request(conn.sock.data)
439 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
440 self.assertNotIn('content-length', [k.lower() for k in headers])
441 self.assertEqual(body, b"0\r\n\r\n")
442
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000443 def _make_body(self, empty_lines=False):
444 lines = self.expected_body.split(b' ')
445 for idx, line in enumerate(lines):
446 # for testing handling empty lines
447 if empty_lines and idx % 2:
448 yield b''
449 if idx < len(lines) - 1:
450 yield line + b' '
451 else:
452 yield line
453
454 def _parse_request(self, data):
455 lines = data.split(b'\r\n')
456 request = lines[0]
457 headers = {}
458 n = 1
459 while n < len(lines) and len(lines[n]) > 0:
460 key, val = lines[n].split(b':')
461 key = key.decode('latin-1').strip()
462 headers[key] = val.decode('latin-1').strip()
463 n += 1
464
465 return request, headers, b'\r\n'.join(lines[n + 1:])
466
467 def _parse_chunked(self, data):
468 body = []
469 trailers = {}
470 n = 0
471 lines = data.split(b'\r\n')
472 # parse body
473 while True:
474 size, chunk = lines[n:n+2]
475 size = int(size, 16)
476
477 if size == 0:
478 n += 1
479 break
480
481 self.assertEqual(size, len(chunk))
482 body.append(chunk)
483
484 n += 2
485 # we /should/ hit the end chunk, but check against the size of
486 # lines so we're not stuck in an infinite loop should we get
487 # malformed data
488 if n > len(lines):
489 break
490
491 return b''.join(body)
492
493
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494class BasicTest(TestCase):
495 def test_status_lines(self):
496 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000497
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 body = "HTTP/1.1 200 Ok\r\n\r\nText"
499 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000500 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000501 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200502 self.assertEqual(resp.read(0), b'') # Issue #20007
503 self.assertFalse(resp.isclosed())
504 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000505 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000506 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200507 self.assertFalse(resp.closed)
508 resp.close()
509 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000510
Thomas Wouters89f507f2006-12-13 04:49:30 +0000511 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
512 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000513 resp = client.HTTPResponse(sock)
514 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000515
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000516 def test_bad_status_repr(self):
517 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200518 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000519
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000520 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000521 # if we have Content-Length, HTTPResponse knows when to close itself,
522 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000523 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
524 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000525 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000526 resp.begin()
527 self.assertEqual(resp.read(2), b'Te')
528 self.assertFalse(resp.isclosed())
529 self.assertEqual(resp.read(2), b'xt')
530 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200531 self.assertFalse(resp.closed)
532 resp.close()
533 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000534
Martin Panterce911c32016-03-17 06:42:48 +0000535 def test_mixed_reads(self):
536 # readline() should update the remaining length, so that read() knows
537 # how much data is left and does not raise IncompleteRead
538 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
539 sock = FakeSocket(body)
540 resp = client.HTTPResponse(sock)
541 resp.begin()
542 self.assertEqual(resp.readline(), b'Text\r\n')
543 self.assertFalse(resp.isclosed())
544 self.assertEqual(resp.read(), b'Another')
545 self.assertTrue(resp.isclosed())
546 self.assertFalse(resp.closed)
547 resp.close()
548 self.assertTrue(resp.closed)
549
Antoine Pitrou38d96432011-12-06 22:33:57 +0100550 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000551 # if we have Content-Length, HTTPResponse knows when to close itself,
552 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100553 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
554 sock = FakeSocket(body)
555 resp = client.HTTPResponse(sock)
556 resp.begin()
557 b = bytearray(2)
558 n = resp.readinto(b)
559 self.assertEqual(n, 2)
560 self.assertEqual(bytes(b), b'Te')
561 self.assertFalse(resp.isclosed())
562 n = resp.readinto(b)
563 self.assertEqual(n, 2)
564 self.assertEqual(bytes(b), b'xt')
565 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200566 self.assertFalse(resp.closed)
567 resp.close()
568 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100569
Antoine Pitrou084daa22012-12-15 19:11:54 +0100570 def test_partial_reads_no_content_length(self):
571 # when no length is present, the socket should be gracefully closed when
572 # all data was read
573 body = "HTTP/1.1 200 Ok\r\n\r\nText"
574 sock = FakeSocket(body)
575 resp = client.HTTPResponse(sock)
576 resp.begin()
577 self.assertEqual(resp.read(2), b'Te')
578 self.assertFalse(resp.isclosed())
579 self.assertEqual(resp.read(2), b'xt')
580 self.assertEqual(resp.read(1), b'')
581 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200582 self.assertFalse(resp.closed)
583 resp.close()
584 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100585
Antoine Pitroud20e7742012-12-15 19:22:30 +0100586 def test_partial_readintos_no_content_length(self):
587 # when no length is present, the socket should be gracefully closed when
588 # all data was read
589 body = "HTTP/1.1 200 Ok\r\n\r\nText"
590 sock = FakeSocket(body)
591 resp = client.HTTPResponse(sock)
592 resp.begin()
593 b = bytearray(2)
594 n = resp.readinto(b)
595 self.assertEqual(n, 2)
596 self.assertEqual(bytes(b), b'Te')
597 self.assertFalse(resp.isclosed())
598 n = resp.readinto(b)
599 self.assertEqual(n, 2)
600 self.assertEqual(bytes(b), b'xt')
601 n = resp.readinto(b)
602 self.assertEqual(n, 0)
603 self.assertTrue(resp.isclosed())
604
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100605 def test_partial_reads_incomplete_body(self):
606 # if the server shuts down the connection before the whole
607 # content-length is delivered, the socket is gracefully closed
608 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
609 sock = FakeSocket(body)
610 resp = client.HTTPResponse(sock)
611 resp.begin()
612 self.assertEqual(resp.read(2), b'Te')
613 self.assertFalse(resp.isclosed())
614 self.assertEqual(resp.read(2), b'xt')
615 self.assertEqual(resp.read(1), b'')
616 self.assertTrue(resp.isclosed())
617
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100618 def test_partial_readintos_incomplete_body(self):
619 # if the server shuts down the connection before the whole
620 # content-length is delivered, the socket is gracefully closed
621 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
622 sock = FakeSocket(body)
623 resp = client.HTTPResponse(sock)
624 resp.begin()
625 b = bytearray(2)
626 n = resp.readinto(b)
627 self.assertEqual(n, 2)
628 self.assertEqual(bytes(b), b'Te')
629 self.assertFalse(resp.isclosed())
630 n = resp.readinto(b)
631 self.assertEqual(n, 2)
632 self.assertEqual(bytes(b), b'xt')
633 n = resp.readinto(b)
634 self.assertEqual(n, 0)
635 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200636 self.assertFalse(resp.closed)
637 resp.close()
638 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100639
Thomas Wouters89f507f2006-12-13 04:49:30 +0000640 def test_host_port(self):
641 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000642
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200643 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000644 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000645
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000646 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
647 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000648 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200649 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000650 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200651 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
652 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000653 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000654 self.assertEqual(h, c.host)
655 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000656
Thomas Wouters89f507f2006-12-13 04:49:30 +0000657 def test_response_headers(self):
658 # test response with multiple message headers with the same field name.
659 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000660 'Set-Cookie: Customer="WILE_E_COYOTE"; '
661 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000662 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
663 ' Path="/acme"\r\n'
664 '\r\n'
665 'No body\r\n')
666 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
667 ', '
668 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
669 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000670 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671 r.begin()
672 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000673 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000674
Thomas Wouters89f507f2006-12-13 04:49:30 +0000675 def test_read_head(self):
676 # Test that the library doesn't attempt to read any data
677 # from a HEAD request. (Tickles SF bug #622042.)
678 sock = FakeSocket(
679 'HTTP/1.1 200 OK\r\n'
680 'Content-Length: 14432\r\n'
681 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300682 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000683 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000684 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000685 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000686 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000687
Antoine Pitrou38d96432011-12-06 22:33:57 +0100688 def test_readinto_head(self):
689 # Test that the library doesn't attempt to read any data
690 # from a HEAD request. (Tickles SF bug #622042.)
691 sock = FakeSocket(
692 'HTTP/1.1 200 OK\r\n'
693 'Content-Length: 14432\r\n'
694 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300695 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100696 resp = client.HTTPResponse(sock, method="HEAD")
697 resp.begin()
698 b = bytearray(5)
699 if resp.readinto(b) != 0:
700 self.fail("Did not expect response from HEAD request")
701 self.assertEqual(bytes(b), b'\x00'*5)
702
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100703 def test_too_many_headers(self):
704 headers = '\r\n'.join('Header%d: foo' % i
705 for i in range(client._MAXHEADERS + 1)) + '\r\n'
706 text = ('HTTP/1.1 200 OK\r\n' + headers)
707 s = FakeSocket(text)
708 r = client.HTTPResponse(s)
709 self.assertRaisesRegex(client.HTTPException,
710 r"got more than \d+ headers", r.begin)
711
Thomas Wouters89f507f2006-12-13 04:49:30 +0000712 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000713 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000714 b'Accept-Encoding: identity\r\n'
715 b'Transfer-Encoding: chunked\r\n'
716 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000717
Brett Cannon77b7de62010-10-29 23:31:11 +0000718 with open(__file__, 'rb') as body:
719 conn = client.HTTPConnection('example.com')
720 sock = FakeSocket(body)
721 conn.sock = sock
722 conn.request('GET', '/foo', body)
723 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
724 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000725
Antoine Pitrouead1d622009-09-29 18:44:53 +0000726 def test_send(self):
727 expected = b'this is a test this is only a test'
728 conn = client.HTTPConnection('example.com')
729 sock = FakeSocket(None)
730 conn.sock = sock
731 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000732 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000733 sock.data = b''
734 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000735 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000736 sock.data = b''
737 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000738 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000739
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300740 def test_send_updating_file(self):
741 def data():
742 yield 'data'
743 yield None
744 yield 'data_two'
745
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000746 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300747 mode = 'r'
748 d = data()
749 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000750 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300751
752 expected = b'data'
753
754 conn = client.HTTPConnection('example.com')
755 sock = FakeSocket("")
756 conn.sock = sock
757 conn.send(UpdatingFile())
758 self.assertEqual(sock.data, expected)
759
760
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000761 def test_send_iter(self):
762 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
763 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
764 b'\r\nonetwothree'
765
766 def body():
767 yield b"one"
768 yield b"two"
769 yield b"three"
770
771 conn = client.HTTPConnection('example.com')
772 sock = FakeSocket("")
773 conn.sock = sock
774 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000775 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000776
Nir Sofferad455cd2017-11-06 23:16:37 +0200777 def test_blocksize_request(self):
778 """Check that request() respects the configured block size."""
779 blocksize = 8 # For easy debugging.
780 conn = client.HTTPConnection('example.com', blocksize=blocksize)
781 sock = FakeSocket(None)
782 conn.sock = sock
783 expected = b"a" * blocksize + b"b"
784 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
785 self.assertEqual(sock.sendall_calls, 3)
786 body = sock.data.split(b"\r\n\r\n", 1)[1]
787 self.assertEqual(body, expected)
788
789 def test_blocksize_send(self):
790 """Check that send() respects the configured block size."""
791 blocksize = 8 # For easy debugging.
792 conn = client.HTTPConnection('example.com', blocksize=blocksize)
793 sock = FakeSocket(None)
794 conn.sock = sock
795 expected = b"a" * blocksize + b"b"
796 conn.send(io.BytesIO(expected))
797 self.assertEqual(sock.sendall_calls, 2)
798 self.assertEqual(sock.data, expected)
799
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800800 def test_send_type_error(self):
801 # See: Issue #12676
802 conn = client.HTTPConnection('example.com')
803 conn.sock = FakeSocket('')
804 with self.assertRaises(TypeError):
805 conn.request('POST', 'test', conn)
806
Christian Heimesa612dc02008-02-24 13:08:18 +0000807 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000808 expected = chunked_expected
809 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000810 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000811 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100812 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000813 resp.close()
814
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100815 # Various read sizes
816 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000817 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100818 resp = client.HTTPResponse(sock, method="GET")
819 resp.begin()
820 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
821 resp.close()
822
Christian Heimesa612dc02008-02-24 13:08:18 +0000823 for x in ('', 'foo\r\n'):
824 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000825 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000826 resp.begin()
827 try:
828 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000829 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100830 self.assertEqual(i.partial, expected)
831 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
832 self.assertEqual(repr(i), expected_message)
833 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000834 else:
835 self.fail('IncompleteRead expected')
836 finally:
837 resp.close()
838
Antoine Pitrou38d96432011-12-06 22:33:57 +0100839 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000840
841 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100842 nexpected = len(expected)
843 b = bytearray(128)
844
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000845 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100846 resp = client.HTTPResponse(sock, method="GET")
847 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100848 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100849 self.assertEqual(b[:nexpected], expected)
850 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100851 resp.close()
852
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100853 # Various read sizes
854 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000855 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100856 resp = client.HTTPResponse(sock, method="GET")
857 resp.begin()
858 m = memoryview(b)
859 i = resp.readinto(m[0:n])
860 i += resp.readinto(m[i:n + i])
861 i += resp.readinto(m[i:])
862 self.assertEqual(b[:nexpected], expected)
863 self.assertEqual(i, nexpected)
864 resp.close()
865
Antoine Pitrou38d96432011-12-06 22:33:57 +0100866 for x in ('', 'foo\r\n'):
867 sock = FakeSocket(chunked_start + x)
868 resp = client.HTTPResponse(sock, method="GET")
869 resp.begin()
870 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100871 n = resp.readinto(b)
872 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100873 self.assertEqual(i.partial, expected)
874 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
875 self.assertEqual(repr(i), expected_message)
876 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100877 else:
878 self.fail('IncompleteRead expected')
879 finally:
880 resp.close()
881
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000882 def test_chunked_head(self):
883 chunked_start = (
884 'HTTP/1.1 200 OK\r\n'
885 'Transfer-Encoding: chunked\r\n\r\n'
886 'a\r\n'
887 'hello world\r\n'
888 '1\r\n'
889 'd\r\n'
890 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000891 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000892 resp = client.HTTPResponse(sock, method="HEAD")
893 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000894 self.assertEqual(resp.read(), b'')
895 self.assertEqual(resp.status, 200)
896 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000897 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200898 self.assertFalse(resp.closed)
899 resp.close()
900 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000901
Antoine Pitrou38d96432011-12-06 22:33:57 +0100902 def test_readinto_chunked_head(self):
903 chunked_start = (
904 'HTTP/1.1 200 OK\r\n'
905 'Transfer-Encoding: chunked\r\n\r\n'
906 'a\r\n'
907 'hello world\r\n'
908 '1\r\n'
909 'd\r\n'
910 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000911 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100912 resp = client.HTTPResponse(sock, method="HEAD")
913 resp.begin()
914 b = bytearray(5)
915 n = resp.readinto(b)
916 self.assertEqual(n, 0)
917 self.assertEqual(bytes(b), b'\x00'*5)
918 self.assertEqual(resp.status, 200)
919 self.assertEqual(resp.reason, 'OK')
920 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200921 self.assertFalse(resp.closed)
922 resp.close()
923 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100924
Christian Heimesa612dc02008-02-24 13:08:18 +0000925 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000926 sock = FakeSocket(
927 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000928 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000929 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000930 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100931 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000932
Benjamin Peterson6accb982009-03-02 22:50:25 +0000933 def test_incomplete_read(self):
934 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000935 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000936 resp.begin()
937 try:
938 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000939 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000940 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000941 self.assertEqual(repr(i),
942 "IncompleteRead(7 bytes read, 3 more expected)")
943 self.assertEqual(str(i),
944 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100945 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000946 else:
947 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000948
Jeremy Hylton636950f2009-03-28 04:34:21 +0000949 def test_epipe(self):
950 sock = EPipeSocket(
951 "HTTP/1.0 401 Authorization Required\r\n"
952 "Content-type: text/html\r\n"
953 "WWW-Authenticate: Basic realm=\"example\"\r\n",
954 b"Content-Length")
955 conn = client.HTTPConnection("example.com")
956 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200957 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000958 lambda: conn.request("PUT", "/url", "body"))
959 resp = conn.getresponse()
960 self.assertEqual(401, resp.status)
961 self.assertEqual("Basic realm=\"example\"",
962 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000963
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000964 # Test lines overflowing the max line size (_MAXLINE in http.client)
965
966 def test_overflowing_status_line(self):
967 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
968 resp = client.HTTPResponse(FakeSocket(body))
969 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
970
971 def test_overflowing_header_line(self):
972 body = (
973 'HTTP/1.1 200 OK\r\n'
974 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
975 )
976 resp = client.HTTPResponse(FakeSocket(body))
977 self.assertRaises(client.LineTooLong, resp.begin)
978
979 def test_overflowing_chunked_line(self):
980 body = (
981 'HTTP/1.1 200 OK\r\n'
982 'Transfer-Encoding: chunked\r\n\r\n'
983 + '0' * 65536 + 'a\r\n'
984 'hello world\r\n'
985 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000986 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000987 )
988 resp = client.HTTPResponse(FakeSocket(body))
989 resp.begin()
990 self.assertRaises(client.LineTooLong, resp.read)
991
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800992 def test_early_eof(self):
993 # Test httpresponse with no \r\n termination,
994 body = "HTTP/1.1 200 Ok"
995 sock = FakeSocket(body)
996 resp = client.HTTPResponse(sock)
997 resp.begin()
998 self.assertEqual(resp.read(), b'')
999 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001000 self.assertFalse(resp.closed)
1001 resp.close()
1002 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001003
Serhiy Storchakab491e052014-12-01 13:07:45 +02001004 def test_error_leak(self):
1005 # Test that the socket is not leaked if getresponse() fails
1006 conn = client.HTTPConnection('example.com')
1007 response = None
1008 class Response(client.HTTPResponse):
1009 def __init__(self, *pos, **kw):
1010 nonlocal response
1011 response = self # Avoid garbage collector closing the socket
1012 client.HTTPResponse.__init__(self, *pos, **kw)
1013 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001014 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001015 conn.request('GET', '/')
1016 self.assertRaises(client.BadStatusLine, conn.getresponse)
1017 self.assertTrue(response.closed)
1018 self.assertTrue(conn.sock.file_closed)
1019
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001020 def test_chunked_extension(self):
1021 extra = '3;foo=bar\r\n' + 'abc\r\n'
1022 expected = chunked_expected + b'abc'
1023
1024 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1025 resp = client.HTTPResponse(sock, method="GET")
1026 resp.begin()
1027 self.assertEqual(resp.read(), expected)
1028 resp.close()
1029
1030 def test_chunked_missing_end(self):
1031 """some servers may serve up a short chunked encoding stream"""
1032 expected = chunked_expected
1033 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1034 resp = client.HTTPResponse(sock, method="GET")
1035 resp.begin()
1036 self.assertEqual(resp.read(), expected)
1037 resp.close()
1038
1039 def test_chunked_trailers(self):
1040 """See that trailers are read and ignored"""
1041 expected = chunked_expected
1042 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1043 resp = client.HTTPResponse(sock, method="GET")
1044 resp.begin()
1045 self.assertEqual(resp.read(), expected)
1046 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001047 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001048 resp.close()
1049
1050 def test_chunked_sync(self):
1051 """Check that we don't read past the end of the chunked-encoding stream"""
1052 expected = chunked_expected
1053 extradata = "extradata"
1054 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1055 resp = client.HTTPResponse(sock, method="GET")
1056 resp.begin()
1057 self.assertEqual(resp.read(), expected)
1058 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001059 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001060 resp.close()
1061
1062 def test_content_length_sync(self):
1063 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001064 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001065 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001066 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 +00001067 resp = client.HTTPResponse(sock, method="GET")
1068 resp.begin()
1069 self.assertEqual(resp.read(), expected)
1070 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001071 self.assertEqual(sock.file.read(), extradata) #we read to the end
1072 resp.close()
1073
1074 def test_readlines_content_length(self):
1075 extradata = b"extradata"
1076 expected = b"Hello123\r\n"
1077 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1078 resp = client.HTTPResponse(sock, method="GET")
1079 resp.begin()
1080 self.assertEqual(resp.readlines(2000), [expected])
1081 # the file should now have our extradata ready to be read
1082 self.assertEqual(sock.file.read(), extradata) #we read to the end
1083 resp.close()
1084
1085 def test_read1_content_length(self):
1086 extradata = b"extradata"
1087 expected = b"Hello123\r\n"
1088 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1089 resp = client.HTTPResponse(sock, method="GET")
1090 resp.begin()
1091 self.assertEqual(resp.read1(2000), expected)
1092 # the file should now have our extradata ready to be read
1093 self.assertEqual(sock.file.read(), extradata) #we read to the end
1094 resp.close()
1095
1096 def test_readline_bound_content_length(self):
1097 extradata = b"extradata"
1098 expected = b"Hello123\r\n"
1099 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1100 resp = client.HTTPResponse(sock, method="GET")
1101 resp.begin()
1102 self.assertEqual(resp.readline(10), expected)
1103 self.assertEqual(resp.readline(10), b"")
1104 # the file should now have our extradata ready to be read
1105 self.assertEqual(sock.file.read(), extradata) #we read to the end
1106 resp.close()
1107
1108 def test_read1_bound_content_length(self):
1109 extradata = b"extradata"
1110 expected = b"Hello123\r\n"
1111 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1112 resp = client.HTTPResponse(sock, method="GET")
1113 resp.begin()
1114 self.assertEqual(resp.read1(20), expected*2)
1115 self.assertEqual(resp.read(), expected)
1116 # the file should now have our extradata ready to be read
1117 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001118 resp.close()
1119
Martin Panterd979b2c2016-04-09 14:03:17 +00001120 def test_response_fileno(self):
1121 # Make sure fd returned by fileno is valid.
Martin Panterd979b2c2016-04-09 14:03:17 +00001122 serv = socket.socket(
1123 socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
1124 self.addCleanup(serv.close)
1125 serv.bind((HOST, 0))
1126 serv.listen()
1127
1128 result = None
1129 def run_server():
1130 [conn, address] = serv.accept()
1131 with conn, conn.makefile("rb") as reader:
1132 # Read the request header until a blank line
1133 while True:
1134 line = reader.readline()
1135 if not line.rstrip(b"\r\n"):
1136 break
1137 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1138 nonlocal result
1139 result = reader.read()
1140
1141 thread = threading.Thread(target=run_server)
1142 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001143 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001144 conn = client.HTTPConnection(*serv.getsockname())
1145 conn.request("CONNECT", "dummy:1234")
1146 response = conn.getresponse()
1147 try:
1148 self.assertEqual(response.status, client.OK)
1149 s = socket.socket(fileno=response.fileno())
1150 try:
1151 s.sendall(b"proxied data\n")
1152 finally:
1153 s.detach()
1154 finally:
1155 response.close()
1156 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001157 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001158 self.assertEqual(result, b"proxied data\n")
1159
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001160class ExtendedReadTest(TestCase):
1161 """
1162 Test peek(), read1(), readline()
1163 """
1164 lines = (
1165 'HTTP/1.1 200 OK\r\n'
1166 '\r\n'
1167 'hello world!\n'
1168 'and now \n'
1169 'for something completely different\n'
1170 'foo'
1171 )
1172 lines_expected = lines[lines.find('hello'):].encode("ascii")
1173 lines_chunked = (
1174 'HTTP/1.1 200 OK\r\n'
1175 'Transfer-Encoding: chunked\r\n\r\n'
1176 'a\r\n'
1177 'hello worl\r\n'
1178 '3\r\n'
1179 'd!\n\r\n'
1180 '9\r\n'
1181 'and now \n\r\n'
1182 '23\r\n'
1183 'for something completely different\n\r\n'
1184 '3\r\n'
1185 'foo\r\n'
1186 '0\r\n' # terminating chunk
1187 '\r\n' # end of trailers
1188 )
1189
1190 def setUp(self):
1191 sock = FakeSocket(self.lines)
1192 resp = client.HTTPResponse(sock, method="GET")
1193 resp.begin()
1194 resp.fp = io.BufferedReader(resp.fp)
1195 self.resp = resp
1196
1197
1198
1199 def test_peek(self):
1200 resp = self.resp
1201 # patch up the buffered peek so that it returns not too much stuff
1202 oldpeek = resp.fp.peek
1203 def mypeek(n=-1):
1204 p = oldpeek(n)
1205 if n >= 0:
1206 return p[:n]
1207 return p[:10]
1208 resp.fp.peek = mypeek
1209
1210 all = []
1211 while True:
1212 # try a short peek
1213 p = resp.peek(3)
1214 if p:
1215 self.assertGreater(len(p), 0)
1216 # then unbounded peek
1217 p2 = resp.peek()
1218 self.assertGreaterEqual(len(p2), len(p))
1219 self.assertTrue(p2.startswith(p))
1220 next = resp.read(len(p2))
1221 self.assertEqual(next, p2)
1222 else:
1223 next = resp.read()
1224 self.assertFalse(next)
1225 all.append(next)
1226 if not next:
1227 break
1228 self.assertEqual(b"".join(all), self.lines_expected)
1229
1230 def test_readline(self):
1231 resp = self.resp
1232 self._verify_readline(self.resp.readline, self.lines_expected)
1233
1234 def _verify_readline(self, readline, expected):
1235 all = []
1236 while True:
1237 # short readlines
1238 line = readline(5)
1239 if line and line != b"foo":
1240 if len(line) < 5:
1241 self.assertTrue(line.endswith(b"\n"))
1242 all.append(line)
1243 if not line:
1244 break
1245 self.assertEqual(b"".join(all), expected)
1246
1247 def test_read1(self):
1248 resp = self.resp
1249 def r():
1250 res = resp.read1(4)
1251 self.assertLessEqual(len(res), 4)
1252 return res
1253 readliner = Readliner(r)
1254 self._verify_readline(readliner.readline, self.lines_expected)
1255
1256 def test_read1_unbounded(self):
1257 resp = self.resp
1258 all = []
1259 while True:
1260 data = resp.read1()
1261 if not data:
1262 break
1263 all.append(data)
1264 self.assertEqual(b"".join(all), self.lines_expected)
1265
1266 def test_read1_bounded(self):
1267 resp = self.resp
1268 all = []
1269 while True:
1270 data = resp.read1(10)
1271 if not data:
1272 break
1273 self.assertLessEqual(len(data), 10)
1274 all.append(data)
1275 self.assertEqual(b"".join(all), self.lines_expected)
1276
1277 def test_read1_0(self):
1278 self.assertEqual(self.resp.read1(0), b"")
1279
1280 def test_peek_0(self):
1281 p = self.resp.peek(0)
1282 self.assertLessEqual(0, len(p))
1283
1284class ExtendedReadTestChunked(ExtendedReadTest):
1285 """
1286 Test peek(), read1(), readline() in chunked mode
1287 """
1288 lines = (
1289 'HTTP/1.1 200 OK\r\n'
1290 'Transfer-Encoding: chunked\r\n\r\n'
1291 'a\r\n'
1292 'hello worl\r\n'
1293 '3\r\n'
1294 'd!\n\r\n'
1295 '9\r\n'
1296 'and now \n\r\n'
1297 '23\r\n'
1298 'for something completely different\n\r\n'
1299 '3\r\n'
1300 'foo\r\n'
1301 '0\r\n' # terminating chunk
1302 '\r\n' # end of trailers
1303 )
1304
1305
1306class Readliner:
1307 """
1308 a simple readline class that uses an arbitrary read function and buffering
1309 """
1310 def __init__(self, readfunc):
1311 self.readfunc = readfunc
1312 self.remainder = b""
1313
1314 def readline(self, limit):
1315 data = []
1316 datalen = 0
1317 read = self.remainder
1318 try:
1319 while True:
1320 idx = read.find(b'\n')
1321 if idx != -1:
1322 break
1323 if datalen + len(read) >= limit:
1324 idx = limit - datalen - 1
1325 # read more data
1326 data.append(read)
1327 read = self.readfunc()
1328 if not read:
1329 idx = 0 #eof condition
1330 break
1331 idx += 1
1332 data.append(read[:idx])
1333 self.remainder = read[idx:]
1334 return b"".join(data)
1335 except:
1336 self.remainder = b"".join(data)
1337 raise
1338
Berker Peksagbabc6882015-02-20 09:39:38 +02001339
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001340class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001341 def test_all(self):
1342 # Documented objects defined in the module should be in __all__
1343 expected = {"responses"} # White-list documented dict() object
1344 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1345 # intentionally omitted for simplicity
1346 blacklist = {"HTTPMessage", "parse_headers"}
1347 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001348 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001349 continue
1350 module_object = getattr(client, name)
1351 if getattr(module_object, "__module__", None) == "http.client":
1352 expected.add(name)
1353 self.assertCountEqual(client.__all__, expected)
1354
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001355 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001356 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001357
Berker Peksagabbf0f42015-02-20 14:57:31 +02001358 def test_client_constants(self):
1359 # Make sure we don't break backward compatibility with 3.4
1360 expected = [
1361 'CONTINUE',
1362 'SWITCHING_PROTOCOLS',
1363 'PROCESSING',
1364 'OK',
1365 'CREATED',
1366 'ACCEPTED',
1367 'NON_AUTHORITATIVE_INFORMATION',
1368 'NO_CONTENT',
1369 'RESET_CONTENT',
1370 'PARTIAL_CONTENT',
1371 'MULTI_STATUS',
1372 'IM_USED',
1373 'MULTIPLE_CHOICES',
1374 'MOVED_PERMANENTLY',
1375 'FOUND',
1376 'SEE_OTHER',
1377 'NOT_MODIFIED',
1378 'USE_PROXY',
1379 'TEMPORARY_REDIRECT',
1380 'BAD_REQUEST',
1381 'UNAUTHORIZED',
1382 'PAYMENT_REQUIRED',
1383 'FORBIDDEN',
1384 'NOT_FOUND',
1385 'METHOD_NOT_ALLOWED',
1386 'NOT_ACCEPTABLE',
1387 'PROXY_AUTHENTICATION_REQUIRED',
1388 'REQUEST_TIMEOUT',
1389 'CONFLICT',
1390 'GONE',
1391 'LENGTH_REQUIRED',
1392 'PRECONDITION_FAILED',
1393 'REQUEST_ENTITY_TOO_LARGE',
1394 'REQUEST_URI_TOO_LONG',
1395 'UNSUPPORTED_MEDIA_TYPE',
1396 'REQUESTED_RANGE_NOT_SATISFIABLE',
1397 'EXPECTATION_FAILED',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001398 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001399 'UNPROCESSABLE_ENTITY',
1400 'LOCKED',
1401 'FAILED_DEPENDENCY',
1402 'UPGRADE_REQUIRED',
1403 'PRECONDITION_REQUIRED',
1404 'TOO_MANY_REQUESTS',
1405 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1406 'INTERNAL_SERVER_ERROR',
1407 'NOT_IMPLEMENTED',
1408 'BAD_GATEWAY',
1409 'SERVICE_UNAVAILABLE',
1410 'GATEWAY_TIMEOUT',
1411 'HTTP_VERSION_NOT_SUPPORTED',
1412 'INSUFFICIENT_STORAGE',
1413 'NOT_EXTENDED',
1414 'NETWORK_AUTHENTICATION_REQUIRED',
1415 ]
1416 for const in expected:
1417 with self.subTest(constant=const):
1418 self.assertTrue(hasattr(client, const))
1419
Gregory P. Smithb4066372010-01-03 03:28:29 +00001420
1421class SourceAddressTest(TestCase):
1422 def setUp(self):
1423 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1424 self.port = support.bind_port(self.serv)
1425 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001426 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001427 self.conn = None
1428
1429 def tearDown(self):
1430 if self.conn:
1431 self.conn.close()
1432 self.conn = None
1433 self.serv.close()
1434 self.serv = None
1435
1436 def testHTTPConnectionSourceAddress(self):
1437 self.conn = client.HTTPConnection(HOST, self.port,
1438 source_address=('', self.source_port))
1439 self.conn.connect()
1440 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1441
1442 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1443 'http.client.HTTPSConnection not defined')
1444 def testHTTPSConnectionSourceAddress(self):
1445 self.conn = client.HTTPSConnection(HOST, self.port,
1446 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001447 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001448 # this code doesn't deal with setting up an active running SSL server
1449 # for an ssl_wrapped connect() to actually return from.
1450
1451
Guido van Rossumd8faa362007-04-27 19:54:29 +00001452class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001453 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001454
1455 def setUp(self):
1456 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001457 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001458 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001459
1460 def tearDown(self):
1461 self.serv.close()
1462 self.serv = None
1463
1464 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001465 # This will prove that the timeout gets through HTTPConnection
1466 # and into the socket.
1467
Georg Brandlf78e02b2008-06-10 17:40:04 +00001468 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001469 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001470 socket.setdefaulttimeout(30)
1471 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001472 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001473 httpConn.connect()
1474 finally:
1475 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001476 self.assertEqual(httpConn.sock.gettimeout(), 30)
1477 httpConn.close()
1478
Georg Brandlf78e02b2008-06-10 17:40:04 +00001479 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001480 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001481 socket.setdefaulttimeout(30)
1482 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001483 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001484 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001485 httpConn.connect()
1486 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001487 socket.setdefaulttimeout(None)
1488 self.assertEqual(httpConn.sock.gettimeout(), None)
1489 httpConn.close()
1490
1491 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001492 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001493 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001494 self.assertEqual(httpConn.sock.gettimeout(), 30)
1495 httpConn.close()
1496
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001497
R David Murraycae7bdb2015-04-05 19:26:29 -04001498class PersistenceTest(TestCase):
1499
1500 def test_reuse_reconnect(self):
1501 # Should reuse or reconnect depending on header from server
1502 tests = (
1503 ('1.0', '', False),
1504 ('1.0', 'Connection: keep-alive\r\n', True),
1505 ('1.1', '', True),
1506 ('1.1', 'Connection: close\r\n', False),
1507 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1508 ('1.1', 'Connection: cloSE\r\n', False),
1509 )
1510 for version, header, reuse in tests:
1511 with self.subTest(version=version, header=header):
1512 msg = (
1513 'HTTP/{} 200 OK\r\n'
1514 '{}'
1515 'Content-Length: 12\r\n'
1516 '\r\n'
1517 'Dummy body\r\n'
1518 ).format(version, header)
1519 conn = FakeSocketHTTPConnection(msg)
1520 self.assertIsNone(conn.sock)
1521 conn.request('GET', '/open-connection')
1522 with conn.getresponse() as response:
1523 self.assertEqual(conn.sock is None, not reuse)
1524 response.read()
1525 self.assertEqual(conn.sock is None, not reuse)
1526 self.assertEqual(conn.connections, 1)
1527 conn.request('GET', '/subsequent-request')
1528 self.assertEqual(conn.connections, 1 if reuse else 2)
1529
1530 def test_disconnected(self):
1531
1532 def make_reset_reader(text):
1533 """Return BufferedReader that raises ECONNRESET at EOF"""
1534 stream = io.BytesIO(text)
1535 def readinto(buffer):
1536 size = io.BytesIO.readinto(stream, buffer)
1537 if size == 0:
1538 raise ConnectionResetError()
1539 return size
1540 stream.readinto = readinto
1541 return io.BufferedReader(stream)
1542
1543 tests = (
1544 (io.BytesIO, client.RemoteDisconnected),
1545 (make_reset_reader, ConnectionResetError),
1546 )
1547 for stream_factory, exception in tests:
1548 with self.subTest(exception=exception):
1549 conn = FakeSocketHTTPConnection(b'', stream_factory)
1550 conn.request('GET', '/eof-response')
1551 self.assertRaises(exception, conn.getresponse)
1552 self.assertIsNone(conn.sock)
1553 # HTTPConnection.connect() should be automatically invoked
1554 conn.request('GET', '/reconnect')
1555 self.assertEqual(conn.connections, 2)
1556
1557 def test_100_close(self):
1558 conn = FakeSocketHTTPConnection(
1559 b'HTTP/1.1 100 Continue\r\n'
1560 b'\r\n'
1561 # Missing final response
1562 )
1563 conn.request('GET', '/', headers={'Expect': '100-continue'})
1564 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1565 self.assertIsNone(conn.sock)
1566 conn.request('GET', '/reconnect')
1567 self.assertEqual(conn.connections, 2)
1568
1569
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001570class HTTPSTest(TestCase):
1571
1572 def setUp(self):
1573 if not hasattr(client, 'HTTPSConnection'):
1574 self.skipTest('ssl support required')
1575
1576 def make_server(self, certfile):
1577 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001578 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001579
1580 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001581 # simple test to check it's storing the timeout
1582 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1583 self.assertEqual(h.timeout, 30)
1584
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001585 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001586 # Default settings: requires a valid cert from a trusted CA
1587 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001588 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001589 with support.transient_internet('self-signed.pythontest.net'):
1590 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1591 with self.assertRaises(ssl.SSLError) as exc_info:
1592 h.request('GET', '/')
1593 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1594
1595 def test_networked_noverification(self):
1596 # Switch off cert verification
1597 import ssl
1598 support.requires('network')
1599 with support.transient_internet('self-signed.pythontest.net'):
1600 context = ssl._create_unverified_context()
1601 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1602 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001603 h.request('GET', '/')
1604 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001605 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001606 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001607 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001608
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001609 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001610 def test_networked_trusted_by_default_cert(self):
1611 # Default settings: requires a valid cert from a trusted CA
1612 support.requires('network')
1613 with support.transient_internet('www.python.org'):
1614 h = client.HTTPSConnection('www.python.org', 443)
1615 h.request('GET', '/')
1616 resp = h.getresponse()
1617 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001618 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001619 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001620 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001621
1622 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001623 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001624 import ssl
1625 support.requires('network')
Miss Islington (bot)ffa29b52019-05-06 20:51:25 -07001626 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
1627 with support.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001628 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1629 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1630 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001631 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Miss Islington (bot)ffa29b52019-05-06 20:51:25 -07001632 try:
1633 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1634 context=context)
1635 h.request('GET', '/')
1636 resp = h.getresponse()
1637 except ssl.SSLError as ssl_err:
1638 ssl_err_str = str(ssl_err)
1639 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1640 # modern Linux distros (Debian Buster, etc) default OpenSSL
1641 # configurations it'll fail saying "key too weak" until we
1642 # address https://bugs.python.org/issue36816 to use a proper
1643 # key size on self-signed.pythontest.net.
1644 if re.search(r'(?i)key.too.weak', ssl_err_str):
1645 raise unittest.SkipTest(
1646 f'Got {ssl_err_str} trying to connect '
1647 f'to {selfsigned_pythontestdotnet}. '
1648 'See https://bugs.python.org/issue36816.')
1649 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001650 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001651 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001652 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001653 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001654
1655 def test_networked_bad_cert(self):
1656 # We feed a "CA" cert that is unrelated to the server's cert
1657 import ssl
1658 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001659 with support.transient_internet('self-signed.pythontest.net'):
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)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001662 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1663 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001664 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001665 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1666
1667 def test_local_unknown_cert(self):
1668 # The custom cert isn't known to the default trust bundle
1669 import ssl
1670 server = self.make_server(CERT_localhost)
1671 h = client.HTTPSConnection('localhost', server.port)
1672 with self.assertRaises(ssl.SSLError) as exc_info:
1673 h.request('GET', '/')
1674 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001675
1676 def test_local_good_hostname(self):
1677 # The (valid) cert validates the HTTP hostname
1678 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001679 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001680 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001681 context.load_verify_locations(CERT_localhost)
1682 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001683 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001684 h.request('GET', '/nonexistent')
1685 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001686 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001687 self.assertEqual(resp.status, 404)
1688
1689 def test_local_bad_hostname(self):
1690 # The (valid) cert doesn't validate the HTTP hostname
1691 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001692 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001693 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001694 context.load_verify_locations(CERT_fakehostname)
1695 h = client.HTTPSConnection('localhost', server.port, context=context)
1696 with self.assertRaises(ssl.CertificateError):
1697 h.request('GET', '/')
1698 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001699 with support.check_warnings(('', DeprecationWarning)):
1700 h = client.HTTPSConnection('localhost', server.port,
1701 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001702 with self.assertRaises(ssl.CertificateError):
1703 h.request('GET', '/')
1704 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001705 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001706 with support.check_warnings(('', DeprecationWarning)):
1707 h = client.HTTPSConnection('localhost', server.port,
1708 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001709 h.request('GET', '/nonexistent')
1710 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001711 resp.close()
1712 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001713 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001714 # The context's check_hostname setting is used if one isn't passed to
1715 # HTTPSConnection.
1716 context.check_hostname = False
1717 h = client.HTTPSConnection('localhost', server.port, context=context)
1718 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001719 resp = h.getresponse()
1720 self.assertEqual(resp.status, 404)
1721 resp.close()
1722 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001723 # Passing check_hostname to HTTPSConnection should override the
1724 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001725 with support.check_warnings(('', DeprecationWarning)):
1726 h = client.HTTPSConnection('localhost', server.port,
1727 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001728 with self.assertRaises(ssl.CertificateError):
1729 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001730
Petri Lehtinene119c402011-10-26 21:29:15 +03001731 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1732 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001733 def test_host_port(self):
1734 # Check invalid host_port
1735
1736 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1737 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1738
1739 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1740 "fe80::207:e9ff:fe9b", 8000),
1741 ("www.python.org:443", "www.python.org", 443),
1742 ("www.python.org:", "www.python.org", 443),
1743 ("www.python.org", "www.python.org", 443),
1744 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1745 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1746 443)):
1747 c = client.HTTPSConnection(hp)
1748 self.assertEqual(h, c.host)
1749 self.assertEqual(p, c.port)
1750
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001751
Jeremy Hylton236654b2009-03-27 20:24:34 +00001752class RequestBodyTest(TestCase):
1753 """Test cases where a request includes a message body."""
1754
1755 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001756 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001757 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001758 self.conn.sock = self.sock
1759
1760 def get_headers_and_fp(self):
1761 f = io.BytesIO(self.sock.data)
1762 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001763 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001764 return message, f
1765
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001766 def test_list_body(self):
1767 # Note that no content-length is automatically calculated for
1768 # an iterable. The request will fall back to send chunked
1769 # transfer encoding.
1770 cases = (
1771 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1772 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1773 )
1774 for body, expected in cases:
1775 with self.subTest(body):
1776 self.conn = client.HTTPConnection('example.com')
1777 self.conn.sock = self.sock = FakeSocket('')
1778
1779 self.conn.request('PUT', '/url', body)
1780 msg, f = self.get_headers_and_fp()
1781 self.assertNotIn('Content-Type', msg)
1782 self.assertNotIn('Content-Length', msg)
1783 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1784 self.assertEqual(expected, f.read())
1785
Jeremy Hylton236654b2009-03-27 20:24:34 +00001786 def test_manual_content_length(self):
1787 # Set an incorrect content-length so that we can verify that
1788 # it will not be over-ridden by the library.
1789 self.conn.request("PUT", "/url", "body",
1790 {"Content-Length": "42"})
1791 message, f = self.get_headers_and_fp()
1792 self.assertEqual("42", message.get("content-length"))
1793 self.assertEqual(4, len(f.read()))
1794
1795 def test_ascii_body(self):
1796 self.conn.request("PUT", "/url", "body")
1797 message, f = self.get_headers_and_fp()
1798 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001799 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001800 self.assertEqual("4", message.get("content-length"))
1801 self.assertEqual(b'body', f.read())
1802
1803 def test_latin1_body(self):
1804 self.conn.request("PUT", "/url", "body\xc1")
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())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001808 self.assertEqual("5", message.get("content-length"))
1809 self.assertEqual(b'body\xc1', f.read())
1810
1811 def test_bytes_body(self):
1812 self.conn.request("PUT", "/url", b"body\xc1")
1813 message, f = self.get_headers_and_fp()
1814 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001815 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001816 self.assertEqual("5", message.get("content-length"))
1817 self.assertEqual(b'body\xc1', f.read())
1818
Martin Panteref91bb22016-08-27 01:39:26 +00001819 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001820 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001821 with open(support.TESTFN, "w") as f:
1822 f.write("body")
1823 with open(support.TESTFN) as f:
1824 self.conn.request("PUT", "/url", f)
1825 message, f = self.get_headers_and_fp()
1826 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001827 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001828 # No content-length will be determined for files; the body
1829 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001830 self.assertIsNone(message.get("content-length"))
1831 self.assertEqual("chunked", message.get("transfer-encoding"))
1832 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001833
1834 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001835 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001836 with open(support.TESTFN, "wb") as f:
1837 f.write(b"body\xc1")
1838 with open(support.TESTFN, "rb") as f:
1839 self.conn.request("PUT", "/url", f)
1840 message, f = self.get_headers_and_fp()
1841 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001842 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001843 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1844 self.assertNotIn("Content-Length", message)
1845 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001846
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001847
1848class HTTPResponseTest(TestCase):
1849
1850 def setUp(self):
1851 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1852 second-value\r\n\r\nText"
1853 sock = FakeSocket(body)
1854 self.resp = client.HTTPResponse(sock)
1855 self.resp.begin()
1856
1857 def test_getting_header(self):
1858 header = self.resp.getheader('My-Header')
1859 self.assertEqual(header, 'first-value, second-value')
1860
1861 header = self.resp.getheader('My-Header', 'some default')
1862 self.assertEqual(header, 'first-value, second-value')
1863
1864 def test_getting_nonexistent_header_with_string_default(self):
1865 header = self.resp.getheader('No-Such-Header', 'default-value')
1866 self.assertEqual(header, 'default-value')
1867
1868 def test_getting_nonexistent_header_with_iterable_default(self):
1869 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1870 self.assertEqual(header, 'default, values')
1871
1872 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1873 self.assertEqual(header, 'default, values')
1874
1875 def test_getting_nonexistent_header_without_default(self):
1876 header = self.resp.getheader('No-Such-Header')
1877 self.assertEqual(header, None)
1878
1879 def test_getting_header_defaultint(self):
1880 header = self.resp.getheader('No-Such-Header',default=42)
1881 self.assertEqual(header, 42)
1882
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001883class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001884 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001885 response_text = (
1886 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1887 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1888 'Content-Length: 42\r\n\r\n'
1889 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001890 self.host = 'proxy.com'
1891 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001892 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001893
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001894 def tearDown(self):
1895 self.conn.close()
1896
Berker Peksagab53ab02015-02-03 12:22:11 +02001897 def _create_connection(self, response_text):
1898 def create_connection(address, timeout=None, source_address=None):
1899 return FakeSocket(response_text, host=address[0], port=address[1])
1900 return create_connection
1901
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001902 def test_set_tunnel_host_port_headers(self):
1903 tunnel_host = 'destination.com'
1904 tunnel_port = 8888
1905 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1906 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1907 headers=tunnel_headers)
1908 self.conn.request('HEAD', '/', '')
1909 self.assertEqual(self.conn.sock.host, self.host)
1910 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1911 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1912 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1913 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1914
1915 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001916 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001917 self.conn.connect()
1918 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001919 'destination.com')
1920
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001921 def test_connect_with_tunnel(self):
1922 self.conn.set_tunnel('destination.com')
1923 self.conn.request('HEAD', '/', '')
1924 self.assertEqual(self.conn.sock.host, self.host)
1925 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1926 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001927 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001928 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1929 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001930
1931 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001932 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001933
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001934 def test_connect_put_request(self):
1935 self.conn.set_tunnel('destination.com')
1936 self.conn.request('PUT', '/', '')
1937 self.assertEqual(self.conn.sock.host, self.host)
1938 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1939 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1940 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1941
Berker Peksagab53ab02015-02-03 12:22:11 +02001942 def test_tunnel_debuglog(self):
1943 expected_header = 'X-Dummy: 1'
1944 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1945
1946 self.conn.set_debuglevel(1)
1947 self.conn._create_connection = self._create_connection(response_text)
1948 self.conn.set_tunnel('destination.com')
1949
1950 with support.captured_stdout() as output:
1951 self.conn.request('PUT', '/', '')
1952 lines = output.getvalue().splitlines()
1953 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001954
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001955
Thomas Wouters89f507f2006-12-13 04:49:30 +00001956if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04001957 unittest.main(verbosity=2)