blob: 6d2ed39ee9c6d2bc43ff58768e2627918d56b80b [file] [log] [blame]
Jeremy Hylton636950f2009-03-28 04:34:21 +00001import errno
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002from http import client
Jeremy Hylton8fff7922007-08-03 20:56:14 +00003import io
R David Murraybeed8402015-03-22 15:18:23 -04004import itertools
Antoine Pitrou803e6d62010-10-13 10:36:15 +00005import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00006import array
Guido van Rossumd8faa362007-04-27 19:54:29 +00007import socket
Jeremy Hylton121d34a2003-07-08 12:36:58 +00008
Gregory P. Smithb4066372010-01-03 03:28:29 +00009import unittest
10TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000011
Benjamin Petersonee8712c2008-05-20 21:35:26 +000012from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000013
Antoine Pitrou803e6d62010-10-13 10:36:15 +000014here = os.path.dirname(__file__)
15# Self-signed cert file for 'localhost'
16CERT_localhost = os.path.join(here, 'keycert.pem')
17# Self-signed cert file for 'fakehostname'
18CERT_fakehostname = os.path.join(here, 'keycert2.pem')
Georg Brandlfbaf9312014-11-05 20:37:40 +010019# Self-signed cert file for self-signed.pythontest.net
20CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000021
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000022# constants for testing chunked encoding
23chunked_start = (
24 'HTTP/1.1 200 OK\r\n'
25 'Transfer-Encoding: chunked\r\n\r\n'
26 'a\r\n'
27 'hello worl\r\n'
28 '3\r\n'
29 'd! \r\n'
30 '8\r\n'
31 'and now \r\n'
32 '22\r\n'
33 'for something completely different\r\n'
34)
35chunked_expected = b'hello world! and now for something completely different'
36chunk_extension = ";foo=bar"
37last_chunk = "0\r\n"
38last_chunk_extended = "0" + chunk_extension + "\r\n"
39trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
40chunked_end = "\r\n"
41
Benjamin Petersonee8712c2008-05-20 21:35:26 +000042HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000043
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000044class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040045 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000046 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000047 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000048 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000049 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000050 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010051 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020052 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040053 self.host = host
54 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000055
Jeremy Hylton2c178252004-08-07 16:28:14 +000056 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010057 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000058 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000059
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000060 def makefile(self, mode, bufsize=None):
61 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000062 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000063 # keep the file around so we can check how much was read from it
64 self.file = self.fileclass(self.text)
Serhiy Storchakab491e052014-12-01 13:07:45 +020065 self.file.close = self.file_close #nerf close ()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000066 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000067
Serhiy Storchakab491e052014-12-01 13:07:45 +020068 def file_close(self):
69 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000070
Senthil Kumaran9da047b2014-04-14 13:07:56 -040071 def close(self):
72 pass
73
Benjamin Peterson9d8a3ad2015-01-23 11:02:57 -050074 def setsockopt(self, level, optname, value):
75 pass
76
Jeremy Hylton636950f2009-03-28 04:34:21 +000077class EPipeSocket(FakeSocket):
78
79 def __init__(self, text, pipe_trigger):
80 # When sendall() is called with pipe_trigger, raise EPIPE.
81 FakeSocket.__init__(self, text)
82 self.pipe_trigger = pipe_trigger
83
84 def sendall(self, data):
85 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020086 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000087 self.data += data
88
89 def close(self):
90 pass
91
Serhiy Storchaka50254c52013-08-29 11:35:43 +030092class NoEOFBytesIO(io.BytesIO):
93 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000094
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000095 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000096 more from the underlying file than it should.
97 """
98 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000099 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000100 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000101 raise AssertionError('caller tried to read past EOF')
102 return data
103
104 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000105 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +0000106 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +0000107 raise AssertionError('caller tried to read past EOF')
108 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000109
R David Murraycae7bdb2015-04-05 19:26:29 -0400110class FakeSocketHTTPConnection(client.HTTPConnection):
111 """HTTPConnection subclass using FakeSocket; counts connect() calls"""
112
113 def __init__(self, *args):
114 self.connections = 0
115 super().__init__('example.com')
116 self.fake_socket_args = args
117 self._create_connection = self.create_connection
118
119 def connect(self):
120 """Count the number of times connect() is invoked"""
121 self.connections += 1
122 return super().connect()
123
124 def create_connection(self, *pos, **kw):
125 return FakeSocket(*self.fake_socket_args)
126
Jeremy Hylton2c178252004-08-07 16:28:14 +0000127class HeaderTests(TestCase):
128 def test_auto_headers(self):
129 # Some headers are added automatically, but should not be added by
130 # .request() if they are explicitly set.
131
Jeremy Hylton2c178252004-08-07 16:28:14 +0000132 class HeaderCountingBuffer(list):
133 def __init__(self):
134 self.count = {}
135 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000136 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000137 if len(kv) > 1:
138 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000139 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000140 self.count.setdefault(lcKey, 0)
141 self.count[lcKey] += 1
142 list.append(self, item)
143
144 for explicit_header in True, False:
145 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000146 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000147 conn.sock = FakeSocket('blahblahblah')
148 conn._buffer = HeaderCountingBuffer()
149
150 body = 'spamspamspam'
151 headers = {}
152 if explicit_header:
153 headers[header] = str(len(body))
154 conn.request('POST', '/', body, headers)
155 self.assertEqual(conn._buffer.count[header.lower()], 1)
156
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800157 def test_content_length_0(self):
158
159 class ContentLengthChecker(list):
160 def __init__(self):
161 list.__init__(self)
162 self.content_length = None
163 def append(self, item):
164 kv = item.split(b':', 1)
165 if len(kv) > 1 and kv[0].lower() == b'content-length':
166 self.content_length = kv[1].strip()
167 list.append(self, item)
168
R David Murraybeed8402015-03-22 15:18:23 -0400169 # Here, we're testing that methods expecting a body get a
170 # content-length set to zero if the body is empty (either None or '')
171 bodies = (None, '')
172 methods_with_body = ('PUT', 'POST', 'PATCH')
173 for method, body in itertools.product(methods_with_body, bodies):
174 conn = client.HTTPConnection('example.com')
175 conn.sock = FakeSocket(None)
176 conn._buffer = ContentLengthChecker()
177 conn.request(method, '/', body)
178 self.assertEqual(
179 conn._buffer.content_length, b'0',
180 'Header Content-Length incorrect on {}'.format(method)
181 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800182
R David Murraybeed8402015-03-22 15:18:23 -0400183 # For these methods, we make sure that content-length is not set when
184 # the body is None because it might cause unexpected behaviour on the
185 # server.
186 methods_without_body = (
187 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
188 )
189 for method in methods_without_body:
190 conn = client.HTTPConnection('example.com')
191 conn.sock = FakeSocket(None)
192 conn._buffer = ContentLengthChecker()
193 conn.request(method, '/', None)
194 self.assertEqual(
195 conn._buffer.content_length, None,
196 'Header Content-Length set for empty body on {}'.format(method)
197 )
198
199 # If the body is set to '', that's considered to be "present but
200 # empty" rather than "missing", so content length would be set, even
201 # for methods that don't expect a body.
202 for method in methods_without_body:
203 conn = client.HTTPConnection('example.com')
204 conn.sock = FakeSocket(None)
205 conn._buffer = ContentLengthChecker()
206 conn.request(method, '/', '')
207 self.assertEqual(
208 conn._buffer.content_length, b'0',
209 'Header Content-Length incorrect on {}'.format(method)
210 )
211
212 # If the body is set, make sure Content-Length is set.
213 for method in itertools.chain(methods_without_body, methods_with_body):
214 conn = client.HTTPConnection('example.com')
215 conn.sock = FakeSocket(None)
216 conn._buffer = ContentLengthChecker()
217 conn.request(method, '/', ' ')
218 self.assertEqual(
219 conn._buffer.content_length, b'1',
220 'Header Content-Length incorrect on {}'.format(method)
221 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800222
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000223 def test_putheader(self):
224 conn = client.HTTPConnection('example.com')
225 conn.sock = FakeSocket(None)
226 conn.putrequest('GET','/')
227 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200228 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000229
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200230 conn.putheader('Foo', ' bar ')
231 self.assertIn(b'Foo: bar ', conn._buffer)
232 conn.putheader('Bar', '\tbaz\t')
233 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
234 conn.putheader('Authorization', 'Bearer mytoken')
235 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
236 conn.putheader('IterHeader', 'IterA', 'IterB')
237 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
238 conn.putheader('LatinHeader', b'\xFF')
239 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
240 conn.putheader('Utf8Header', b'\xc3\x80')
241 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
242 conn.putheader('C1-Control', b'next\x85line')
243 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
244 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
245 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
246 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
247 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
248 conn.putheader('Key Space', 'value')
249 self.assertIn(b'Key Space: value', conn._buffer)
250 conn.putheader('KeySpace ', 'value')
251 self.assertIn(b'KeySpace : value', conn._buffer)
252 conn.putheader(b'Nonbreak\xa0Space', 'value')
253 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
254 conn.putheader(b'\xa0NonbreakSpace', 'value')
255 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
256
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000257 def test_ipv6host_header(self):
258 # Default host header on IPv6 transaction should wrapped by [] if
259 # its actual IPv6 address
260 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
261 b'Accept-Encoding: identity\r\n\r\n'
262 conn = client.HTTPConnection('[2001::]:81')
263 sock = FakeSocket('')
264 conn.sock = sock
265 conn.request('GET', '/foo')
266 self.assertTrue(sock.data.startswith(expected))
267
268 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
269 b'Accept-Encoding: identity\r\n\r\n'
270 conn = client.HTTPConnection('[2001:102A::]')
271 sock = FakeSocket('')
272 conn.sock = sock
273 conn.request('GET', '/foo')
274 self.assertTrue(sock.data.startswith(expected))
275
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500276 def test_malformed_headers_coped_with(self):
277 # Issue 19996
278 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
279 sock = FakeSocket(body)
280 resp = client.HTTPResponse(sock)
281 resp.begin()
282
283 self.assertEqual(resp.getheader('First'), 'val')
284 self.assertEqual(resp.getheader('Second'), 'val')
285
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200286 def test_invalid_headers(self):
287 conn = client.HTTPConnection('example.com')
288 conn.sock = FakeSocket('')
289 conn.putrequest('GET', '/')
290
291 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
292 # longer allowed in header names
293 cases = (
294 (b'Invalid\r\nName', b'ValidValue'),
295 (b'Invalid\rName', b'ValidValue'),
296 (b'Invalid\nName', b'ValidValue'),
297 (b'\r\nInvalidName', b'ValidValue'),
298 (b'\rInvalidName', b'ValidValue'),
299 (b'\nInvalidName', b'ValidValue'),
300 (b' InvalidName', b'ValidValue'),
301 (b'\tInvalidName', b'ValidValue'),
302 (b'Invalid:Name', b'ValidValue'),
303 (b':InvalidName', b'ValidValue'),
304 (b'ValidName', b'Invalid\r\nValue'),
305 (b'ValidName', b'Invalid\rValue'),
306 (b'ValidName', b'Invalid\nValue'),
307 (b'ValidName', b'InvalidValue\r\n'),
308 (b'ValidName', b'InvalidValue\r'),
309 (b'ValidName', b'InvalidValue\n'),
310 )
311 for name, value in cases:
312 with self.subTest((name, value)):
313 with self.assertRaisesRegex(ValueError, 'Invalid header'):
314 conn.putheader(name, value)
315
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000316
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317class BasicTest(TestCase):
318 def test_status_lines(self):
319 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000320
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 body = "HTTP/1.1 200 Ok\r\n\r\nText"
322 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000323 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000324 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200325 self.assertEqual(resp.read(0), b'') # Issue #20007
326 self.assertFalse(resp.isclosed())
327 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000328 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000329 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200330 self.assertFalse(resp.closed)
331 resp.close()
332 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000333
Thomas Wouters89f507f2006-12-13 04:49:30 +0000334 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
335 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000336 resp = client.HTTPResponse(sock)
337 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000338
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000339 def test_bad_status_repr(self):
340 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000341 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000342
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000343 def test_partial_reads(self):
Martin Panterce911c32016-03-17 06:42:48 +0000344 # if we have Content-Length, HTTPResponse knows when to close itself,
345 # the same behaviour as when we read the whole thing with read()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000346 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
347 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000348 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000349 resp.begin()
350 self.assertEqual(resp.read(2), b'Te')
351 self.assertFalse(resp.isclosed())
352 self.assertEqual(resp.read(2), b'xt')
353 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200354 self.assertFalse(resp.closed)
355 resp.close()
356 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000357
Martin Panterce911c32016-03-17 06:42:48 +0000358 def test_mixed_reads(self):
359 # readline() should update the remaining length, so that read() knows
360 # how much data is left and does not raise IncompleteRead
361 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
362 sock = FakeSocket(body)
363 resp = client.HTTPResponse(sock)
364 resp.begin()
365 self.assertEqual(resp.readline(), b'Text\r\n')
366 self.assertFalse(resp.isclosed())
367 self.assertEqual(resp.read(), b'Another')
368 self.assertTrue(resp.isclosed())
369 self.assertFalse(resp.closed)
370 resp.close()
371 self.assertTrue(resp.closed)
372
Antoine Pitrou38d96432011-12-06 22:33:57 +0100373 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000374 # if we have Content-Length, HTTPResponse knows when to close itself,
375 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100376 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
377 sock = FakeSocket(body)
378 resp = client.HTTPResponse(sock)
379 resp.begin()
380 b = bytearray(2)
381 n = resp.readinto(b)
382 self.assertEqual(n, 2)
383 self.assertEqual(bytes(b), b'Te')
384 self.assertFalse(resp.isclosed())
385 n = resp.readinto(b)
386 self.assertEqual(n, 2)
387 self.assertEqual(bytes(b), b'xt')
388 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200389 self.assertFalse(resp.closed)
390 resp.close()
391 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100392
Antoine Pitrou084daa22012-12-15 19:11:54 +0100393 def test_partial_reads_no_content_length(self):
394 # when no length is present, the socket should be gracefully closed when
395 # all data was read
396 body = "HTTP/1.1 200 Ok\r\n\r\nText"
397 sock = FakeSocket(body)
398 resp = client.HTTPResponse(sock)
399 resp.begin()
400 self.assertEqual(resp.read(2), b'Te')
401 self.assertFalse(resp.isclosed())
402 self.assertEqual(resp.read(2), b'xt')
403 self.assertEqual(resp.read(1), b'')
404 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200405 self.assertFalse(resp.closed)
406 resp.close()
407 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100408
Antoine Pitroud20e7742012-12-15 19:22:30 +0100409 def test_partial_readintos_no_content_length(self):
410 # when no length is present, the socket should be gracefully closed when
411 # all data was read
412 body = "HTTP/1.1 200 Ok\r\n\r\nText"
413 sock = FakeSocket(body)
414 resp = client.HTTPResponse(sock)
415 resp.begin()
416 b = bytearray(2)
417 n = resp.readinto(b)
418 self.assertEqual(n, 2)
419 self.assertEqual(bytes(b), b'Te')
420 self.assertFalse(resp.isclosed())
421 n = resp.readinto(b)
422 self.assertEqual(n, 2)
423 self.assertEqual(bytes(b), b'xt')
424 n = resp.readinto(b)
425 self.assertEqual(n, 0)
426 self.assertTrue(resp.isclosed())
427
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100428 def test_partial_reads_incomplete_body(self):
429 # if the server shuts down the connection before the whole
430 # content-length is delivered, the socket is gracefully closed
431 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
432 sock = FakeSocket(body)
433 resp = client.HTTPResponse(sock)
434 resp.begin()
435 self.assertEqual(resp.read(2), b'Te')
436 self.assertFalse(resp.isclosed())
437 self.assertEqual(resp.read(2), b'xt')
438 self.assertEqual(resp.read(1), b'')
439 self.assertTrue(resp.isclosed())
440
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100441 def test_partial_readintos_incomplete_body(self):
442 # if the server shuts down the connection before the whole
443 # content-length is delivered, the socket is gracefully closed
444 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
445 sock = FakeSocket(body)
446 resp = client.HTTPResponse(sock)
447 resp.begin()
448 b = bytearray(2)
449 n = resp.readinto(b)
450 self.assertEqual(n, 2)
451 self.assertEqual(bytes(b), b'Te')
452 self.assertFalse(resp.isclosed())
453 n = resp.readinto(b)
454 self.assertEqual(n, 2)
455 self.assertEqual(bytes(b), b'xt')
456 n = resp.readinto(b)
457 self.assertEqual(n, 0)
458 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200459 self.assertFalse(resp.closed)
460 resp.close()
461 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100462
Thomas Wouters89f507f2006-12-13 04:49:30 +0000463 def test_host_port(self):
464 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000465
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200466 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000467 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000468
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000469 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
470 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000471 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200472 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000473 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200474 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
475 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000476 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000477 self.assertEqual(h, c.host)
478 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000479
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480 def test_response_headers(self):
481 # test response with multiple message headers with the same field name.
482 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000483 'Set-Cookie: Customer="WILE_E_COYOTE"; '
484 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000485 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
486 ' Path="/acme"\r\n'
487 '\r\n'
488 'No body\r\n')
489 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
490 ', '
491 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
492 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000493 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 r.begin()
495 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000496 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000497
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498 def test_read_head(self):
499 # Test that the library doesn't attempt to read any data
500 # from a HEAD request. (Tickles SF bug #622042.)
501 sock = FakeSocket(
502 'HTTP/1.1 200 OK\r\n'
503 'Content-Length: 14432\r\n'
504 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300505 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000506 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000507 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000508 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000509 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000510
Antoine Pitrou38d96432011-12-06 22:33:57 +0100511 def test_readinto_head(self):
512 # Test that the library doesn't attempt to read any data
513 # from a HEAD request. (Tickles SF bug #622042.)
514 sock = FakeSocket(
515 'HTTP/1.1 200 OK\r\n'
516 'Content-Length: 14432\r\n'
517 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300518 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100519 resp = client.HTTPResponse(sock, method="HEAD")
520 resp.begin()
521 b = bytearray(5)
522 if resp.readinto(b) != 0:
523 self.fail("Did not expect response from HEAD request")
524 self.assertEqual(bytes(b), b'\x00'*5)
525
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100526 def test_too_many_headers(self):
527 headers = '\r\n'.join('Header%d: foo' % i
528 for i in range(client._MAXHEADERS + 1)) + '\r\n'
529 text = ('HTTP/1.1 200 OK\r\n' + headers)
530 s = FakeSocket(text)
531 r = client.HTTPResponse(s)
532 self.assertRaisesRegex(client.HTTPException,
533 r"got more than \d+ headers", r.begin)
534
Thomas Wouters89f507f2006-12-13 04:49:30 +0000535 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000536 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
537 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000538
Brett Cannon77b7de62010-10-29 23:31:11 +0000539 with open(__file__, 'rb') as body:
540 conn = client.HTTPConnection('example.com')
541 sock = FakeSocket(body)
542 conn.sock = sock
543 conn.request('GET', '/foo', body)
544 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
545 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000546
Antoine Pitrouead1d622009-09-29 18:44:53 +0000547 def test_send(self):
548 expected = b'this is a test this is only a test'
549 conn = client.HTTPConnection('example.com')
550 sock = FakeSocket(None)
551 conn.sock = sock
552 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000553 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000554 sock.data = b''
555 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000556 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000557 sock.data = b''
558 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000559 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000560
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300561 def test_send_updating_file(self):
562 def data():
563 yield 'data'
564 yield None
565 yield 'data_two'
566
567 class UpdatingFile():
568 mode = 'r'
569 d = data()
570 def read(self, blocksize=-1):
571 return self.d.__next__()
572
573 expected = b'data'
574
575 conn = client.HTTPConnection('example.com')
576 sock = FakeSocket("")
577 conn.sock = sock
578 conn.send(UpdatingFile())
579 self.assertEqual(sock.data, expected)
580
581
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000582 def test_send_iter(self):
583 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
584 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
585 b'\r\nonetwothree'
586
587 def body():
588 yield b"one"
589 yield b"two"
590 yield b"three"
591
592 conn = client.HTTPConnection('example.com')
593 sock = FakeSocket("")
594 conn.sock = sock
595 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000596 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000597
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800598 def test_send_type_error(self):
599 # See: Issue #12676
600 conn = client.HTTPConnection('example.com')
601 conn.sock = FakeSocket('')
602 with self.assertRaises(TypeError):
603 conn.request('POST', 'test', conn)
604
Christian Heimesa612dc02008-02-24 13:08:18 +0000605 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000606 expected = chunked_expected
607 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000608 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000609 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100610 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000611 resp.close()
612
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100613 # Various read sizes
614 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000615 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100616 resp = client.HTTPResponse(sock, method="GET")
617 resp.begin()
618 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
619 resp.close()
620
Christian Heimesa612dc02008-02-24 13:08:18 +0000621 for x in ('', 'foo\r\n'):
622 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000623 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000624 resp.begin()
625 try:
626 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000627 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100628 self.assertEqual(i.partial, expected)
629 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
630 self.assertEqual(repr(i), expected_message)
631 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000632 else:
633 self.fail('IncompleteRead expected')
634 finally:
635 resp.close()
636
Antoine Pitrou38d96432011-12-06 22:33:57 +0100637 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000638
639 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100640 nexpected = len(expected)
641 b = bytearray(128)
642
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000643 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100644 resp = client.HTTPResponse(sock, method="GET")
645 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100646 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100647 self.assertEqual(b[:nexpected], expected)
648 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100649 resp.close()
650
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100651 # Various read sizes
652 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000653 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100654 resp = client.HTTPResponse(sock, method="GET")
655 resp.begin()
656 m = memoryview(b)
657 i = resp.readinto(m[0:n])
658 i += resp.readinto(m[i:n + i])
659 i += resp.readinto(m[i:])
660 self.assertEqual(b[:nexpected], expected)
661 self.assertEqual(i, nexpected)
662 resp.close()
663
Antoine Pitrou38d96432011-12-06 22:33:57 +0100664 for x in ('', 'foo\r\n'):
665 sock = FakeSocket(chunked_start + x)
666 resp = client.HTTPResponse(sock, method="GET")
667 resp.begin()
668 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100669 n = resp.readinto(b)
670 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100671 self.assertEqual(i.partial, expected)
672 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
673 self.assertEqual(repr(i), expected_message)
674 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100675 else:
676 self.fail('IncompleteRead expected')
677 finally:
678 resp.close()
679
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000680 def test_chunked_head(self):
681 chunked_start = (
682 'HTTP/1.1 200 OK\r\n'
683 'Transfer-Encoding: chunked\r\n\r\n'
684 'a\r\n'
685 'hello world\r\n'
686 '1\r\n'
687 'd\r\n'
688 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000689 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000690 resp = client.HTTPResponse(sock, method="HEAD")
691 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000692 self.assertEqual(resp.read(), b'')
693 self.assertEqual(resp.status, 200)
694 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000695 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200696 self.assertFalse(resp.closed)
697 resp.close()
698 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000699
Antoine Pitrou38d96432011-12-06 22:33:57 +0100700 def test_readinto_chunked_head(self):
701 chunked_start = (
702 'HTTP/1.1 200 OK\r\n'
703 'Transfer-Encoding: chunked\r\n\r\n'
704 'a\r\n'
705 'hello world\r\n'
706 '1\r\n'
707 'd\r\n'
708 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000709 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100710 resp = client.HTTPResponse(sock, method="HEAD")
711 resp.begin()
712 b = bytearray(5)
713 n = resp.readinto(b)
714 self.assertEqual(n, 0)
715 self.assertEqual(bytes(b), b'\x00'*5)
716 self.assertEqual(resp.status, 200)
717 self.assertEqual(resp.reason, 'OK')
718 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200719 self.assertFalse(resp.closed)
720 resp.close()
721 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100722
Christian Heimesa612dc02008-02-24 13:08:18 +0000723 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000724 sock = FakeSocket(
725 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000726 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000727 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000728 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100729 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000730
Benjamin Peterson6accb982009-03-02 22:50:25 +0000731 def test_incomplete_read(self):
732 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000733 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000734 resp.begin()
735 try:
736 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000737 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000738 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000739 self.assertEqual(repr(i),
740 "IncompleteRead(7 bytes read, 3 more expected)")
741 self.assertEqual(str(i),
742 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100743 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000744 else:
745 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000746
Jeremy Hylton636950f2009-03-28 04:34:21 +0000747 def test_epipe(self):
748 sock = EPipeSocket(
749 "HTTP/1.0 401 Authorization Required\r\n"
750 "Content-type: text/html\r\n"
751 "WWW-Authenticate: Basic realm=\"example\"\r\n",
752 b"Content-Length")
753 conn = client.HTTPConnection("example.com")
754 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200755 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000756 lambda: conn.request("PUT", "/url", "body"))
757 resp = conn.getresponse()
758 self.assertEqual(401, resp.status)
759 self.assertEqual("Basic realm=\"example\"",
760 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000761
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000762 # Test lines overflowing the max line size (_MAXLINE in http.client)
763
764 def test_overflowing_status_line(self):
765 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
766 resp = client.HTTPResponse(FakeSocket(body))
767 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
768
769 def test_overflowing_header_line(self):
770 body = (
771 'HTTP/1.1 200 OK\r\n'
772 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
773 )
774 resp = client.HTTPResponse(FakeSocket(body))
775 self.assertRaises(client.LineTooLong, resp.begin)
776
777 def test_overflowing_chunked_line(self):
778 body = (
779 'HTTP/1.1 200 OK\r\n'
780 'Transfer-Encoding: chunked\r\n\r\n'
781 + '0' * 65536 + 'a\r\n'
782 'hello world\r\n'
783 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000784 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000785 )
786 resp = client.HTTPResponse(FakeSocket(body))
787 resp.begin()
788 self.assertRaises(client.LineTooLong, resp.read)
789
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800790 def test_early_eof(self):
791 # Test httpresponse with no \r\n termination,
792 body = "HTTP/1.1 200 Ok"
793 sock = FakeSocket(body)
794 resp = client.HTTPResponse(sock)
795 resp.begin()
796 self.assertEqual(resp.read(), b'')
797 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200798 self.assertFalse(resp.closed)
799 resp.close()
800 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800801
Serhiy Storchakab491e052014-12-01 13:07:45 +0200802 def test_error_leak(self):
803 # Test that the socket is not leaked if getresponse() fails
804 conn = client.HTTPConnection('example.com')
805 response = None
806 class Response(client.HTTPResponse):
807 def __init__(self, *pos, **kw):
808 nonlocal response
809 response = self # Avoid garbage collector closing the socket
810 client.HTTPResponse.__init__(self, *pos, **kw)
811 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -0400812 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +0200813 conn.request('GET', '/')
814 self.assertRaises(client.BadStatusLine, conn.getresponse)
815 self.assertTrue(response.closed)
816 self.assertTrue(conn.sock.file_closed)
817
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000818 def test_chunked_extension(self):
819 extra = '3;foo=bar\r\n' + 'abc\r\n'
820 expected = chunked_expected + b'abc'
821
822 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
823 resp = client.HTTPResponse(sock, method="GET")
824 resp.begin()
825 self.assertEqual(resp.read(), expected)
826 resp.close()
827
828 def test_chunked_missing_end(self):
829 """some servers may serve up a short chunked encoding stream"""
830 expected = chunked_expected
831 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
832 resp = client.HTTPResponse(sock, method="GET")
833 resp.begin()
834 self.assertEqual(resp.read(), expected)
835 resp.close()
836
837 def test_chunked_trailers(self):
838 """See that trailers are read and ignored"""
839 expected = chunked_expected
840 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
841 resp = client.HTTPResponse(sock, method="GET")
842 resp.begin()
843 self.assertEqual(resp.read(), expected)
844 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +0000845 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000846 resp.close()
847
848 def test_chunked_sync(self):
849 """Check that we don't read past the end of the chunked-encoding stream"""
850 expected = chunked_expected
851 extradata = "extradata"
852 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
853 resp = client.HTTPResponse(sock, method="GET")
854 resp.begin()
855 self.assertEqual(resp.read(), expected)
856 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +0000857 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000858 resp.close()
859
860 def test_content_length_sync(self):
861 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +0000862 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000863 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +0000864 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 +0000865 resp = client.HTTPResponse(sock, method="GET")
866 resp.begin()
867 self.assertEqual(resp.read(), expected)
868 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +0000869 self.assertEqual(sock.file.read(), extradata) #we read to the end
870 resp.close()
871
872 def test_readlines_content_length(self):
873 extradata = b"extradata"
874 expected = b"Hello123\r\n"
875 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
876 resp = client.HTTPResponse(sock, method="GET")
877 resp.begin()
878 self.assertEqual(resp.readlines(2000), [expected])
879 # the file should now have our extradata ready to be read
880 self.assertEqual(sock.file.read(), extradata) #we read to the end
881 resp.close()
882
883 def test_read1_content_length(self):
884 extradata = b"extradata"
885 expected = b"Hello123\r\n"
886 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
887 resp = client.HTTPResponse(sock, method="GET")
888 resp.begin()
889 self.assertEqual(resp.read1(2000), expected)
890 # the file should now have our extradata ready to be read
891 self.assertEqual(sock.file.read(), extradata) #we read to the end
892 resp.close()
893
894 def test_readline_bound_content_length(self):
895 extradata = b"extradata"
896 expected = b"Hello123\r\n"
897 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
898 resp = client.HTTPResponse(sock, method="GET")
899 resp.begin()
900 self.assertEqual(resp.readline(10), expected)
901 self.assertEqual(resp.readline(10), b"")
902 # the file should now have our extradata ready to be read
903 self.assertEqual(sock.file.read(), extradata) #we read to the end
904 resp.close()
905
906 def test_read1_bound_content_length(self):
907 extradata = b"extradata"
908 expected = b"Hello123\r\n"
909 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
910 resp = client.HTTPResponse(sock, method="GET")
911 resp.begin()
912 self.assertEqual(resp.read1(20), expected*2)
913 self.assertEqual(resp.read(), expected)
914 # the file should now have our extradata ready to be read
915 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000916 resp.close()
917
918class ExtendedReadTest(TestCase):
919 """
920 Test peek(), read1(), readline()
921 """
922 lines = (
923 'HTTP/1.1 200 OK\r\n'
924 '\r\n'
925 'hello world!\n'
926 'and now \n'
927 'for something completely different\n'
928 'foo'
929 )
930 lines_expected = lines[lines.find('hello'):].encode("ascii")
931 lines_chunked = (
932 'HTTP/1.1 200 OK\r\n'
933 'Transfer-Encoding: chunked\r\n\r\n'
934 'a\r\n'
935 'hello worl\r\n'
936 '3\r\n'
937 'd!\n\r\n'
938 '9\r\n'
939 'and now \n\r\n'
940 '23\r\n'
941 'for something completely different\n\r\n'
942 '3\r\n'
943 'foo\r\n'
944 '0\r\n' # terminating chunk
945 '\r\n' # end of trailers
946 )
947
948 def setUp(self):
949 sock = FakeSocket(self.lines)
950 resp = client.HTTPResponse(sock, method="GET")
951 resp.begin()
952 resp.fp = io.BufferedReader(resp.fp)
953 self.resp = resp
954
955
956
957 def test_peek(self):
958 resp = self.resp
959 # patch up the buffered peek so that it returns not too much stuff
960 oldpeek = resp.fp.peek
961 def mypeek(n=-1):
962 p = oldpeek(n)
963 if n >= 0:
964 return p[:n]
965 return p[:10]
966 resp.fp.peek = mypeek
967
968 all = []
969 while True:
970 # try a short peek
971 p = resp.peek(3)
972 if p:
973 self.assertGreater(len(p), 0)
974 # then unbounded peek
975 p2 = resp.peek()
976 self.assertGreaterEqual(len(p2), len(p))
977 self.assertTrue(p2.startswith(p))
978 next = resp.read(len(p2))
979 self.assertEqual(next, p2)
980 else:
981 next = resp.read()
982 self.assertFalse(next)
983 all.append(next)
984 if not next:
985 break
986 self.assertEqual(b"".join(all), self.lines_expected)
987
988 def test_readline(self):
989 resp = self.resp
990 self._verify_readline(self.resp.readline, self.lines_expected)
991
992 def _verify_readline(self, readline, expected):
993 all = []
994 while True:
995 # short readlines
996 line = readline(5)
997 if line and line != b"foo":
998 if len(line) < 5:
999 self.assertTrue(line.endswith(b"\n"))
1000 all.append(line)
1001 if not line:
1002 break
1003 self.assertEqual(b"".join(all), expected)
1004
1005 def test_read1(self):
1006 resp = self.resp
1007 def r():
1008 res = resp.read1(4)
1009 self.assertLessEqual(len(res), 4)
1010 return res
1011 readliner = Readliner(r)
1012 self._verify_readline(readliner.readline, self.lines_expected)
1013
1014 def test_read1_unbounded(self):
1015 resp = self.resp
1016 all = []
1017 while True:
1018 data = resp.read1()
1019 if not data:
1020 break
1021 all.append(data)
1022 self.assertEqual(b"".join(all), self.lines_expected)
1023
1024 def test_read1_bounded(self):
1025 resp = self.resp
1026 all = []
1027 while True:
1028 data = resp.read1(10)
1029 if not data:
1030 break
1031 self.assertLessEqual(len(data), 10)
1032 all.append(data)
1033 self.assertEqual(b"".join(all), self.lines_expected)
1034
1035 def test_read1_0(self):
1036 self.assertEqual(self.resp.read1(0), b"")
1037
1038 def test_peek_0(self):
1039 p = self.resp.peek(0)
1040 self.assertLessEqual(0, len(p))
1041
1042class ExtendedReadTestChunked(ExtendedReadTest):
1043 """
1044 Test peek(), read1(), readline() in chunked mode
1045 """
1046 lines = (
1047 'HTTP/1.1 200 OK\r\n'
1048 'Transfer-Encoding: chunked\r\n\r\n'
1049 'a\r\n'
1050 'hello worl\r\n'
1051 '3\r\n'
1052 'd!\n\r\n'
1053 '9\r\n'
1054 'and now \n\r\n'
1055 '23\r\n'
1056 'for something completely different\n\r\n'
1057 '3\r\n'
1058 'foo\r\n'
1059 '0\r\n' # terminating chunk
1060 '\r\n' # end of trailers
1061 )
1062
1063
1064class Readliner:
1065 """
1066 a simple readline class that uses an arbitrary read function and buffering
1067 """
1068 def __init__(self, readfunc):
1069 self.readfunc = readfunc
1070 self.remainder = b""
1071
1072 def readline(self, limit):
1073 data = []
1074 datalen = 0
1075 read = self.remainder
1076 try:
1077 while True:
1078 idx = read.find(b'\n')
1079 if idx != -1:
1080 break
1081 if datalen + len(read) >= limit:
1082 idx = limit - datalen - 1
1083 # read more data
1084 data.append(read)
1085 read = self.readfunc()
1086 if not read:
1087 idx = 0 #eof condition
1088 break
1089 idx += 1
1090 data.append(read[:idx])
1091 self.remainder = read[idx:]
1092 return b"".join(data)
1093 except:
1094 self.remainder = b"".join(data)
1095 raise
1096
Berker Peksagbabc6882015-02-20 09:39:38 +02001097
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001098class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001099 def test_all(self):
1100 # Documented objects defined in the module should be in __all__
1101 expected = {"responses"} # White-list documented dict() object
1102 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1103 # intentionally omitted for simplicity
1104 blacklist = {"HTTPMessage", "parse_headers"}
1105 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001106 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001107 continue
1108 module_object = getattr(client, name)
1109 if getattr(module_object, "__module__", None) == "http.client":
1110 expected.add(name)
1111 self.assertCountEqual(client.__all__, expected)
1112
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001113 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001114 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001115
Berker Peksagabbf0f42015-02-20 14:57:31 +02001116 def test_client_constants(self):
1117 # Make sure we don't break backward compatibility with 3.4
1118 expected = [
1119 'CONTINUE',
1120 'SWITCHING_PROTOCOLS',
1121 'PROCESSING',
1122 'OK',
1123 'CREATED',
1124 'ACCEPTED',
1125 'NON_AUTHORITATIVE_INFORMATION',
1126 'NO_CONTENT',
1127 'RESET_CONTENT',
1128 'PARTIAL_CONTENT',
1129 'MULTI_STATUS',
1130 'IM_USED',
1131 'MULTIPLE_CHOICES',
1132 'MOVED_PERMANENTLY',
1133 'FOUND',
1134 'SEE_OTHER',
1135 'NOT_MODIFIED',
1136 'USE_PROXY',
1137 'TEMPORARY_REDIRECT',
1138 'BAD_REQUEST',
1139 'UNAUTHORIZED',
1140 'PAYMENT_REQUIRED',
1141 'FORBIDDEN',
1142 'NOT_FOUND',
1143 'METHOD_NOT_ALLOWED',
1144 'NOT_ACCEPTABLE',
1145 'PROXY_AUTHENTICATION_REQUIRED',
1146 'REQUEST_TIMEOUT',
1147 'CONFLICT',
1148 'GONE',
1149 'LENGTH_REQUIRED',
1150 'PRECONDITION_FAILED',
1151 'REQUEST_ENTITY_TOO_LARGE',
1152 'REQUEST_URI_TOO_LONG',
1153 'UNSUPPORTED_MEDIA_TYPE',
1154 'REQUESTED_RANGE_NOT_SATISFIABLE',
1155 'EXPECTATION_FAILED',
1156 'UNPROCESSABLE_ENTITY',
1157 'LOCKED',
1158 'FAILED_DEPENDENCY',
1159 'UPGRADE_REQUIRED',
1160 'PRECONDITION_REQUIRED',
1161 'TOO_MANY_REQUESTS',
1162 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1163 'INTERNAL_SERVER_ERROR',
1164 'NOT_IMPLEMENTED',
1165 'BAD_GATEWAY',
1166 'SERVICE_UNAVAILABLE',
1167 'GATEWAY_TIMEOUT',
1168 'HTTP_VERSION_NOT_SUPPORTED',
1169 'INSUFFICIENT_STORAGE',
1170 'NOT_EXTENDED',
1171 'NETWORK_AUTHENTICATION_REQUIRED',
1172 ]
1173 for const in expected:
1174 with self.subTest(constant=const):
1175 self.assertTrue(hasattr(client, const))
1176
Gregory P. Smithb4066372010-01-03 03:28:29 +00001177
1178class SourceAddressTest(TestCase):
1179 def setUp(self):
1180 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1181 self.port = support.bind_port(self.serv)
1182 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001183 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001184 self.conn = None
1185
1186 def tearDown(self):
1187 if self.conn:
1188 self.conn.close()
1189 self.conn = None
1190 self.serv.close()
1191 self.serv = None
1192
1193 def testHTTPConnectionSourceAddress(self):
1194 self.conn = client.HTTPConnection(HOST, self.port,
1195 source_address=('', self.source_port))
1196 self.conn.connect()
1197 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1198
1199 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1200 'http.client.HTTPSConnection not defined')
1201 def testHTTPSConnectionSourceAddress(self):
1202 self.conn = client.HTTPSConnection(HOST, self.port,
1203 source_address=('', self.source_port))
1204 # We don't test anything here other the constructor not barfing as
1205 # this code doesn't deal with setting up an active running SSL server
1206 # for an ssl_wrapped connect() to actually return from.
1207
1208
Guido van Rossumd8faa362007-04-27 19:54:29 +00001209class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001210 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001211
1212 def setUp(self):
1213 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001214 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001215 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001216
1217 def tearDown(self):
1218 self.serv.close()
1219 self.serv = None
1220
1221 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001222 # This will prove that the timeout gets through HTTPConnection
1223 # and into the socket.
1224
Georg Brandlf78e02b2008-06-10 17:40:04 +00001225 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001226 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001227 socket.setdefaulttimeout(30)
1228 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001229 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001230 httpConn.connect()
1231 finally:
1232 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001233 self.assertEqual(httpConn.sock.gettimeout(), 30)
1234 httpConn.close()
1235
Georg Brandlf78e02b2008-06-10 17:40:04 +00001236 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001237 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001238 socket.setdefaulttimeout(30)
1239 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001240 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001241 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001242 httpConn.connect()
1243 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001244 socket.setdefaulttimeout(None)
1245 self.assertEqual(httpConn.sock.gettimeout(), None)
1246 httpConn.close()
1247
1248 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001249 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001250 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001251 self.assertEqual(httpConn.sock.gettimeout(), 30)
1252 httpConn.close()
1253
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001254
R David Murraycae7bdb2015-04-05 19:26:29 -04001255class PersistenceTest(TestCase):
1256
1257 def test_reuse_reconnect(self):
1258 # Should reuse or reconnect depending on header from server
1259 tests = (
1260 ('1.0', '', False),
1261 ('1.0', 'Connection: keep-alive\r\n', True),
1262 ('1.1', '', True),
1263 ('1.1', 'Connection: close\r\n', False),
1264 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1265 ('1.1', 'Connection: cloSE\r\n', False),
1266 )
1267 for version, header, reuse in tests:
1268 with self.subTest(version=version, header=header):
1269 msg = (
1270 'HTTP/{} 200 OK\r\n'
1271 '{}'
1272 'Content-Length: 12\r\n'
1273 '\r\n'
1274 'Dummy body\r\n'
1275 ).format(version, header)
1276 conn = FakeSocketHTTPConnection(msg)
1277 self.assertIsNone(conn.sock)
1278 conn.request('GET', '/open-connection')
1279 with conn.getresponse() as response:
1280 self.assertEqual(conn.sock is None, not reuse)
1281 response.read()
1282 self.assertEqual(conn.sock is None, not reuse)
1283 self.assertEqual(conn.connections, 1)
1284 conn.request('GET', '/subsequent-request')
1285 self.assertEqual(conn.connections, 1 if reuse else 2)
1286
1287 def test_disconnected(self):
1288
1289 def make_reset_reader(text):
1290 """Return BufferedReader that raises ECONNRESET at EOF"""
1291 stream = io.BytesIO(text)
1292 def readinto(buffer):
1293 size = io.BytesIO.readinto(stream, buffer)
1294 if size == 0:
1295 raise ConnectionResetError()
1296 return size
1297 stream.readinto = readinto
1298 return io.BufferedReader(stream)
1299
1300 tests = (
1301 (io.BytesIO, client.RemoteDisconnected),
1302 (make_reset_reader, ConnectionResetError),
1303 )
1304 for stream_factory, exception in tests:
1305 with self.subTest(exception=exception):
1306 conn = FakeSocketHTTPConnection(b'', stream_factory)
1307 conn.request('GET', '/eof-response')
1308 self.assertRaises(exception, conn.getresponse)
1309 self.assertIsNone(conn.sock)
1310 # HTTPConnection.connect() should be automatically invoked
1311 conn.request('GET', '/reconnect')
1312 self.assertEqual(conn.connections, 2)
1313
1314 def test_100_close(self):
1315 conn = FakeSocketHTTPConnection(
1316 b'HTTP/1.1 100 Continue\r\n'
1317 b'\r\n'
1318 # Missing final response
1319 )
1320 conn.request('GET', '/', headers={'Expect': '100-continue'})
1321 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1322 self.assertIsNone(conn.sock)
1323 conn.request('GET', '/reconnect')
1324 self.assertEqual(conn.connections, 2)
1325
1326
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001327class HTTPSTest(TestCase):
1328
1329 def setUp(self):
1330 if not hasattr(client, 'HTTPSConnection'):
1331 self.skipTest('ssl support required')
1332
1333 def make_server(self, certfile):
1334 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001335 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001336
1337 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001338 # simple test to check it's storing the timeout
1339 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1340 self.assertEqual(h.timeout, 30)
1341
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001342 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001343 # Default settings: requires a valid cert from a trusted CA
1344 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001345 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001346 with support.transient_internet('self-signed.pythontest.net'):
1347 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1348 with self.assertRaises(ssl.SSLError) as exc_info:
1349 h.request('GET', '/')
1350 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1351
1352 def test_networked_noverification(self):
1353 # Switch off cert verification
1354 import ssl
1355 support.requires('network')
1356 with support.transient_internet('self-signed.pythontest.net'):
1357 context = ssl._create_unverified_context()
1358 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1359 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001360 h.request('GET', '/')
1361 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001362 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001363 self.assertIn('nginx', resp.getheader('server'))
1364
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001365 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001366 def test_networked_trusted_by_default_cert(self):
1367 # Default settings: requires a valid cert from a trusted CA
1368 support.requires('network')
1369 with support.transient_internet('www.python.org'):
1370 h = client.HTTPSConnection('www.python.org', 443)
1371 h.request('GET', '/')
1372 resp = h.getresponse()
1373 content_type = resp.getheader('content-type')
Victor Stinnerb389b482015-02-27 17:47:23 +01001374 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001375 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001376
1377 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001378 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001379 import ssl
1380 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +01001381 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001382 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1383 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +01001384 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
1385 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001386 h.request('GET', '/')
1387 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001388 server_string = resp.getheader('server')
Victor Stinnerb389b482015-02-27 17:47:23 +01001389 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001390 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001391
1392 def test_networked_bad_cert(self):
1393 # We feed a "CA" cert that is unrelated to the server's cert
1394 import ssl
1395 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001396 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001397 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1398 context.verify_mode = ssl.CERT_REQUIRED
1399 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001400 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1401 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001402 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001403 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1404
1405 def test_local_unknown_cert(self):
1406 # The custom cert isn't known to the default trust bundle
1407 import ssl
1408 server = self.make_server(CERT_localhost)
1409 h = client.HTTPSConnection('localhost', server.port)
1410 with self.assertRaises(ssl.SSLError) as exc_info:
1411 h.request('GET', '/')
1412 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001413
1414 def test_local_good_hostname(self):
1415 # The (valid) cert validates the HTTP hostname
1416 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001417 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001418 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1419 context.verify_mode = ssl.CERT_REQUIRED
1420 context.load_verify_locations(CERT_localhost)
1421 h = client.HTTPSConnection('localhost', server.port, context=context)
1422 h.request('GET', '/nonexistent')
1423 resp = h.getresponse()
1424 self.assertEqual(resp.status, 404)
1425
1426 def test_local_bad_hostname(self):
1427 # The (valid) cert doesn't validate the HTTP hostname
1428 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001429 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001430 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1431 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -05001432 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001433 context.load_verify_locations(CERT_fakehostname)
1434 h = client.HTTPSConnection('localhost', server.port, context=context)
1435 with self.assertRaises(ssl.CertificateError):
1436 h.request('GET', '/')
1437 # Same with explicit check_hostname=True
1438 h = client.HTTPSConnection('localhost', server.port, context=context,
1439 check_hostname=True)
1440 with self.assertRaises(ssl.CertificateError):
1441 h.request('GET', '/')
1442 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001443 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001444 h = client.HTTPSConnection('localhost', server.port, context=context,
1445 check_hostname=False)
1446 h.request('GET', '/nonexistent')
1447 resp = h.getresponse()
1448 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001449 # The context's check_hostname setting is used if one isn't passed to
1450 # HTTPSConnection.
1451 context.check_hostname = False
1452 h = client.HTTPSConnection('localhost', server.port, context=context)
1453 h.request('GET', '/nonexistent')
1454 self.assertEqual(h.getresponse().status, 404)
1455 # Passing check_hostname to HTTPSConnection should override the
1456 # context's setting.
1457 h = client.HTTPSConnection('localhost', server.port, context=context,
1458 check_hostname=True)
1459 with self.assertRaises(ssl.CertificateError):
1460 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001461
Petri Lehtinene119c402011-10-26 21:29:15 +03001462 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1463 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001464 def test_host_port(self):
1465 # Check invalid host_port
1466
1467 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1468 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1469
1470 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1471 "fe80::207:e9ff:fe9b", 8000),
1472 ("www.python.org:443", "www.python.org", 443),
1473 ("www.python.org:", "www.python.org", 443),
1474 ("www.python.org", "www.python.org", 443),
1475 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1476 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1477 443)):
1478 c = client.HTTPSConnection(hp)
1479 self.assertEqual(h, c.host)
1480 self.assertEqual(p, c.port)
1481
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001482
Jeremy Hylton236654b2009-03-27 20:24:34 +00001483class RequestBodyTest(TestCase):
1484 """Test cases where a request includes a message body."""
1485
1486 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001487 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001488 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001489 self.conn.sock = self.sock
1490
1491 def get_headers_and_fp(self):
1492 f = io.BytesIO(self.sock.data)
1493 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001494 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001495 return message, f
1496
1497 def test_manual_content_length(self):
1498 # Set an incorrect content-length so that we can verify that
1499 # it will not be over-ridden by the library.
1500 self.conn.request("PUT", "/url", "body",
1501 {"Content-Length": "42"})
1502 message, f = self.get_headers_and_fp()
1503 self.assertEqual("42", message.get("content-length"))
1504 self.assertEqual(4, len(f.read()))
1505
1506 def test_ascii_body(self):
1507 self.conn.request("PUT", "/url", "body")
1508 message, f = self.get_headers_and_fp()
1509 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001510 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001511 self.assertEqual("4", message.get("content-length"))
1512 self.assertEqual(b'body', f.read())
1513
1514 def test_latin1_body(self):
1515 self.conn.request("PUT", "/url", "body\xc1")
1516 message, f = self.get_headers_and_fp()
1517 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001518 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001519 self.assertEqual("5", message.get("content-length"))
1520 self.assertEqual(b'body\xc1', f.read())
1521
1522 def test_bytes_body(self):
1523 self.conn.request("PUT", "/url", b"body\xc1")
1524 message, f = self.get_headers_and_fp()
1525 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001526 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001527 self.assertEqual("5", message.get("content-length"))
1528 self.assertEqual(b'body\xc1', f.read())
1529
1530 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001531 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001532 with open(support.TESTFN, "w") as f:
1533 f.write("body")
1534 with open(support.TESTFN) as f:
1535 self.conn.request("PUT", "/url", f)
1536 message, f = self.get_headers_and_fp()
1537 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001538 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001539 self.assertEqual("4", message.get("content-length"))
1540 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001541
1542 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001543 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001544 with open(support.TESTFN, "wb") as f:
1545 f.write(b"body\xc1")
1546 with open(support.TESTFN, "rb") as f:
1547 self.conn.request("PUT", "/url", f)
1548 message, f = self.get_headers_and_fp()
1549 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001550 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001551 self.assertEqual("5", message.get("content-length"))
1552 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001553
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001554
1555class HTTPResponseTest(TestCase):
1556
1557 def setUp(self):
1558 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1559 second-value\r\n\r\nText"
1560 sock = FakeSocket(body)
1561 self.resp = client.HTTPResponse(sock)
1562 self.resp.begin()
1563
1564 def test_getting_header(self):
1565 header = self.resp.getheader('My-Header')
1566 self.assertEqual(header, 'first-value, second-value')
1567
1568 header = self.resp.getheader('My-Header', 'some default')
1569 self.assertEqual(header, 'first-value, second-value')
1570
1571 def test_getting_nonexistent_header_with_string_default(self):
1572 header = self.resp.getheader('No-Such-Header', 'default-value')
1573 self.assertEqual(header, 'default-value')
1574
1575 def test_getting_nonexistent_header_with_iterable_default(self):
1576 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1577 self.assertEqual(header, 'default, values')
1578
1579 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1580 self.assertEqual(header, 'default, values')
1581
1582 def test_getting_nonexistent_header_without_default(self):
1583 header = self.resp.getheader('No-Such-Header')
1584 self.assertEqual(header, None)
1585
1586 def test_getting_header_defaultint(self):
1587 header = self.resp.getheader('No-Such-Header',default=42)
1588 self.assertEqual(header, 42)
1589
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001590class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001591 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001592 response_text = (
1593 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1594 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1595 'Content-Length: 42\r\n\r\n'
1596 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001597 self.host = 'proxy.com'
1598 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001599 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001600
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001601 def tearDown(self):
1602 self.conn.close()
1603
Berker Peksagab53ab02015-02-03 12:22:11 +02001604 def _create_connection(self, response_text):
1605 def create_connection(address, timeout=None, source_address=None):
1606 return FakeSocket(response_text, host=address[0], port=address[1])
1607 return create_connection
1608
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001609 def test_set_tunnel_host_port_headers(self):
1610 tunnel_host = 'destination.com'
1611 tunnel_port = 8888
1612 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1613 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1614 headers=tunnel_headers)
1615 self.conn.request('HEAD', '/', '')
1616 self.assertEqual(self.conn.sock.host, self.host)
1617 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1618 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1619 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1620 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1621
1622 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001623 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001624 self.conn.connect()
1625 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001626 'destination.com')
1627
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001628 def test_connect_with_tunnel(self):
1629 self.conn.set_tunnel('destination.com')
1630 self.conn.request('HEAD', '/', '')
1631 self.assertEqual(self.conn.sock.host, self.host)
1632 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1633 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001634 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001635 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1636 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001637
1638 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001639 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001640
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001641 def test_connect_put_request(self):
1642 self.conn.set_tunnel('destination.com')
1643 self.conn.request('PUT', '/', '')
1644 self.assertEqual(self.conn.sock.host, self.host)
1645 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1646 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1647 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1648
Berker Peksagab53ab02015-02-03 12:22:11 +02001649 def test_tunnel_debuglog(self):
1650 expected_header = 'X-Dummy: 1'
1651 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1652
1653 self.conn.set_debuglevel(1)
1654 self.conn._create_connection = self._create_connection(response_text)
1655 self.conn.set_tunnel('destination.com')
1656
1657 with support.captured_stdout() as output:
1658 self.conn.request('PUT', '/', '')
1659 lines = output.getvalue().splitlines()
1660 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001661
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001662
Benjamin Peterson9566de12014-12-13 16:13:24 -05001663@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001664def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001665 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
R David Murraycae7bdb2015-04-05 19:26:29 -04001666 PersistenceTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001667 HTTPSTest, RequestBodyTest, SourceAddressTest,
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001668 HTTPResponseTest, ExtendedReadTest,
Senthil Kumaran166214c2014-04-14 13:10:05 -04001669 ExtendedReadTestChunked, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001670
Thomas Wouters89f507f2006-12-13 04:49:30 +00001671if __name__ == '__main__':
1672 test_main()