blob: f45e352d6af098d32537eaf8a072dc5a744cd049 [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):
Martin Panter8d56c022016-05-29 04:13:35 +0000258 # Default host header on IPv6 transaction should be wrapped by [] if
259 # it is an IPv6 address
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000260 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
Martin Panterd979b2c2016-04-09 14:03:17 +0000918 def test_response_fileno(self):
919 # Make sure fd returned by fileno is valid.
920 threading = support.import_module("threading")
921
922 serv = socket.socket(
923 socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
924 self.addCleanup(serv.close)
925 serv.bind((HOST, 0))
926 serv.listen()
927
928 result = None
929 def run_server():
930 [conn, address] = serv.accept()
931 with conn, conn.makefile("rb") as reader:
932 # Read the request header until a blank line
933 while True:
934 line = reader.readline()
935 if not line.rstrip(b"\r\n"):
936 break
937 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
938 nonlocal result
939 result = reader.read()
940
941 thread = threading.Thread(target=run_server)
942 thread.start()
943 conn = client.HTTPConnection(*serv.getsockname())
944 conn.request("CONNECT", "dummy:1234")
945 response = conn.getresponse()
946 try:
947 self.assertEqual(response.status, client.OK)
948 s = socket.socket(fileno=response.fileno())
949 try:
950 s.sendall(b"proxied data\n")
951 finally:
952 s.detach()
953 finally:
954 response.close()
955 conn.close()
956 thread.join()
957 self.assertEqual(result, b"proxied data\n")
958
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000959class ExtendedReadTest(TestCase):
960 """
961 Test peek(), read1(), readline()
962 """
963 lines = (
964 'HTTP/1.1 200 OK\r\n'
965 '\r\n'
966 'hello world!\n'
967 'and now \n'
968 'for something completely different\n'
969 'foo'
970 )
971 lines_expected = lines[lines.find('hello'):].encode("ascii")
972 lines_chunked = (
973 'HTTP/1.1 200 OK\r\n'
974 'Transfer-Encoding: chunked\r\n\r\n'
975 'a\r\n'
976 'hello worl\r\n'
977 '3\r\n'
978 'd!\n\r\n'
979 '9\r\n'
980 'and now \n\r\n'
981 '23\r\n'
982 'for something completely different\n\r\n'
983 '3\r\n'
984 'foo\r\n'
985 '0\r\n' # terminating chunk
986 '\r\n' # end of trailers
987 )
988
989 def setUp(self):
990 sock = FakeSocket(self.lines)
991 resp = client.HTTPResponse(sock, method="GET")
992 resp.begin()
993 resp.fp = io.BufferedReader(resp.fp)
994 self.resp = resp
995
996
997
998 def test_peek(self):
999 resp = self.resp
1000 # patch up the buffered peek so that it returns not too much stuff
1001 oldpeek = resp.fp.peek
1002 def mypeek(n=-1):
1003 p = oldpeek(n)
1004 if n >= 0:
1005 return p[:n]
1006 return p[:10]
1007 resp.fp.peek = mypeek
1008
1009 all = []
1010 while True:
1011 # try a short peek
1012 p = resp.peek(3)
1013 if p:
1014 self.assertGreater(len(p), 0)
1015 # then unbounded peek
1016 p2 = resp.peek()
1017 self.assertGreaterEqual(len(p2), len(p))
1018 self.assertTrue(p2.startswith(p))
1019 next = resp.read(len(p2))
1020 self.assertEqual(next, p2)
1021 else:
1022 next = resp.read()
1023 self.assertFalse(next)
1024 all.append(next)
1025 if not next:
1026 break
1027 self.assertEqual(b"".join(all), self.lines_expected)
1028
1029 def test_readline(self):
1030 resp = self.resp
1031 self._verify_readline(self.resp.readline, self.lines_expected)
1032
1033 def _verify_readline(self, readline, expected):
1034 all = []
1035 while True:
1036 # short readlines
1037 line = readline(5)
1038 if line and line != b"foo":
1039 if len(line) < 5:
1040 self.assertTrue(line.endswith(b"\n"))
1041 all.append(line)
1042 if not line:
1043 break
1044 self.assertEqual(b"".join(all), expected)
1045
1046 def test_read1(self):
1047 resp = self.resp
1048 def r():
1049 res = resp.read1(4)
1050 self.assertLessEqual(len(res), 4)
1051 return res
1052 readliner = Readliner(r)
1053 self._verify_readline(readliner.readline, self.lines_expected)
1054
1055 def test_read1_unbounded(self):
1056 resp = self.resp
1057 all = []
1058 while True:
1059 data = resp.read1()
1060 if not data:
1061 break
1062 all.append(data)
1063 self.assertEqual(b"".join(all), self.lines_expected)
1064
1065 def test_read1_bounded(self):
1066 resp = self.resp
1067 all = []
1068 while True:
1069 data = resp.read1(10)
1070 if not data:
1071 break
1072 self.assertLessEqual(len(data), 10)
1073 all.append(data)
1074 self.assertEqual(b"".join(all), self.lines_expected)
1075
1076 def test_read1_0(self):
1077 self.assertEqual(self.resp.read1(0), b"")
1078
1079 def test_peek_0(self):
1080 p = self.resp.peek(0)
1081 self.assertLessEqual(0, len(p))
1082
1083class ExtendedReadTestChunked(ExtendedReadTest):
1084 """
1085 Test peek(), read1(), readline() in chunked mode
1086 """
1087 lines = (
1088 'HTTP/1.1 200 OK\r\n'
1089 'Transfer-Encoding: chunked\r\n\r\n'
1090 'a\r\n'
1091 'hello worl\r\n'
1092 '3\r\n'
1093 'd!\n\r\n'
1094 '9\r\n'
1095 'and now \n\r\n'
1096 '23\r\n'
1097 'for something completely different\n\r\n'
1098 '3\r\n'
1099 'foo\r\n'
1100 '0\r\n' # terminating chunk
1101 '\r\n' # end of trailers
1102 )
1103
1104
1105class Readliner:
1106 """
1107 a simple readline class that uses an arbitrary read function and buffering
1108 """
1109 def __init__(self, readfunc):
1110 self.readfunc = readfunc
1111 self.remainder = b""
1112
1113 def readline(self, limit):
1114 data = []
1115 datalen = 0
1116 read = self.remainder
1117 try:
1118 while True:
1119 idx = read.find(b'\n')
1120 if idx != -1:
1121 break
1122 if datalen + len(read) >= limit:
1123 idx = limit - datalen - 1
1124 # read more data
1125 data.append(read)
1126 read = self.readfunc()
1127 if not read:
1128 idx = 0 #eof condition
1129 break
1130 idx += 1
1131 data.append(read[:idx])
1132 self.remainder = read[idx:]
1133 return b"".join(data)
1134 except:
1135 self.remainder = b"".join(data)
1136 raise
1137
Berker Peksagbabc6882015-02-20 09:39:38 +02001138
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001139class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001140 def test_all(self):
1141 # Documented objects defined in the module should be in __all__
1142 expected = {"responses"} # White-list documented dict() object
1143 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1144 # intentionally omitted for simplicity
1145 blacklist = {"HTTPMessage", "parse_headers"}
1146 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001147 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001148 continue
1149 module_object = getattr(client, name)
1150 if getattr(module_object, "__module__", None) == "http.client":
1151 expected.add(name)
1152 self.assertCountEqual(client.__all__, expected)
1153
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001154 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001155 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001156
Berker Peksagabbf0f42015-02-20 14:57:31 +02001157 def test_client_constants(self):
1158 # Make sure we don't break backward compatibility with 3.4
1159 expected = [
1160 'CONTINUE',
1161 'SWITCHING_PROTOCOLS',
1162 'PROCESSING',
1163 'OK',
1164 'CREATED',
1165 'ACCEPTED',
1166 'NON_AUTHORITATIVE_INFORMATION',
1167 'NO_CONTENT',
1168 'RESET_CONTENT',
1169 'PARTIAL_CONTENT',
1170 'MULTI_STATUS',
1171 'IM_USED',
1172 'MULTIPLE_CHOICES',
1173 'MOVED_PERMANENTLY',
1174 'FOUND',
1175 'SEE_OTHER',
1176 'NOT_MODIFIED',
1177 'USE_PROXY',
1178 'TEMPORARY_REDIRECT',
1179 'BAD_REQUEST',
1180 'UNAUTHORIZED',
1181 'PAYMENT_REQUIRED',
1182 'FORBIDDEN',
1183 'NOT_FOUND',
1184 'METHOD_NOT_ALLOWED',
1185 'NOT_ACCEPTABLE',
1186 'PROXY_AUTHENTICATION_REQUIRED',
1187 'REQUEST_TIMEOUT',
1188 'CONFLICT',
1189 'GONE',
1190 'LENGTH_REQUIRED',
1191 'PRECONDITION_FAILED',
1192 'REQUEST_ENTITY_TOO_LARGE',
1193 'REQUEST_URI_TOO_LONG',
1194 'UNSUPPORTED_MEDIA_TYPE',
1195 'REQUESTED_RANGE_NOT_SATISFIABLE',
1196 'EXPECTATION_FAILED',
1197 'UNPROCESSABLE_ENTITY',
1198 'LOCKED',
1199 'FAILED_DEPENDENCY',
1200 'UPGRADE_REQUIRED',
1201 'PRECONDITION_REQUIRED',
1202 'TOO_MANY_REQUESTS',
1203 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1204 'INTERNAL_SERVER_ERROR',
1205 'NOT_IMPLEMENTED',
1206 'BAD_GATEWAY',
1207 'SERVICE_UNAVAILABLE',
1208 'GATEWAY_TIMEOUT',
1209 'HTTP_VERSION_NOT_SUPPORTED',
1210 'INSUFFICIENT_STORAGE',
1211 'NOT_EXTENDED',
1212 'NETWORK_AUTHENTICATION_REQUIRED',
1213 ]
1214 for const in expected:
1215 with self.subTest(constant=const):
1216 self.assertTrue(hasattr(client, const))
1217
Gregory P. Smithb4066372010-01-03 03:28:29 +00001218
1219class SourceAddressTest(TestCase):
1220 def setUp(self):
1221 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1222 self.port = support.bind_port(self.serv)
1223 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001224 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001225 self.conn = None
1226
1227 def tearDown(self):
1228 if self.conn:
1229 self.conn.close()
1230 self.conn = None
1231 self.serv.close()
1232 self.serv = None
1233
1234 def testHTTPConnectionSourceAddress(self):
1235 self.conn = client.HTTPConnection(HOST, self.port,
1236 source_address=('', self.source_port))
1237 self.conn.connect()
1238 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1239
1240 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1241 'http.client.HTTPSConnection not defined')
1242 def testHTTPSConnectionSourceAddress(self):
1243 self.conn = client.HTTPSConnection(HOST, self.port,
1244 source_address=('', self.source_port))
1245 # We don't test anything here other the constructor not barfing as
1246 # this code doesn't deal with setting up an active running SSL server
1247 # for an ssl_wrapped connect() to actually return from.
1248
1249
Guido van Rossumd8faa362007-04-27 19:54:29 +00001250class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001251 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001252
1253 def setUp(self):
1254 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001255 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001256 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001257
1258 def tearDown(self):
1259 self.serv.close()
1260 self.serv = None
1261
1262 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001263 # This will prove that the timeout gets through HTTPConnection
1264 # and into the socket.
1265
Georg Brandlf78e02b2008-06-10 17:40:04 +00001266 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001267 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001268 socket.setdefaulttimeout(30)
1269 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001270 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001271 httpConn.connect()
1272 finally:
1273 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001274 self.assertEqual(httpConn.sock.gettimeout(), 30)
1275 httpConn.close()
1276
Georg Brandlf78e02b2008-06-10 17:40:04 +00001277 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001278 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001279 socket.setdefaulttimeout(30)
1280 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001281 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001282 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001283 httpConn.connect()
1284 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001285 socket.setdefaulttimeout(None)
1286 self.assertEqual(httpConn.sock.gettimeout(), None)
1287 httpConn.close()
1288
1289 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001290 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001291 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001292 self.assertEqual(httpConn.sock.gettimeout(), 30)
1293 httpConn.close()
1294
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001295
R David Murraycae7bdb2015-04-05 19:26:29 -04001296class PersistenceTest(TestCase):
1297
1298 def test_reuse_reconnect(self):
1299 # Should reuse or reconnect depending on header from server
1300 tests = (
1301 ('1.0', '', False),
1302 ('1.0', 'Connection: keep-alive\r\n', True),
1303 ('1.1', '', True),
1304 ('1.1', 'Connection: close\r\n', False),
1305 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1306 ('1.1', 'Connection: cloSE\r\n', False),
1307 )
1308 for version, header, reuse in tests:
1309 with self.subTest(version=version, header=header):
1310 msg = (
1311 'HTTP/{} 200 OK\r\n'
1312 '{}'
1313 'Content-Length: 12\r\n'
1314 '\r\n'
1315 'Dummy body\r\n'
1316 ).format(version, header)
1317 conn = FakeSocketHTTPConnection(msg)
1318 self.assertIsNone(conn.sock)
1319 conn.request('GET', '/open-connection')
1320 with conn.getresponse() as response:
1321 self.assertEqual(conn.sock is None, not reuse)
1322 response.read()
1323 self.assertEqual(conn.sock is None, not reuse)
1324 self.assertEqual(conn.connections, 1)
1325 conn.request('GET', '/subsequent-request')
1326 self.assertEqual(conn.connections, 1 if reuse else 2)
1327
1328 def test_disconnected(self):
1329
1330 def make_reset_reader(text):
1331 """Return BufferedReader that raises ECONNRESET at EOF"""
1332 stream = io.BytesIO(text)
1333 def readinto(buffer):
1334 size = io.BytesIO.readinto(stream, buffer)
1335 if size == 0:
1336 raise ConnectionResetError()
1337 return size
1338 stream.readinto = readinto
1339 return io.BufferedReader(stream)
1340
1341 tests = (
1342 (io.BytesIO, client.RemoteDisconnected),
1343 (make_reset_reader, ConnectionResetError),
1344 )
1345 for stream_factory, exception in tests:
1346 with self.subTest(exception=exception):
1347 conn = FakeSocketHTTPConnection(b'', stream_factory)
1348 conn.request('GET', '/eof-response')
1349 self.assertRaises(exception, conn.getresponse)
1350 self.assertIsNone(conn.sock)
1351 # HTTPConnection.connect() should be automatically invoked
1352 conn.request('GET', '/reconnect')
1353 self.assertEqual(conn.connections, 2)
1354
1355 def test_100_close(self):
1356 conn = FakeSocketHTTPConnection(
1357 b'HTTP/1.1 100 Continue\r\n'
1358 b'\r\n'
1359 # Missing final response
1360 )
1361 conn.request('GET', '/', headers={'Expect': '100-continue'})
1362 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1363 self.assertIsNone(conn.sock)
1364 conn.request('GET', '/reconnect')
1365 self.assertEqual(conn.connections, 2)
1366
1367
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001368class HTTPSTest(TestCase):
1369
1370 def setUp(self):
1371 if not hasattr(client, 'HTTPSConnection'):
1372 self.skipTest('ssl support required')
1373
1374 def make_server(self, certfile):
1375 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001376 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001377
1378 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001379 # simple test to check it's storing the timeout
1380 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1381 self.assertEqual(h.timeout, 30)
1382
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001383 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001384 # Default settings: requires a valid cert from a trusted CA
1385 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001386 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001387 with support.transient_internet('self-signed.pythontest.net'):
1388 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1389 with self.assertRaises(ssl.SSLError) as exc_info:
1390 h.request('GET', '/')
1391 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1392
1393 def test_networked_noverification(self):
1394 # Switch off cert verification
1395 import ssl
1396 support.requires('network')
1397 with support.transient_internet('self-signed.pythontest.net'):
1398 context = ssl._create_unverified_context()
1399 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1400 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001401 h.request('GET', '/')
1402 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001403 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001404 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001405 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001406
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001407 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001408 def test_networked_trusted_by_default_cert(self):
1409 # Default settings: requires a valid cert from a trusted CA
1410 support.requires('network')
1411 with support.transient_internet('www.python.org'):
1412 h = client.HTTPSConnection('www.python.org', 443)
1413 h.request('GET', '/')
1414 resp = h.getresponse()
1415 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001416 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001417 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001418 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001419
1420 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001421 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001422 import ssl
1423 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +01001424 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001425 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1426 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +01001427 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
1428 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001429 h.request('GET', '/')
1430 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001431 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001432 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001433 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001434 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001435
1436 def test_networked_bad_cert(self):
1437 # We feed a "CA" cert that is unrelated to the server's cert
1438 import ssl
1439 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001440 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001441 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1442 context.verify_mode = ssl.CERT_REQUIRED
1443 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001444 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1445 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001446 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001447 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1448
1449 def test_local_unknown_cert(self):
1450 # The custom cert isn't known to the default trust bundle
1451 import ssl
1452 server = self.make_server(CERT_localhost)
1453 h = client.HTTPSConnection('localhost', server.port)
1454 with self.assertRaises(ssl.SSLError) as exc_info:
1455 h.request('GET', '/')
1456 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001457
1458 def test_local_good_hostname(self):
1459 # The (valid) cert validates the HTTP hostname
1460 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001461 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001462 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1463 context.verify_mode = ssl.CERT_REQUIRED
1464 context.load_verify_locations(CERT_localhost)
1465 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001466 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001467 h.request('GET', '/nonexistent')
1468 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001469 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001470 self.assertEqual(resp.status, 404)
1471
1472 def test_local_bad_hostname(self):
1473 # The (valid) cert doesn't validate the HTTP hostname
1474 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001475 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001476 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1477 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -05001478 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001479 context.load_verify_locations(CERT_fakehostname)
1480 h = client.HTTPSConnection('localhost', server.port, context=context)
1481 with self.assertRaises(ssl.CertificateError):
1482 h.request('GET', '/')
1483 # Same with explicit check_hostname=True
1484 h = client.HTTPSConnection('localhost', server.port, context=context,
1485 check_hostname=True)
1486 with self.assertRaises(ssl.CertificateError):
1487 h.request('GET', '/')
1488 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001489 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001490 h = client.HTTPSConnection('localhost', server.port, context=context,
1491 check_hostname=False)
1492 h.request('GET', '/nonexistent')
1493 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001494 resp.close()
1495 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001496 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001497 # The context's check_hostname setting is used if one isn't passed to
1498 # HTTPSConnection.
1499 context.check_hostname = False
1500 h = client.HTTPSConnection('localhost', server.port, context=context)
1501 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001502 resp = h.getresponse()
1503 self.assertEqual(resp.status, 404)
1504 resp.close()
1505 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001506 # Passing check_hostname to HTTPSConnection should override the
1507 # context's setting.
1508 h = client.HTTPSConnection('localhost', server.port, context=context,
1509 check_hostname=True)
1510 with self.assertRaises(ssl.CertificateError):
1511 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001512
Petri Lehtinene119c402011-10-26 21:29:15 +03001513 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1514 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001515 def test_host_port(self):
1516 # Check invalid host_port
1517
1518 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1519 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1520
1521 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1522 "fe80::207:e9ff:fe9b", 8000),
1523 ("www.python.org:443", "www.python.org", 443),
1524 ("www.python.org:", "www.python.org", 443),
1525 ("www.python.org", "www.python.org", 443),
1526 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1527 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1528 443)):
1529 c = client.HTTPSConnection(hp)
1530 self.assertEqual(h, c.host)
1531 self.assertEqual(p, c.port)
1532
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001533
Jeremy Hylton236654b2009-03-27 20:24:34 +00001534class RequestBodyTest(TestCase):
1535 """Test cases where a request includes a message body."""
1536
1537 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001538 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001539 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001540 self.conn.sock = self.sock
1541
1542 def get_headers_and_fp(self):
1543 f = io.BytesIO(self.sock.data)
1544 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001545 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001546 return message, f
1547
1548 def test_manual_content_length(self):
1549 # Set an incorrect content-length so that we can verify that
1550 # it will not be over-ridden by the library.
1551 self.conn.request("PUT", "/url", "body",
1552 {"Content-Length": "42"})
1553 message, f = self.get_headers_and_fp()
1554 self.assertEqual("42", message.get("content-length"))
1555 self.assertEqual(4, len(f.read()))
1556
1557 def test_ascii_body(self):
1558 self.conn.request("PUT", "/url", "body")
1559 message, f = self.get_headers_and_fp()
1560 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001561 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001562 self.assertEqual("4", message.get("content-length"))
1563 self.assertEqual(b'body', f.read())
1564
1565 def test_latin1_body(self):
1566 self.conn.request("PUT", "/url", "body\xc1")
1567 message, f = self.get_headers_and_fp()
1568 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001569 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001570 self.assertEqual("5", message.get("content-length"))
1571 self.assertEqual(b'body\xc1', f.read())
1572
1573 def test_bytes_body(self):
1574 self.conn.request("PUT", "/url", b"body\xc1")
1575 message, f = self.get_headers_and_fp()
1576 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001577 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001578 self.assertEqual("5", message.get("content-length"))
1579 self.assertEqual(b'body\xc1', f.read())
1580
1581 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001582 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001583 with open(support.TESTFN, "w") as f:
1584 f.write("body")
1585 with open(support.TESTFN) as f:
1586 self.conn.request("PUT", "/url", f)
1587 message, f = self.get_headers_and_fp()
1588 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001589 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001590 self.assertEqual("4", message.get("content-length"))
1591 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001592
1593 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001594 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001595 with open(support.TESTFN, "wb") as f:
1596 f.write(b"body\xc1")
1597 with open(support.TESTFN, "rb") as f:
1598 self.conn.request("PUT", "/url", f)
1599 message, f = self.get_headers_and_fp()
1600 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001601 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001602 self.assertEqual("5", message.get("content-length"))
1603 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001604
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001605
1606class HTTPResponseTest(TestCase):
1607
1608 def setUp(self):
1609 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1610 second-value\r\n\r\nText"
1611 sock = FakeSocket(body)
1612 self.resp = client.HTTPResponse(sock)
1613 self.resp.begin()
1614
1615 def test_getting_header(self):
1616 header = self.resp.getheader('My-Header')
1617 self.assertEqual(header, 'first-value, second-value')
1618
1619 header = self.resp.getheader('My-Header', 'some default')
1620 self.assertEqual(header, 'first-value, second-value')
1621
1622 def test_getting_nonexistent_header_with_string_default(self):
1623 header = self.resp.getheader('No-Such-Header', 'default-value')
1624 self.assertEqual(header, 'default-value')
1625
1626 def test_getting_nonexistent_header_with_iterable_default(self):
1627 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1628 self.assertEqual(header, 'default, values')
1629
1630 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1631 self.assertEqual(header, 'default, values')
1632
1633 def test_getting_nonexistent_header_without_default(self):
1634 header = self.resp.getheader('No-Such-Header')
1635 self.assertEqual(header, None)
1636
1637 def test_getting_header_defaultint(self):
1638 header = self.resp.getheader('No-Such-Header',default=42)
1639 self.assertEqual(header, 42)
1640
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001641class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001642 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001643 response_text = (
1644 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1645 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1646 'Content-Length: 42\r\n\r\n'
1647 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001648 self.host = 'proxy.com'
1649 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001650 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001651
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001652 def tearDown(self):
1653 self.conn.close()
1654
Berker Peksagab53ab02015-02-03 12:22:11 +02001655 def _create_connection(self, response_text):
1656 def create_connection(address, timeout=None, source_address=None):
1657 return FakeSocket(response_text, host=address[0], port=address[1])
1658 return create_connection
1659
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001660 def test_set_tunnel_host_port_headers(self):
1661 tunnel_host = 'destination.com'
1662 tunnel_port = 8888
1663 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1664 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1665 headers=tunnel_headers)
1666 self.conn.request('HEAD', '/', '')
1667 self.assertEqual(self.conn.sock.host, self.host)
1668 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1669 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1670 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1671 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1672
1673 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001674 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001675 self.conn.connect()
1676 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001677 'destination.com')
1678
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001679 def test_connect_with_tunnel(self):
1680 self.conn.set_tunnel('destination.com')
1681 self.conn.request('HEAD', '/', '')
1682 self.assertEqual(self.conn.sock.host, self.host)
1683 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1684 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001685 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001686 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1687 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001688
1689 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001690 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001691
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001692 def test_connect_put_request(self):
1693 self.conn.set_tunnel('destination.com')
1694 self.conn.request('PUT', '/', '')
1695 self.assertEqual(self.conn.sock.host, self.host)
1696 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1697 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1698 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1699
Berker Peksagab53ab02015-02-03 12:22:11 +02001700 def test_tunnel_debuglog(self):
1701 expected_header = 'X-Dummy: 1'
1702 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1703
1704 self.conn.set_debuglevel(1)
1705 self.conn._create_connection = self._create_connection(response_text)
1706 self.conn.set_tunnel('destination.com')
1707
1708 with support.captured_stdout() as output:
1709 self.conn.request('PUT', '/', '')
1710 lines = output.getvalue().splitlines()
1711 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001712
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001713
Benjamin Peterson9566de12014-12-13 16:13:24 -05001714@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001715def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001716 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
R David Murraycae7bdb2015-04-05 19:26:29 -04001717 PersistenceTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001718 HTTPSTest, RequestBodyTest, SourceAddressTest,
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001719 HTTPResponseTest, ExtendedReadTest,
Senthil Kumaran166214c2014-04-14 13:10:05 -04001720 ExtendedReadTestChunked, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001721
Thomas Wouters89f507f2006-12-13 04:49:30 +00001722if __name__ == '__main__':
1723 test_main()