blob: 5a5fcecbc9c15d967363c58fbf33f51d2c6c8560 [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 Galindo162d45c2019-08-09 01:22:59 +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
Miss Islington (bot)668d3212020-07-18 13:39:12 -0700367class HttpMethodTests(TestCase):
368 def test_invalid_method_names(self):
369 methods = (
370 'GET\r',
371 'POST\n',
372 'PUT\n\r',
373 'POST\nValue',
374 'POST\nHOST:abc',
375 'GET\nrHost:abc\n',
376 'POST\rRemainder:\r',
377 'GET\rHOST:\n',
378 '\nPUT'
379 )
380
381 for method in methods:
382 with self.assertRaisesRegex(
383 ValueError, "method can't contain control characters"):
384 conn = client.HTTPConnection('example.com')
385 conn.sock = FakeSocket(None)
386 conn.request(method=method, url="/")
387
388
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000389class TransferEncodingTest(TestCase):
390 expected_body = b"It's just a flesh wound"
391
392 def test_endheaders_chunked(self):
393 conn = client.HTTPConnection('example.com')
394 conn.sock = FakeSocket(b'')
395 conn.putrequest('POST', '/')
396 conn.endheaders(self._make_body(), encode_chunked=True)
397
398 _, _, body = self._parse_request(conn.sock.data)
399 body = self._parse_chunked(body)
400 self.assertEqual(body, self.expected_body)
401
402 def test_explicit_headers(self):
403 # explicit chunked
404 conn = client.HTTPConnection('example.com')
405 conn.sock = FakeSocket(b'')
406 # this shouldn't actually be automatically chunk-encoded because the
407 # calling code has explicitly stated that it's taking care of it
408 conn.request(
409 'POST', '/', self._make_body(), {'Transfer-Encoding': 'chunked'})
410
411 _, headers, body = self._parse_request(conn.sock.data)
412 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
413 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
414 self.assertEqual(body, self.expected_body)
415
416 # explicit chunked, string body
417 conn = client.HTTPConnection('example.com')
418 conn.sock = FakeSocket(b'')
419 conn.request(
420 'POST', '/', self.expected_body.decode('latin-1'),
421 {'Transfer-Encoding': 'chunked'})
422
423 _, headers, body = self._parse_request(conn.sock.data)
424 self.assertNotIn('content-length', [k.lower() for k in headers.keys()])
425 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
426 self.assertEqual(body, self.expected_body)
427
428 # User-specified TE, but request() does the chunk encoding
429 conn = client.HTTPConnection('example.com')
430 conn.sock = FakeSocket(b'')
431 conn.request('POST', '/',
432 headers={'Transfer-Encoding': 'gzip, chunked'},
433 encode_chunked=True,
434 body=self._make_body())
435 _, headers, body = self._parse_request(conn.sock.data)
436 self.assertNotIn('content-length', [k.lower() for k in headers])
437 self.assertEqual(headers['Transfer-Encoding'], 'gzip, chunked')
438 self.assertEqual(self._parse_chunked(body), self.expected_body)
439
440 def test_request(self):
441 for empty_lines in (False, True,):
442 conn = client.HTTPConnection('example.com')
443 conn.sock = FakeSocket(b'')
444 conn.request(
445 'POST', '/', self._make_body(empty_lines=empty_lines))
446
447 _, headers, body = self._parse_request(conn.sock.data)
448 body = self._parse_chunked(body)
449 self.assertEqual(body, self.expected_body)
450 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
451
452 # Content-Length and Transfer-Encoding SHOULD not be sent in the
453 # same request
454 self.assertNotIn('content-length', [k.lower() for k in headers])
455
Martin Panteref91bb22016-08-27 01:39:26 +0000456 def test_empty_body(self):
457 # Zero-length iterable should be treated like any other iterable
458 conn = client.HTTPConnection('example.com')
459 conn.sock = FakeSocket(b'')
460 conn.request('POST', '/', ())
461 _, headers, body = self._parse_request(conn.sock.data)
462 self.assertEqual(headers['Transfer-Encoding'], 'chunked')
463 self.assertNotIn('content-length', [k.lower() for k in headers])
464 self.assertEqual(body, b"0\r\n\r\n")
465
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000466 def _make_body(self, empty_lines=False):
467 lines = self.expected_body.split(b' ')
468 for idx, line in enumerate(lines):
469 # for testing handling empty lines
470 if empty_lines and idx % 2:
471 yield b''
472 if idx < len(lines) - 1:
473 yield line + b' '
474 else:
475 yield line
476
477 def _parse_request(self, data):
478 lines = data.split(b'\r\n')
479 request = lines[0]
480 headers = {}
481 n = 1
482 while n < len(lines) and len(lines[n]) > 0:
483 key, val = lines[n].split(b':')
484 key = key.decode('latin-1').strip()
485 headers[key] = val.decode('latin-1').strip()
486 n += 1
487
488 return request, headers, b'\r\n'.join(lines[n + 1:])
489
490 def _parse_chunked(self, data):
491 body = []
492 trailers = {}
493 n = 0
494 lines = data.split(b'\r\n')
495 # parse body
496 while True:
497 size, chunk = lines[n:n+2]
498 size = int(size, 16)
499
500 if size == 0:
501 n += 1
502 break
503
504 self.assertEqual(size, len(chunk))
505 body.append(chunk)
506
507 n += 2
508 # we /should/ hit the end chunk, but check against the size of
509 # lines so we're not stuck in an infinite loop should we get
510 # malformed data
511 if n > len(lines):
512 break
513
514 return b''.join(body)
515
516
Thomas Wouters89f507f2006-12-13 04:49:30 +0000517class BasicTest(TestCase):
518 def test_status_lines(self):
519 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000520
Thomas Wouters89f507f2006-12-13 04:49:30 +0000521 body = "HTTP/1.1 200 Ok\r\n\r\nText"
522 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000523 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000524 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200525 self.assertEqual(resp.read(0), b'') # Issue #20007
526 self.assertFalse(resp.isclosed())
527 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000528 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000529 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200530 self.assertFalse(resp.closed)
531 resp.close()
532 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000533
Thomas Wouters89f507f2006-12-13 04:49:30 +0000534 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
535 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000536 resp = client.HTTPResponse(sock)
537 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000538
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000539 def test_bad_status_repr(self):
540 exc = client.BadStatusLine('')
Serhiy Storchakaf8a4c032017-11-15 17:53:28 +0200541 self.assertEqual(repr(exc), '''BadStatusLine("''")''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000542
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000543 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000544 # if we have Content-Length, HTTPResponse knows when to close itself,
545 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000546 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
547 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000548 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000549 resp.begin()
550 self.assertEqual(resp.read(2), b'Te')
551 self.assertFalse(resp.isclosed())
552 self.assertEqual(resp.read(2), b'xt')
553 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200554 self.assertFalse(resp.closed)
555 resp.close()
556 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000557
Martin Panterce911c32016-03-17 06:42:48 +0000558 def test_mixed_reads(self):
559 # readline() should update the remaining length, so that read() knows
560 # how much data is left and does not raise IncompleteRead
561 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
562 sock = FakeSocket(body)
563 resp = client.HTTPResponse(sock)
564 resp.begin()
565 self.assertEqual(resp.readline(), b'Text\r\n')
566 self.assertFalse(resp.isclosed())
567 self.assertEqual(resp.read(), b'Another')
568 self.assertTrue(resp.isclosed())
569 self.assertFalse(resp.closed)
570 resp.close()
571 self.assertTrue(resp.closed)
572
Antoine Pitrou38d96432011-12-06 22:33:57 +0100573 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000574 # if we have Content-Length, HTTPResponse knows when to close itself,
575 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100576 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
577 sock = FakeSocket(body)
578 resp = client.HTTPResponse(sock)
579 resp.begin()
580 b = bytearray(2)
581 n = resp.readinto(b)
582 self.assertEqual(n, 2)
583 self.assertEqual(bytes(b), b'Te')
584 self.assertFalse(resp.isclosed())
585 n = resp.readinto(b)
586 self.assertEqual(n, 2)
587 self.assertEqual(bytes(b), b'xt')
588 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200589 self.assertFalse(resp.closed)
590 resp.close()
591 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100592
Antoine Pitrou084daa22012-12-15 19:11:54 +0100593 def test_partial_reads_no_content_length(self):
594 # when no length is present, the socket should be gracefully closed when
595 # all data was read
596 body = "HTTP/1.1 200 Ok\r\n\r\nText"
597 sock = FakeSocket(body)
598 resp = client.HTTPResponse(sock)
599 resp.begin()
600 self.assertEqual(resp.read(2), b'Te')
601 self.assertFalse(resp.isclosed())
602 self.assertEqual(resp.read(2), b'xt')
603 self.assertEqual(resp.read(1), b'')
604 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200605 self.assertFalse(resp.closed)
606 resp.close()
607 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100608
Antoine Pitroud20e7742012-12-15 19:22:30 +0100609 def test_partial_readintos_no_content_length(self):
610 # when no length is present, the socket should be gracefully closed when
611 # all data was read
612 body = "HTTP/1.1 200 Ok\r\n\r\nText"
613 sock = FakeSocket(body)
614 resp = client.HTTPResponse(sock)
615 resp.begin()
616 b = bytearray(2)
617 n = resp.readinto(b)
618 self.assertEqual(n, 2)
619 self.assertEqual(bytes(b), b'Te')
620 self.assertFalse(resp.isclosed())
621 n = resp.readinto(b)
622 self.assertEqual(n, 2)
623 self.assertEqual(bytes(b), b'xt')
624 n = resp.readinto(b)
625 self.assertEqual(n, 0)
626 self.assertTrue(resp.isclosed())
627
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100628 def test_partial_reads_incomplete_body(self):
629 # if the server shuts down the connection before the whole
630 # content-length is delivered, the socket is gracefully closed
631 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
632 sock = FakeSocket(body)
633 resp = client.HTTPResponse(sock)
634 resp.begin()
635 self.assertEqual(resp.read(2), b'Te')
636 self.assertFalse(resp.isclosed())
637 self.assertEqual(resp.read(2), b'xt')
638 self.assertEqual(resp.read(1), b'')
639 self.assertTrue(resp.isclosed())
640
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100641 def test_partial_readintos_incomplete_body(self):
642 # if the server shuts down the connection before the whole
643 # content-length is delivered, the socket is gracefully closed
644 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
645 sock = FakeSocket(body)
646 resp = client.HTTPResponse(sock)
647 resp.begin()
648 b = bytearray(2)
649 n = resp.readinto(b)
650 self.assertEqual(n, 2)
651 self.assertEqual(bytes(b), b'Te')
652 self.assertFalse(resp.isclosed())
653 n = resp.readinto(b)
654 self.assertEqual(n, 2)
655 self.assertEqual(bytes(b), b'xt')
656 n = resp.readinto(b)
657 self.assertEqual(n, 0)
658 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200659 self.assertFalse(resp.closed)
660 resp.close()
661 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100662
Thomas Wouters89f507f2006-12-13 04:49:30 +0000663 def test_host_port(self):
664 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000665
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200666 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000667 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000668
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000669 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
670 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000671 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200672 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000673 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200674 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
675 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000676 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000677 self.assertEqual(h, c.host)
678 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000679
Thomas Wouters89f507f2006-12-13 04:49:30 +0000680 def test_response_headers(self):
681 # test response with multiple message headers with the same field name.
682 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000683 'Set-Cookie: Customer="WILE_E_COYOTE"; '
684 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000685 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
686 ' Path="/acme"\r\n'
687 '\r\n'
688 'No body\r\n')
689 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
690 ', '
691 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
692 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000693 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000694 r.begin()
695 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000696 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000697
Thomas Wouters89f507f2006-12-13 04:49:30 +0000698 def test_read_head(self):
699 # Test that the library doesn't attempt to read any data
700 # from a HEAD request. (Tickles SF bug #622042.)
701 sock = FakeSocket(
702 'HTTP/1.1 200 OK\r\n'
703 'Content-Length: 14432\r\n'
704 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300705 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000706 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000707 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000708 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000710
Antoine Pitrou38d96432011-12-06 22:33:57 +0100711 def test_readinto_head(self):
712 # Test that the library doesn't attempt to read any data
713 # from a HEAD request. (Tickles SF bug #622042.)
714 sock = FakeSocket(
715 'HTTP/1.1 200 OK\r\n'
716 'Content-Length: 14432\r\n'
717 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300718 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100719 resp = client.HTTPResponse(sock, method="HEAD")
720 resp.begin()
721 b = bytearray(5)
722 if resp.readinto(b) != 0:
723 self.fail("Did not expect response from HEAD request")
724 self.assertEqual(bytes(b), b'\x00'*5)
725
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100726 def test_too_many_headers(self):
727 headers = '\r\n'.join('Header%d: foo' % i
728 for i in range(client._MAXHEADERS + 1)) + '\r\n'
729 text = ('HTTP/1.1 200 OK\r\n' + headers)
730 s = FakeSocket(text)
731 r = client.HTTPResponse(s)
732 self.assertRaisesRegex(client.HTTPException,
733 r"got more than \d+ headers", r.begin)
734
Thomas Wouters89f507f2006-12-13 04:49:30 +0000735 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000736 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
Martin Panteref91bb22016-08-27 01:39:26 +0000737 b'Accept-Encoding: identity\r\n'
738 b'Transfer-Encoding: chunked\r\n'
739 b'\r\n')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000740
Brett Cannon77b7de62010-10-29 23:31:11 +0000741 with open(__file__, 'rb') as body:
742 conn = client.HTTPConnection('example.com')
743 sock = FakeSocket(body)
744 conn.sock = sock
745 conn.request('GET', '/foo', body)
746 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
747 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000748
Antoine Pitrouead1d622009-09-29 18:44:53 +0000749 def test_send(self):
750 expected = b'this is a test this is only a test'
751 conn = client.HTTPConnection('example.com')
752 sock = FakeSocket(None)
753 conn.sock = sock
754 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000755 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000756 sock.data = b''
757 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000758 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000759 sock.data = b''
760 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000761 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000762
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300763 def test_send_updating_file(self):
764 def data():
765 yield 'data'
766 yield None
767 yield 'data_two'
768
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000769 class UpdatingFile(io.TextIOBase):
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300770 mode = 'r'
771 d = data()
772 def read(self, blocksize=-1):
Martin Panter3c0d0ba2016-08-24 06:33:33 +0000773 return next(self.d)
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300774
775 expected = b'data'
776
777 conn = client.HTTPConnection('example.com')
778 sock = FakeSocket("")
779 conn.sock = sock
780 conn.send(UpdatingFile())
781 self.assertEqual(sock.data, expected)
782
783
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000784 def test_send_iter(self):
785 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
786 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
787 b'\r\nonetwothree'
788
789 def body():
790 yield b"one"
791 yield b"two"
792 yield b"three"
793
794 conn = client.HTTPConnection('example.com')
795 sock = FakeSocket("")
796 conn.sock = sock
797 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000798 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000799
Nir Sofferad455cd2017-11-06 23:16:37 +0200800 def test_blocksize_request(self):
801 """Check that request() respects the configured block size."""
802 blocksize = 8 # For easy debugging.
803 conn = client.HTTPConnection('example.com', blocksize=blocksize)
804 sock = FakeSocket(None)
805 conn.sock = sock
806 expected = b"a" * blocksize + b"b"
807 conn.request("PUT", "/", io.BytesIO(expected), {"Content-Length": "9"})
808 self.assertEqual(sock.sendall_calls, 3)
809 body = sock.data.split(b"\r\n\r\n", 1)[1]
810 self.assertEqual(body, expected)
811
812 def test_blocksize_send(self):
813 """Check that send() respects the configured block size."""
814 blocksize = 8 # For easy debugging.
815 conn = client.HTTPConnection('example.com', blocksize=blocksize)
816 sock = FakeSocket(None)
817 conn.sock = sock
818 expected = b"a" * blocksize + b"b"
819 conn.send(io.BytesIO(expected))
820 self.assertEqual(sock.sendall_calls, 2)
821 self.assertEqual(sock.data, expected)
822
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800823 def test_send_type_error(self):
824 # See: Issue #12676
825 conn = client.HTTPConnection('example.com')
826 conn.sock = FakeSocket('')
827 with self.assertRaises(TypeError):
828 conn.request('POST', 'test', conn)
829
Christian Heimesa612dc02008-02-24 13:08:18 +0000830 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000831 expected = chunked_expected
832 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000833 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000834 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100835 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000836 resp.close()
837
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100838 # Various read sizes
839 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000840 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100841 resp = client.HTTPResponse(sock, method="GET")
842 resp.begin()
843 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
844 resp.close()
845
Christian Heimesa612dc02008-02-24 13:08:18 +0000846 for x in ('', 'foo\r\n'):
847 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000848 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000849 resp.begin()
850 try:
851 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000852 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100853 self.assertEqual(i.partial, expected)
854 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
855 self.assertEqual(repr(i), expected_message)
856 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000857 else:
858 self.fail('IncompleteRead expected')
859 finally:
860 resp.close()
861
Antoine Pitrou38d96432011-12-06 22:33:57 +0100862 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000863
864 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100865 nexpected = len(expected)
866 b = bytearray(128)
867
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000868 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100869 resp = client.HTTPResponse(sock, method="GET")
870 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100871 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100872 self.assertEqual(b[:nexpected], expected)
873 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100874 resp.close()
875
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100876 # Various read sizes
877 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000878 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100879 resp = client.HTTPResponse(sock, method="GET")
880 resp.begin()
881 m = memoryview(b)
882 i = resp.readinto(m[0:n])
883 i += resp.readinto(m[i:n + i])
884 i += resp.readinto(m[i:])
885 self.assertEqual(b[:nexpected], expected)
886 self.assertEqual(i, nexpected)
887 resp.close()
888
Antoine Pitrou38d96432011-12-06 22:33:57 +0100889 for x in ('', 'foo\r\n'):
890 sock = FakeSocket(chunked_start + x)
891 resp = client.HTTPResponse(sock, method="GET")
892 resp.begin()
893 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100894 n = resp.readinto(b)
895 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100896 self.assertEqual(i.partial, expected)
897 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
898 self.assertEqual(repr(i), expected_message)
899 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100900 else:
901 self.fail('IncompleteRead expected')
902 finally:
903 resp.close()
904
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000905 def test_chunked_head(self):
906 chunked_start = (
907 'HTTP/1.1 200 OK\r\n'
908 'Transfer-Encoding: chunked\r\n\r\n'
909 'a\r\n'
910 'hello world\r\n'
911 '1\r\n'
912 'd\r\n'
913 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000914 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000915 resp = client.HTTPResponse(sock, method="HEAD")
916 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000917 self.assertEqual(resp.read(), b'')
918 self.assertEqual(resp.status, 200)
919 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000920 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200921 self.assertFalse(resp.closed)
922 resp.close()
923 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000924
Antoine Pitrou38d96432011-12-06 22:33:57 +0100925 def test_readinto_chunked_head(self):
926 chunked_start = (
927 'HTTP/1.1 200 OK\r\n'
928 'Transfer-Encoding: chunked\r\n\r\n'
929 'a\r\n'
930 'hello world\r\n'
931 '1\r\n'
932 'd\r\n'
933 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000934 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100935 resp = client.HTTPResponse(sock, method="HEAD")
936 resp.begin()
937 b = bytearray(5)
938 n = resp.readinto(b)
939 self.assertEqual(n, 0)
940 self.assertEqual(bytes(b), b'\x00'*5)
941 self.assertEqual(resp.status, 200)
942 self.assertEqual(resp.reason, 'OK')
943 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200944 self.assertFalse(resp.closed)
945 resp.close()
946 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100947
Christian Heimesa612dc02008-02-24 13:08:18 +0000948 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000949 sock = FakeSocket(
950 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000951 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000952 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000953 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100954 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000955
Benjamin Peterson6accb982009-03-02 22:50:25 +0000956 def test_incomplete_read(self):
957 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000958 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000959 resp.begin()
960 try:
961 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000962 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000963 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000964 self.assertEqual(repr(i),
965 "IncompleteRead(7 bytes read, 3 more expected)")
966 self.assertEqual(str(i),
967 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100968 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000969 else:
970 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000971
Jeremy Hylton636950f2009-03-28 04:34:21 +0000972 def test_epipe(self):
973 sock = EPipeSocket(
974 "HTTP/1.0 401 Authorization Required\r\n"
975 "Content-type: text/html\r\n"
976 "WWW-Authenticate: Basic realm=\"example\"\r\n",
977 b"Content-Length")
978 conn = client.HTTPConnection("example.com")
979 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200980 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000981 lambda: conn.request("PUT", "/url", "body"))
982 resp = conn.getresponse()
983 self.assertEqual(401, resp.status)
984 self.assertEqual("Basic realm=\"example\"",
985 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000986
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000987 # Test lines overflowing the max line size (_MAXLINE in http.client)
988
989 def test_overflowing_status_line(self):
990 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
991 resp = client.HTTPResponse(FakeSocket(body))
992 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
993
994 def test_overflowing_header_line(self):
995 body = (
996 'HTTP/1.1 200 OK\r\n'
997 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
998 )
999 resp = client.HTTPResponse(FakeSocket(body))
1000 self.assertRaises(client.LineTooLong, resp.begin)
1001
1002 def test_overflowing_chunked_line(self):
1003 body = (
1004 'HTTP/1.1 200 OK\r\n'
1005 'Transfer-Encoding: chunked\r\n\r\n'
1006 + '0' * 65536 + 'a\r\n'
1007 'hello world\r\n'
1008 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001009 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +00001010 )
1011 resp = client.HTTPResponse(FakeSocket(body))
1012 resp.begin()
1013 self.assertRaises(client.LineTooLong, resp.read)
1014
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001015 def test_early_eof(self):
1016 # Test httpresponse with no \r\n termination,
1017 body = "HTTP/1.1 200 Ok"
1018 sock = FakeSocket(body)
1019 resp = client.HTTPResponse(sock)
1020 resp.begin()
1021 self.assertEqual(resp.read(), b'')
1022 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +02001023 self.assertFalse(resp.closed)
1024 resp.close()
1025 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +08001026
Serhiy Storchakab491e052014-12-01 13:07:45 +02001027 def test_error_leak(self):
1028 # Test that the socket is not leaked if getresponse() fails
1029 conn = client.HTTPConnection('example.com')
1030 response = None
1031 class Response(client.HTTPResponse):
1032 def __init__(self, *pos, **kw):
1033 nonlocal response
1034 response = self # Avoid garbage collector closing the socket
1035 client.HTTPResponse.__init__(self, *pos, **kw)
1036 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -04001037 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +02001038 conn.request('GET', '/')
1039 self.assertRaises(client.BadStatusLine, conn.getresponse)
1040 self.assertTrue(response.closed)
1041 self.assertTrue(conn.sock.file_closed)
1042
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001043 def test_chunked_extension(self):
1044 extra = '3;foo=bar\r\n' + 'abc\r\n'
1045 expected = chunked_expected + b'abc'
1046
1047 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
1048 resp = client.HTTPResponse(sock, method="GET")
1049 resp.begin()
1050 self.assertEqual(resp.read(), expected)
1051 resp.close()
1052
1053 def test_chunked_missing_end(self):
1054 """some servers may serve up a short chunked encoding stream"""
1055 expected = chunked_expected
1056 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
1057 resp = client.HTTPResponse(sock, method="GET")
1058 resp.begin()
1059 self.assertEqual(resp.read(), expected)
1060 resp.close()
1061
1062 def test_chunked_trailers(self):
1063 """See that trailers are read and ignored"""
1064 expected = chunked_expected
1065 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
1066 resp = client.HTTPResponse(sock, method="GET")
1067 resp.begin()
1068 self.assertEqual(resp.read(), expected)
1069 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +00001070 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001071 resp.close()
1072
1073 def test_chunked_sync(self):
1074 """Check that we don't read past the end of the chunked-encoding stream"""
1075 expected = chunked_expected
1076 extradata = "extradata"
1077 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
1078 resp = client.HTTPResponse(sock, method="GET")
1079 resp.begin()
1080 self.assertEqual(resp.read(), expected)
1081 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001082 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001083 resp.close()
1084
1085 def test_content_length_sync(self):
1086 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +00001087 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001088 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +00001089 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 +00001090 resp = client.HTTPResponse(sock, method="GET")
1091 resp.begin()
1092 self.assertEqual(resp.read(), expected)
1093 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +00001094 self.assertEqual(sock.file.read(), extradata) #we read to the end
1095 resp.close()
1096
1097 def test_readlines_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.readlines(2000), [expected])
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_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: 10\r\n\r\n' + expected + extradata)
1112 resp = client.HTTPResponse(sock, method="GET")
1113 resp.begin()
1114 self.assertEqual(resp.read1(2000), expected)
1115 # the file should now have our extradata ready to be read
1116 self.assertEqual(sock.file.read(), extradata) #we read to the end
1117 resp.close()
1118
1119 def test_readline_bound_content_length(self):
1120 extradata = b"extradata"
1121 expected = b"Hello123\r\n"
1122 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
1123 resp = client.HTTPResponse(sock, method="GET")
1124 resp.begin()
1125 self.assertEqual(resp.readline(10), expected)
1126 self.assertEqual(resp.readline(10), b"")
1127 # the file should now have our extradata ready to be read
1128 self.assertEqual(sock.file.read(), extradata) #we read to the end
1129 resp.close()
1130
1131 def test_read1_bound_content_length(self):
1132 extradata = b"extradata"
1133 expected = b"Hello123\r\n"
1134 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
1135 resp = client.HTTPResponse(sock, method="GET")
1136 resp.begin()
1137 self.assertEqual(resp.read1(20), expected*2)
1138 self.assertEqual(resp.read(), expected)
1139 # the file should now have our extradata ready to be read
1140 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001141 resp.close()
1142
Martin Panterd979b2c2016-04-09 14:03:17 +00001143 def test_response_fileno(self):
1144 # Make sure fd returned by fileno is valid.
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +02001145 serv = socket.create_server((HOST, 0))
Martin Panterd979b2c2016-04-09 14:03:17 +00001146 self.addCleanup(serv.close)
Martin Panterd979b2c2016-04-09 14:03:17 +00001147
1148 result = None
1149 def run_server():
1150 [conn, address] = serv.accept()
1151 with conn, conn.makefile("rb") as reader:
1152 # Read the request header until a blank line
1153 while True:
1154 line = reader.readline()
1155 if not line.rstrip(b"\r\n"):
1156 break
1157 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
1158 nonlocal result
1159 result = reader.read()
1160
1161 thread = threading.Thread(target=run_server)
1162 thread.start()
Martin Panter1fa69152016-08-23 09:01:43 +00001163 self.addCleanup(thread.join, float(1))
Martin Panterd979b2c2016-04-09 14:03:17 +00001164 conn = client.HTTPConnection(*serv.getsockname())
1165 conn.request("CONNECT", "dummy:1234")
1166 response = conn.getresponse()
1167 try:
1168 self.assertEqual(response.status, client.OK)
1169 s = socket.socket(fileno=response.fileno())
1170 try:
1171 s.sendall(b"proxied data\n")
1172 finally:
1173 s.detach()
1174 finally:
1175 response.close()
1176 conn.close()
Martin Panter1fa69152016-08-23 09:01:43 +00001177 thread.join()
Martin Panterd979b2c2016-04-09 14:03:17 +00001178 self.assertEqual(result, b"proxied data\n")
1179
Miss Islington (bot)ff69c9d2020-03-14 12:13:32 -07001180 def test_putrequest_override_domain_validation(self):
Miss Islington (bot)8f478b42019-09-28 07:23:34 -07001181 """
1182 It should be possible to override the default validation
1183 behavior in putrequest (bpo-38216).
1184 """
1185 class UnsafeHTTPConnection(client.HTTPConnection):
1186 def _validate_path(self, url):
1187 pass
1188
1189 conn = UnsafeHTTPConnection('example.com')
1190 conn.sock = FakeSocket('')
1191 conn.putrequest('GET', '/\x00')
1192
Miss Islington (bot)ff69c9d2020-03-14 12:13:32 -07001193 def test_putrequest_override_host_validation(self):
1194 class UnsafeHTTPConnection(client.HTTPConnection):
1195 def _validate_host(self, url):
1196 pass
1197
1198 conn = UnsafeHTTPConnection('example.com\r\n')
1199 conn.sock = FakeSocket('')
1200 # set skip_host so a ValueError is not raised upon adding the
1201 # invalid URL as the value of the "Host:" header
1202 conn.putrequest('GET', '/', skip_host=1)
1203
Miss Islington (bot)8f478b42019-09-28 07:23:34 -07001204 def test_putrequest_override_encoding(self):
1205 """
1206 It should be possible to override the default encoding
1207 to transmit bytes in another encoding even if invalid
1208 (bpo-36274).
1209 """
1210 class UnsafeHTTPConnection(client.HTTPConnection):
1211 def _encode_request(self, str_url):
1212 return str_url.encode('utf-8')
1213
1214 conn = UnsafeHTTPConnection('example.com')
1215 conn.sock = FakeSocket('')
1216 conn.putrequest('GET', '/☃')
1217
1218
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001219class ExtendedReadTest(TestCase):
1220 """
1221 Test peek(), read1(), readline()
1222 """
1223 lines = (
1224 'HTTP/1.1 200 OK\r\n'
1225 '\r\n'
1226 'hello world!\n'
1227 'and now \n'
1228 'for something completely different\n'
1229 'foo'
1230 )
1231 lines_expected = lines[lines.find('hello'):].encode("ascii")
1232 lines_chunked = (
1233 'HTTP/1.1 200 OK\r\n'
1234 'Transfer-Encoding: chunked\r\n\r\n'
1235 'a\r\n'
1236 'hello worl\r\n'
1237 '3\r\n'
1238 'd!\n\r\n'
1239 '9\r\n'
1240 'and now \n\r\n'
1241 '23\r\n'
1242 'for something completely different\n\r\n'
1243 '3\r\n'
1244 'foo\r\n'
1245 '0\r\n' # terminating chunk
1246 '\r\n' # end of trailers
1247 )
1248
1249 def setUp(self):
1250 sock = FakeSocket(self.lines)
1251 resp = client.HTTPResponse(sock, method="GET")
1252 resp.begin()
1253 resp.fp = io.BufferedReader(resp.fp)
1254 self.resp = resp
1255
1256
1257
1258 def test_peek(self):
1259 resp = self.resp
1260 # patch up the buffered peek so that it returns not too much stuff
1261 oldpeek = resp.fp.peek
1262 def mypeek(n=-1):
1263 p = oldpeek(n)
1264 if n >= 0:
1265 return p[:n]
1266 return p[:10]
1267 resp.fp.peek = mypeek
1268
1269 all = []
1270 while True:
1271 # try a short peek
1272 p = resp.peek(3)
1273 if p:
1274 self.assertGreater(len(p), 0)
1275 # then unbounded peek
1276 p2 = resp.peek()
1277 self.assertGreaterEqual(len(p2), len(p))
1278 self.assertTrue(p2.startswith(p))
1279 next = resp.read(len(p2))
1280 self.assertEqual(next, p2)
1281 else:
1282 next = resp.read()
1283 self.assertFalse(next)
1284 all.append(next)
1285 if not next:
1286 break
1287 self.assertEqual(b"".join(all), self.lines_expected)
1288
1289 def test_readline(self):
1290 resp = self.resp
1291 self._verify_readline(self.resp.readline, self.lines_expected)
1292
1293 def _verify_readline(self, readline, expected):
1294 all = []
1295 while True:
1296 # short readlines
1297 line = readline(5)
1298 if line and line != b"foo":
1299 if len(line) < 5:
1300 self.assertTrue(line.endswith(b"\n"))
1301 all.append(line)
1302 if not line:
1303 break
1304 self.assertEqual(b"".join(all), expected)
1305
1306 def test_read1(self):
1307 resp = self.resp
1308 def r():
1309 res = resp.read1(4)
1310 self.assertLessEqual(len(res), 4)
1311 return res
1312 readliner = Readliner(r)
1313 self._verify_readline(readliner.readline, self.lines_expected)
1314
1315 def test_read1_unbounded(self):
1316 resp = self.resp
1317 all = []
1318 while True:
1319 data = resp.read1()
1320 if not data:
1321 break
1322 all.append(data)
1323 self.assertEqual(b"".join(all), self.lines_expected)
1324
1325 def test_read1_bounded(self):
1326 resp = self.resp
1327 all = []
1328 while True:
1329 data = resp.read1(10)
1330 if not data:
1331 break
1332 self.assertLessEqual(len(data), 10)
1333 all.append(data)
1334 self.assertEqual(b"".join(all), self.lines_expected)
1335
1336 def test_read1_0(self):
1337 self.assertEqual(self.resp.read1(0), b"")
1338
1339 def test_peek_0(self):
1340 p = self.resp.peek(0)
1341 self.assertLessEqual(0, len(p))
1342
Miss Islington (bot)8f478b42019-09-28 07:23:34 -07001343
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001344class ExtendedReadTestChunked(ExtendedReadTest):
1345 """
1346 Test peek(), read1(), readline() in chunked mode
1347 """
1348 lines = (
1349 'HTTP/1.1 200 OK\r\n'
1350 'Transfer-Encoding: chunked\r\n\r\n'
1351 'a\r\n'
1352 'hello worl\r\n'
1353 '3\r\n'
1354 'd!\n\r\n'
1355 '9\r\n'
1356 'and now \n\r\n'
1357 '23\r\n'
1358 'for something completely different\n\r\n'
1359 '3\r\n'
1360 'foo\r\n'
1361 '0\r\n' # terminating chunk
1362 '\r\n' # end of trailers
1363 )
1364
1365
1366class Readliner:
1367 """
1368 a simple readline class that uses an arbitrary read function and buffering
1369 """
1370 def __init__(self, readfunc):
1371 self.readfunc = readfunc
1372 self.remainder = b""
1373
1374 def readline(self, limit):
1375 data = []
1376 datalen = 0
1377 read = self.remainder
1378 try:
1379 while True:
1380 idx = read.find(b'\n')
1381 if idx != -1:
1382 break
1383 if datalen + len(read) >= limit:
1384 idx = limit - datalen - 1
1385 # read more data
1386 data.append(read)
1387 read = self.readfunc()
1388 if not read:
1389 idx = 0 #eof condition
1390 break
1391 idx += 1
1392 data.append(read[:idx])
1393 self.remainder = read[idx:]
1394 return b"".join(data)
1395 except:
1396 self.remainder = b"".join(data)
1397 raise
1398
Berker Peksagbabc6882015-02-20 09:39:38 +02001399
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001400class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001401 def test_all(self):
1402 # Documented objects defined in the module should be in __all__
1403 expected = {"responses"} # White-list documented dict() object
1404 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1405 # intentionally omitted for simplicity
1406 blacklist = {"HTTPMessage", "parse_headers"}
1407 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001408 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001409 continue
1410 module_object = getattr(client, name)
1411 if getattr(module_object, "__module__", None) == "http.client":
1412 expected.add(name)
1413 self.assertCountEqual(client.__all__, expected)
1414
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001415 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001416 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001417
Berker Peksagabbf0f42015-02-20 14:57:31 +02001418 def test_client_constants(self):
1419 # Make sure we don't break backward compatibility with 3.4
1420 expected = [
1421 'CONTINUE',
1422 'SWITCHING_PROTOCOLS',
1423 'PROCESSING',
1424 'OK',
1425 'CREATED',
1426 'ACCEPTED',
1427 'NON_AUTHORITATIVE_INFORMATION',
1428 'NO_CONTENT',
1429 'RESET_CONTENT',
1430 'PARTIAL_CONTENT',
1431 'MULTI_STATUS',
1432 'IM_USED',
1433 'MULTIPLE_CHOICES',
1434 'MOVED_PERMANENTLY',
1435 'FOUND',
1436 'SEE_OTHER',
1437 'NOT_MODIFIED',
1438 'USE_PROXY',
1439 'TEMPORARY_REDIRECT',
1440 'BAD_REQUEST',
1441 'UNAUTHORIZED',
1442 'PAYMENT_REQUIRED',
1443 'FORBIDDEN',
1444 'NOT_FOUND',
1445 'METHOD_NOT_ALLOWED',
1446 'NOT_ACCEPTABLE',
1447 'PROXY_AUTHENTICATION_REQUIRED',
1448 'REQUEST_TIMEOUT',
1449 'CONFLICT',
1450 'GONE',
1451 'LENGTH_REQUIRED',
1452 'PRECONDITION_FAILED',
1453 'REQUEST_ENTITY_TOO_LARGE',
1454 'REQUEST_URI_TOO_LONG',
1455 'UNSUPPORTED_MEDIA_TYPE',
1456 'REQUESTED_RANGE_NOT_SATISFIABLE',
1457 'EXPECTATION_FAILED',
Vitor Pereira52ad72d2017-10-26 19:49:19 +01001458 'MISDIRECTED_REQUEST',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001459 'UNPROCESSABLE_ENTITY',
1460 'LOCKED',
1461 'FAILED_DEPENDENCY',
1462 'UPGRADE_REQUIRED',
1463 'PRECONDITION_REQUIRED',
1464 'TOO_MANY_REQUESTS',
1465 'REQUEST_HEADER_FIELDS_TOO_LARGE',
Miss Islington (bot)761e5a72019-08-23 10:56:44 -07001466 'UNAVAILABLE_FOR_LEGAL_REASONS',
Berker Peksagabbf0f42015-02-20 14:57:31 +02001467 'INTERNAL_SERVER_ERROR',
1468 'NOT_IMPLEMENTED',
1469 'BAD_GATEWAY',
1470 'SERVICE_UNAVAILABLE',
1471 'GATEWAY_TIMEOUT',
1472 'HTTP_VERSION_NOT_SUPPORTED',
1473 'INSUFFICIENT_STORAGE',
1474 'NOT_EXTENDED',
1475 'NETWORK_AUTHENTICATION_REQUIRED',
1476 ]
1477 for const in expected:
1478 with self.subTest(constant=const):
1479 self.assertTrue(hasattr(client, const))
1480
Gregory P. Smithb4066372010-01-03 03:28:29 +00001481
1482class SourceAddressTest(TestCase):
1483 def setUp(self):
1484 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1485 self.port = support.bind_port(self.serv)
1486 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001487 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001488 self.conn = None
1489
1490 def tearDown(self):
1491 if self.conn:
1492 self.conn.close()
1493 self.conn = None
1494 self.serv.close()
1495 self.serv = None
1496
1497 def testHTTPConnectionSourceAddress(self):
1498 self.conn = client.HTTPConnection(HOST, self.port,
1499 source_address=('', self.source_port))
1500 self.conn.connect()
1501 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1502
1503 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1504 'http.client.HTTPSConnection not defined')
1505 def testHTTPSConnectionSourceAddress(self):
1506 self.conn = client.HTTPSConnection(HOST, self.port,
1507 source_address=('', self.source_port))
Martin Panterd2a584b2016-10-10 00:24:34 +00001508 # We don't test anything here other than the constructor not barfing as
Gregory P. Smithb4066372010-01-03 03:28:29 +00001509 # this code doesn't deal with setting up an active running SSL server
1510 # for an ssl_wrapped connect() to actually return from.
1511
1512
Guido van Rossumd8faa362007-04-27 19:54:29 +00001513class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001514 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001515
1516 def setUp(self):
1517 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001518 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001519 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001520
1521 def tearDown(self):
1522 self.serv.close()
1523 self.serv = None
1524
1525 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001526 # This will prove that the timeout gets through HTTPConnection
1527 # and into the socket.
1528
Georg Brandlf78e02b2008-06-10 17:40:04 +00001529 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001530 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001531 socket.setdefaulttimeout(30)
1532 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001533 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001534 httpConn.connect()
1535 finally:
1536 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001537 self.assertEqual(httpConn.sock.gettimeout(), 30)
1538 httpConn.close()
1539
Georg Brandlf78e02b2008-06-10 17:40:04 +00001540 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001541 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001542 socket.setdefaulttimeout(30)
1543 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001544 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001545 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001546 httpConn.connect()
1547 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001548 socket.setdefaulttimeout(None)
1549 self.assertEqual(httpConn.sock.gettimeout(), None)
1550 httpConn.close()
1551
1552 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001553 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001554 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001555 self.assertEqual(httpConn.sock.gettimeout(), 30)
1556 httpConn.close()
1557
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001558
R David Murraycae7bdb2015-04-05 19:26:29 -04001559class PersistenceTest(TestCase):
1560
1561 def test_reuse_reconnect(self):
1562 # Should reuse or reconnect depending on header from server
1563 tests = (
1564 ('1.0', '', False),
1565 ('1.0', 'Connection: keep-alive\r\n', True),
1566 ('1.1', '', True),
1567 ('1.1', 'Connection: close\r\n', False),
1568 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1569 ('1.1', 'Connection: cloSE\r\n', False),
1570 )
1571 for version, header, reuse in tests:
1572 with self.subTest(version=version, header=header):
1573 msg = (
1574 'HTTP/{} 200 OK\r\n'
1575 '{}'
1576 'Content-Length: 12\r\n'
1577 '\r\n'
1578 'Dummy body\r\n'
1579 ).format(version, header)
1580 conn = FakeSocketHTTPConnection(msg)
1581 self.assertIsNone(conn.sock)
1582 conn.request('GET', '/open-connection')
1583 with conn.getresponse() as response:
1584 self.assertEqual(conn.sock is None, not reuse)
1585 response.read()
1586 self.assertEqual(conn.sock is None, not reuse)
1587 self.assertEqual(conn.connections, 1)
1588 conn.request('GET', '/subsequent-request')
1589 self.assertEqual(conn.connections, 1 if reuse else 2)
1590
1591 def test_disconnected(self):
1592
1593 def make_reset_reader(text):
1594 """Return BufferedReader that raises ECONNRESET at EOF"""
1595 stream = io.BytesIO(text)
1596 def readinto(buffer):
1597 size = io.BytesIO.readinto(stream, buffer)
1598 if size == 0:
1599 raise ConnectionResetError()
1600 return size
1601 stream.readinto = readinto
1602 return io.BufferedReader(stream)
1603
1604 tests = (
1605 (io.BytesIO, client.RemoteDisconnected),
1606 (make_reset_reader, ConnectionResetError),
1607 )
1608 for stream_factory, exception in tests:
1609 with self.subTest(exception=exception):
1610 conn = FakeSocketHTTPConnection(b'', stream_factory)
1611 conn.request('GET', '/eof-response')
1612 self.assertRaises(exception, conn.getresponse)
1613 self.assertIsNone(conn.sock)
1614 # HTTPConnection.connect() should be automatically invoked
1615 conn.request('GET', '/reconnect')
1616 self.assertEqual(conn.connections, 2)
1617
1618 def test_100_close(self):
1619 conn = FakeSocketHTTPConnection(
1620 b'HTTP/1.1 100 Continue\r\n'
1621 b'\r\n'
1622 # Missing final response
1623 )
1624 conn.request('GET', '/', headers={'Expect': '100-continue'})
1625 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1626 self.assertIsNone(conn.sock)
1627 conn.request('GET', '/reconnect')
1628 self.assertEqual(conn.connections, 2)
1629
1630
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001631class HTTPSTest(TestCase):
1632
1633 def setUp(self):
1634 if not hasattr(client, 'HTTPSConnection'):
1635 self.skipTest('ssl support required')
1636
1637 def make_server(self, certfile):
1638 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001639 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001640
1641 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001642 # simple test to check it's storing the timeout
1643 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1644 self.assertEqual(h.timeout, 30)
1645
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001646 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001647 # Default settings: requires a valid cert from a trusted CA
1648 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001649 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001650 with support.transient_internet('self-signed.pythontest.net'):
1651 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1652 with self.assertRaises(ssl.SSLError) as exc_info:
1653 h.request('GET', '/')
1654 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1655
1656 def test_networked_noverification(self):
1657 # Switch off cert verification
1658 import ssl
1659 support.requires('network')
1660 with support.transient_internet('self-signed.pythontest.net'):
1661 context = ssl._create_unverified_context()
1662 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1663 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001664 h.request('GET', '/')
1665 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001666 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001667 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001668 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001669
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001670 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001671 def test_networked_trusted_by_default_cert(self):
1672 # Default settings: requires a valid cert from a trusted CA
1673 support.requires('network')
1674 with support.transient_internet('www.python.org'):
1675 h = client.HTTPSConnection('www.python.org', 443)
1676 h.request('GET', '/')
1677 resp = h.getresponse()
1678 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001679 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001680 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001681 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001682
1683 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001684 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001685 import ssl
1686 support.requires('network')
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001687 selfsigned_pythontestdotnet = 'self-signed.pythontest.net'
1688 with support.transient_internet(selfsigned_pythontestdotnet):
Christian Heimesa170fa12017-09-15 20:27:30 +02001689 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1690 self.assertEqual(context.verify_mode, ssl.CERT_REQUIRED)
1691 self.assertEqual(context.check_hostname, True)
Georg Brandlfbaf9312014-11-05 20:37:40 +01001692 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
Gregory P. Smith2cc02232019-05-06 17:54:06 -04001693 try:
1694 h = client.HTTPSConnection(selfsigned_pythontestdotnet, 443,
1695 context=context)
1696 h.request('GET', '/')
1697 resp = h.getresponse()
1698 except ssl.SSLError as ssl_err:
1699 ssl_err_str = str(ssl_err)
1700 # In the error message of [SSL: CERTIFICATE_VERIFY_FAILED] on
1701 # modern Linux distros (Debian Buster, etc) default OpenSSL
1702 # configurations it'll fail saying "key too weak" until we
1703 # address https://bugs.python.org/issue36816 to use a proper
1704 # key size on self-signed.pythontest.net.
1705 if re.search(r'(?i)key.too.weak', ssl_err_str):
1706 raise unittest.SkipTest(
1707 f'Got {ssl_err_str} trying to connect '
1708 f'to {selfsigned_pythontestdotnet}. '
1709 'See https://bugs.python.org/issue36816.')
1710 raise
Georg Brandlfbaf9312014-11-05 20:37:40 +01001711 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001712 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001713 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001714 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001715
1716 def test_networked_bad_cert(self):
1717 # We feed a "CA" cert that is unrelated to the server's cert
1718 import ssl
1719 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001720 with support.transient_internet('self-signed.pythontest.net'):
Christian Heimesa170fa12017-09-15 20:27:30 +02001721 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001722 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001723 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1724 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001725 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001726 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1727
1728 def test_local_unknown_cert(self):
1729 # The custom cert isn't known to the default trust bundle
1730 import ssl
1731 server = self.make_server(CERT_localhost)
1732 h = client.HTTPSConnection('localhost', server.port)
1733 with self.assertRaises(ssl.SSLError) as exc_info:
1734 h.request('GET', '/')
1735 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001736
1737 def test_local_good_hostname(self):
1738 # The (valid) cert validates the HTTP hostname
1739 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001740 server = self.make_server(CERT_localhost)
Christian Heimesa170fa12017-09-15 20:27:30 +02001741 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001742 context.load_verify_locations(CERT_localhost)
1743 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001744 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001745 h.request('GET', '/nonexistent')
1746 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001747 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001748 self.assertEqual(resp.status, 404)
1749
1750 def test_local_bad_hostname(self):
1751 # The (valid) cert doesn't validate the HTTP hostname
1752 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001753 server = self.make_server(CERT_fakehostname)
Christian Heimesa170fa12017-09-15 20:27:30 +02001754 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001755 context.load_verify_locations(CERT_fakehostname)
1756 h = client.HTTPSConnection('localhost', server.port, context=context)
1757 with self.assertRaises(ssl.CertificateError):
1758 h.request('GET', '/')
1759 # Same with explicit check_hostname=True
Christian Heimes8d14abc2016-09-11 19:54:43 +02001760 with support.check_warnings(('', DeprecationWarning)):
1761 h = client.HTTPSConnection('localhost', server.port,
1762 context=context, check_hostname=True)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001763 with self.assertRaises(ssl.CertificateError):
1764 h.request('GET', '/')
1765 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001766 context.check_hostname = False
Christian Heimes8d14abc2016-09-11 19:54:43 +02001767 with support.check_warnings(('', DeprecationWarning)):
1768 h = client.HTTPSConnection('localhost', server.port,
1769 context=context, check_hostname=False)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001770 h.request('GET', '/nonexistent')
1771 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001772 resp.close()
1773 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001774 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001775 # The context's check_hostname setting is used if one isn't passed to
1776 # HTTPSConnection.
1777 context.check_hostname = False
1778 h = client.HTTPSConnection('localhost', server.port, context=context)
1779 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001780 resp = h.getresponse()
1781 self.assertEqual(resp.status, 404)
1782 resp.close()
1783 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001784 # Passing check_hostname to HTTPSConnection should override the
1785 # context's setting.
Christian Heimes8d14abc2016-09-11 19:54:43 +02001786 with support.check_warnings(('', DeprecationWarning)):
1787 h = client.HTTPSConnection('localhost', server.port,
1788 context=context, check_hostname=True)
Benjamin Petersona090f012014-12-07 13:18:25 -05001789 with self.assertRaises(ssl.CertificateError):
1790 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001791
Petri Lehtinene119c402011-10-26 21:29:15 +03001792 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1793 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001794 def test_host_port(self):
1795 # Check invalid host_port
1796
1797 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1798 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1799
1800 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1801 "fe80::207:e9ff:fe9b", 8000),
1802 ("www.python.org:443", "www.python.org", 443),
1803 ("www.python.org:", "www.python.org", 443),
1804 ("www.python.org", "www.python.org", 443),
1805 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1806 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1807 443)):
1808 c = client.HTTPSConnection(hp)
1809 self.assertEqual(h, c.host)
1810 self.assertEqual(p, c.port)
1811
Miss Islington (bot)ee72dda2019-07-01 00:07:44 -07001812 def test_tls13_pha(self):
1813 import ssl
1814 if not ssl.HAS_TLSv1_3:
1815 self.skipTest('TLS 1.3 support required')
1816 # just check status of PHA flag
1817 h = client.HTTPSConnection('localhost', 443)
1818 self.assertTrue(h._context.post_handshake_auth)
1819
1820 context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
1821 self.assertFalse(context.post_handshake_auth)
1822 h = client.HTTPSConnection('localhost', 443, context=context)
1823 self.assertIs(h._context, context)
1824 self.assertFalse(h._context.post_handshake_auth)
1825
Pablo Galindo162d45c2019-08-09 01:22:59 +01001826 with warnings.catch_warnings():
1827 warnings.filterwarnings('ignore', 'key_file, cert_file and check_hostname are deprecated',
1828 DeprecationWarning)
1829 h = client.HTTPSConnection('localhost', 443, context=context,
1830 cert_file=CERT_localhost)
Miss Islington (bot)ee72dda2019-07-01 00:07:44 -07001831 self.assertTrue(h._context.post_handshake_auth)
1832
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001833
Jeremy Hylton236654b2009-03-27 20:24:34 +00001834class RequestBodyTest(TestCase):
1835 """Test cases where a request includes a message body."""
1836
1837 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001838 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001839 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001840 self.conn.sock = self.sock
1841
1842 def get_headers_and_fp(self):
1843 f = io.BytesIO(self.sock.data)
1844 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001845 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001846 return message, f
1847
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001848 def test_list_body(self):
1849 # Note that no content-length is automatically calculated for
1850 # an iterable. The request will fall back to send chunked
1851 # transfer encoding.
1852 cases = (
1853 ([b'foo', b'bar'], b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1854 ((b'foo', b'bar'), b'3\r\nfoo\r\n3\r\nbar\r\n0\r\n\r\n'),
1855 )
1856 for body, expected in cases:
1857 with self.subTest(body):
1858 self.conn = client.HTTPConnection('example.com')
1859 self.conn.sock = self.sock = FakeSocket('')
1860
1861 self.conn.request('PUT', '/url', body)
1862 msg, f = self.get_headers_and_fp()
1863 self.assertNotIn('Content-Type', msg)
1864 self.assertNotIn('Content-Length', msg)
1865 self.assertEqual(msg.get('Transfer-Encoding'), 'chunked')
1866 self.assertEqual(expected, f.read())
1867
Jeremy Hylton236654b2009-03-27 20:24:34 +00001868 def test_manual_content_length(self):
1869 # Set an incorrect content-length so that we can verify that
1870 # it will not be over-ridden by the library.
1871 self.conn.request("PUT", "/url", "body",
1872 {"Content-Length": "42"})
1873 message, f = self.get_headers_and_fp()
1874 self.assertEqual("42", message.get("content-length"))
1875 self.assertEqual(4, len(f.read()))
1876
1877 def test_ascii_body(self):
1878 self.conn.request("PUT", "/url", "body")
1879 message, f = self.get_headers_and_fp()
1880 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001881 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001882 self.assertEqual("4", message.get("content-length"))
1883 self.assertEqual(b'body', f.read())
1884
1885 def test_latin1_body(self):
1886 self.conn.request("PUT", "/url", "body\xc1")
1887 message, f = self.get_headers_and_fp()
1888 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001889 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001890 self.assertEqual("5", message.get("content-length"))
1891 self.assertEqual(b'body\xc1', f.read())
1892
1893 def test_bytes_body(self):
1894 self.conn.request("PUT", "/url", b"body\xc1")
1895 message, f = self.get_headers_and_fp()
1896 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001897 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001898 self.assertEqual("5", message.get("content-length"))
1899 self.assertEqual(b'body\xc1', f.read())
1900
Martin Panteref91bb22016-08-27 01:39:26 +00001901 def test_text_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001902 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001903 with open(support.TESTFN, "w") as f:
1904 f.write("body")
1905 with open(support.TESTFN) as f:
1906 self.conn.request("PUT", "/url", f)
1907 message, f = self.get_headers_and_fp()
1908 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001909 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001910 # No content-length will be determined for files; the body
1911 # will be sent using chunked transfer encoding instead.
Martin Panter3c0d0ba2016-08-24 06:33:33 +00001912 self.assertIsNone(message.get("content-length"))
1913 self.assertEqual("chunked", message.get("transfer-encoding"))
1914 self.assertEqual(b'4\r\nbody\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001915
1916 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001917 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001918 with open(support.TESTFN, "wb") as f:
1919 f.write(b"body\xc1")
1920 with open(support.TESTFN, "rb") as f:
1921 self.conn.request("PUT", "/url", f)
1922 message, f = self.get_headers_and_fp()
1923 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001924 self.assertIsNone(message.get_charset())
Martin Panteref91bb22016-08-27 01:39:26 +00001925 self.assertEqual("chunked", message.get("Transfer-Encoding"))
1926 self.assertNotIn("Content-Length", message)
1927 self.assertEqual(b'5\r\nbody\xc1\r\n0\r\n\r\n', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001928
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001929
1930class HTTPResponseTest(TestCase):
1931
1932 def setUp(self):
1933 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1934 second-value\r\n\r\nText"
1935 sock = FakeSocket(body)
1936 self.resp = client.HTTPResponse(sock)
1937 self.resp.begin()
1938
1939 def test_getting_header(self):
1940 header = self.resp.getheader('My-Header')
1941 self.assertEqual(header, 'first-value, second-value')
1942
1943 header = self.resp.getheader('My-Header', 'some default')
1944 self.assertEqual(header, 'first-value, second-value')
1945
1946 def test_getting_nonexistent_header_with_string_default(self):
1947 header = self.resp.getheader('No-Such-Header', 'default-value')
1948 self.assertEqual(header, 'default-value')
1949
1950 def test_getting_nonexistent_header_with_iterable_default(self):
1951 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1952 self.assertEqual(header, 'default, values')
1953
1954 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1955 self.assertEqual(header, 'default, values')
1956
1957 def test_getting_nonexistent_header_without_default(self):
1958 header = self.resp.getheader('No-Such-Header')
1959 self.assertEqual(header, None)
1960
1961 def test_getting_header_defaultint(self):
1962 header = self.resp.getheader('No-Such-Header',default=42)
1963 self.assertEqual(header, 42)
1964
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001965class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001966 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001967 response_text = (
1968 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1969 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1970 'Content-Length: 42\r\n\r\n'
1971 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001972 self.host = 'proxy.com'
1973 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001974 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001975
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001976 def tearDown(self):
1977 self.conn.close()
1978
Berker Peksagab53ab02015-02-03 12:22:11 +02001979 def _create_connection(self, response_text):
1980 def create_connection(address, timeout=None, source_address=None):
1981 return FakeSocket(response_text, host=address[0], port=address[1])
1982 return create_connection
1983
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001984 def test_set_tunnel_host_port_headers(self):
1985 tunnel_host = 'destination.com'
1986 tunnel_port = 8888
1987 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1988 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1989 headers=tunnel_headers)
1990 self.conn.request('HEAD', '/', '')
1991 self.assertEqual(self.conn.sock.host, self.host)
1992 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1993 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1994 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1995 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1996
1997 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001998 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001999 self.conn.connect()
2000 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002001 'destination.com')
2002
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002003 def test_connect_with_tunnel(self):
2004 self.conn.set_tunnel('destination.com')
2005 self.conn.request('HEAD', '/', '')
2006 self.assertEqual(self.conn.sock.host, self.host)
2007 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2008 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02002009 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002010 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
2011 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002012
2013 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002014 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002015
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002016 def test_connect_put_request(self):
2017 self.conn.set_tunnel('destination.com')
2018 self.conn.request('PUT', '/', '')
2019 self.assertEqual(self.conn.sock.host, self.host)
2020 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
2021 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
2022 self.assertIn(b'Host: destination.com', self.conn.sock.data)
2023
Berker Peksagab53ab02015-02-03 12:22:11 +02002024 def test_tunnel_debuglog(self):
2025 expected_header = 'X-Dummy: 1'
2026 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
2027
2028 self.conn.set_debuglevel(1)
2029 self.conn._create_connection = self._create_connection(response_text)
2030 self.conn.set_tunnel('destination.com')
2031
2032 with support.captured_stdout() as output:
2033 self.conn.request('PUT', '/', '')
2034 lines = output.getvalue().splitlines()
2035 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08002036
Senthil Kumaran9da047b2014-04-14 13:07:56 -04002037
Thomas Wouters89f507f2006-12-13 04:49:30 +00002038if __name__ == '__main__':
Terry Jan Reedyffcb0222016-08-23 14:20:37 -04002039 unittest.main(verbosity=2)