blob: d809414b6370c85c5984c018525214107d891f77 [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):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100344 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000345 # same behaviour than when we read the whole thing with read()
346 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
Antoine Pitrou38d96432011-12-06 22:33:57 +0100358 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100359 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100360 # same behaviour than when we read the whole thing with read()
361 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
362 sock = FakeSocket(body)
363 resp = client.HTTPResponse(sock)
364 resp.begin()
365 b = bytearray(2)
366 n = resp.readinto(b)
367 self.assertEqual(n, 2)
368 self.assertEqual(bytes(b), b'Te')
369 self.assertFalse(resp.isclosed())
370 n = resp.readinto(b)
371 self.assertEqual(n, 2)
372 self.assertEqual(bytes(b), b'xt')
373 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200374 self.assertFalse(resp.closed)
375 resp.close()
376 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100377
Antoine Pitrou084daa22012-12-15 19:11:54 +0100378 def test_partial_reads_no_content_length(self):
379 # when no length is present, the socket should be gracefully closed when
380 # all data was read
381 body = "HTTP/1.1 200 Ok\r\n\r\nText"
382 sock = FakeSocket(body)
383 resp = client.HTTPResponse(sock)
384 resp.begin()
385 self.assertEqual(resp.read(2), b'Te')
386 self.assertFalse(resp.isclosed())
387 self.assertEqual(resp.read(2), b'xt')
388 self.assertEqual(resp.read(1), b'')
389 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200390 self.assertFalse(resp.closed)
391 resp.close()
392 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100393
Antoine Pitroud20e7742012-12-15 19:22:30 +0100394 def test_partial_readintos_no_content_length(self):
395 # when no length is present, the socket should be gracefully closed when
396 # all data was read
397 body = "HTTP/1.1 200 Ok\r\n\r\nText"
398 sock = FakeSocket(body)
399 resp = client.HTTPResponse(sock)
400 resp.begin()
401 b = bytearray(2)
402 n = resp.readinto(b)
403 self.assertEqual(n, 2)
404 self.assertEqual(bytes(b), b'Te')
405 self.assertFalse(resp.isclosed())
406 n = resp.readinto(b)
407 self.assertEqual(n, 2)
408 self.assertEqual(bytes(b), b'xt')
409 n = resp.readinto(b)
410 self.assertEqual(n, 0)
411 self.assertTrue(resp.isclosed())
412
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100413 def test_partial_reads_incomplete_body(self):
414 # if the server shuts down the connection before the whole
415 # content-length is delivered, the socket is gracefully closed
416 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
417 sock = FakeSocket(body)
418 resp = client.HTTPResponse(sock)
419 resp.begin()
420 self.assertEqual(resp.read(2), b'Te')
421 self.assertFalse(resp.isclosed())
422 self.assertEqual(resp.read(2), b'xt')
423 self.assertEqual(resp.read(1), b'')
424 self.assertTrue(resp.isclosed())
425
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100426 def test_partial_readintos_incomplete_body(self):
427 # if the server shuts down the connection before the whole
428 # content-length is delivered, the socket is gracefully closed
429 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
430 sock = FakeSocket(body)
431 resp = client.HTTPResponse(sock)
432 resp.begin()
433 b = bytearray(2)
434 n = resp.readinto(b)
435 self.assertEqual(n, 2)
436 self.assertEqual(bytes(b), b'Te')
437 self.assertFalse(resp.isclosed())
438 n = resp.readinto(b)
439 self.assertEqual(n, 2)
440 self.assertEqual(bytes(b), b'xt')
441 n = resp.readinto(b)
442 self.assertEqual(n, 0)
443 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200444 self.assertFalse(resp.closed)
445 resp.close()
446 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100447
Thomas Wouters89f507f2006-12-13 04:49:30 +0000448 def test_host_port(self):
449 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000450
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200451 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000452 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000454 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
455 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200457 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000458 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200459 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
460 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000461 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000462 self.assertEqual(h, c.host)
463 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000464
Thomas Wouters89f507f2006-12-13 04:49:30 +0000465 def test_response_headers(self):
466 # test response with multiple message headers with the same field name.
467 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000468 'Set-Cookie: Customer="WILE_E_COYOTE"; '
469 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000470 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
471 ' Path="/acme"\r\n'
472 '\r\n'
473 'No body\r\n')
474 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
475 ', '
476 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
477 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000478 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000479 r.begin()
480 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000481 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000482
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483 def test_read_head(self):
484 # Test that the library doesn't attempt to read any data
485 # from a HEAD request. (Tickles SF bug #622042.)
486 sock = FakeSocket(
487 'HTTP/1.1 200 OK\r\n'
488 'Content-Length: 14432\r\n'
489 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300490 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000491 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000492 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000493 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000494 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000495
Antoine Pitrou38d96432011-12-06 22:33:57 +0100496 def test_readinto_head(self):
497 # Test that the library doesn't attempt to read any data
498 # from a HEAD request. (Tickles SF bug #622042.)
499 sock = FakeSocket(
500 'HTTP/1.1 200 OK\r\n'
501 'Content-Length: 14432\r\n'
502 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300503 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100504 resp = client.HTTPResponse(sock, method="HEAD")
505 resp.begin()
506 b = bytearray(5)
507 if resp.readinto(b) != 0:
508 self.fail("Did not expect response from HEAD request")
509 self.assertEqual(bytes(b), b'\x00'*5)
510
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100511 def test_too_many_headers(self):
512 headers = '\r\n'.join('Header%d: foo' % i
513 for i in range(client._MAXHEADERS + 1)) + '\r\n'
514 text = ('HTTP/1.1 200 OK\r\n' + headers)
515 s = FakeSocket(text)
516 r = client.HTTPResponse(s)
517 self.assertRaisesRegex(client.HTTPException,
518 r"got more than \d+ headers", r.begin)
519
Thomas Wouters89f507f2006-12-13 04:49:30 +0000520 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000521 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
522 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000523
Brett Cannon77b7de62010-10-29 23:31:11 +0000524 with open(__file__, 'rb') as body:
525 conn = client.HTTPConnection('example.com')
526 sock = FakeSocket(body)
527 conn.sock = sock
528 conn.request('GET', '/foo', body)
529 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
530 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000531
Antoine Pitrouead1d622009-09-29 18:44:53 +0000532 def test_send(self):
533 expected = b'this is a test this is only a test'
534 conn = client.HTTPConnection('example.com')
535 sock = FakeSocket(None)
536 conn.sock = sock
537 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000538 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000539 sock.data = b''
540 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000541 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000542 sock.data = b''
543 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000544 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000545
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300546 def test_send_updating_file(self):
547 def data():
548 yield 'data'
549 yield None
550 yield 'data_two'
551
552 class UpdatingFile():
553 mode = 'r'
554 d = data()
555 def read(self, blocksize=-1):
556 return self.d.__next__()
557
558 expected = b'data'
559
560 conn = client.HTTPConnection('example.com')
561 sock = FakeSocket("")
562 conn.sock = sock
563 conn.send(UpdatingFile())
564 self.assertEqual(sock.data, expected)
565
566
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000567 def test_send_iter(self):
568 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
569 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
570 b'\r\nonetwothree'
571
572 def body():
573 yield b"one"
574 yield b"two"
575 yield b"three"
576
577 conn = client.HTTPConnection('example.com')
578 sock = FakeSocket("")
579 conn.sock = sock
580 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000581 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000582
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800583 def test_send_type_error(self):
584 # See: Issue #12676
585 conn = client.HTTPConnection('example.com')
586 conn.sock = FakeSocket('')
587 with self.assertRaises(TypeError):
588 conn.request('POST', 'test', conn)
589
Christian Heimesa612dc02008-02-24 13:08:18 +0000590 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000591 expected = chunked_expected
592 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000593 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000594 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100595 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000596 resp.close()
597
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100598 # Various read sizes
599 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000600 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100601 resp = client.HTTPResponse(sock, method="GET")
602 resp.begin()
603 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
604 resp.close()
605
Christian Heimesa612dc02008-02-24 13:08:18 +0000606 for x in ('', 'foo\r\n'):
607 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000608 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000609 resp.begin()
610 try:
611 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000612 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100613 self.assertEqual(i.partial, expected)
614 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
615 self.assertEqual(repr(i), expected_message)
616 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000617 else:
618 self.fail('IncompleteRead expected')
619 finally:
620 resp.close()
621
Antoine Pitrou38d96432011-12-06 22:33:57 +0100622 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000623
624 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100625 nexpected = len(expected)
626 b = bytearray(128)
627
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000628 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100629 resp = client.HTTPResponse(sock, method="GET")
630 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100631 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100632 self.assertEqual(b[:nexpected], expected)
633 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100634 resp.close()
635
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100636 # Various read sizes
637 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000638 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100639 resp = client.HTTPResponse(sock, method="GET")
640 resp.begin()
641 m = memoryview(b)
642 i = resp.readinto(m[0:n])
643 i += resp.readinto(m[i:n + i])
644 i += resp.readinto(m[i:])
645 self.assertEqual(b[:nexpected], expected)
646 self.assertEqual(i, nexpected)
647 resp.close()
648
Antoine Pitrou38d96432011-12-06 22:33:57 +0100649 for x in ('', 'foo\r\n'):
650 sock = FakeSocket(chunked_start + x)
651 resp = client.HTTPResponse(sock, method="GET")
652 resp.begin()
653 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100654 n = resp.readinto(b)
655 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100656 self.assertEqual(i.partial, expected)
657 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
658 self.assertEqual(repr(i), expected_message)
659 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100660 else:
661 self.fail('IncompleteRead expected')
662 finally:
663 resp.close()
664
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000665 def test_chunked_head(self):
666 chunked_start = (
667 'HTTP/1.1 200 OK\r\n'
668 'Transfer-Encoding: chunked\r\n\r\n'
669 'a\r\n'
670 'hello world\r\n'
671 '1\r\n'
672 'd\r\n'
673 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000674 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000675 resp = client.HTTPResponse(sock, method="HEAD")
676 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000677 self.assertEqual(resp.read(), b'')
678 self.assertEqual(resp.status, 200)
679 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000680 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200681 self.assertFalse(resp.closed)
682 resp.close()
683 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000684
Antoine Pitrou38d96432011-12-06 22:33:57 +0100685 def test_readinto_chunked_head(self):
686 chunked_start = (
687 'HTTP/1.1 200 OK\r\n'
688 'Transfer-Encoding: chunked\r\n\r\n'
689 'a\r\n'
690 'hello world\r\n'
691 '1\r\n'
692 'd\r\n'
693 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000694 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100695 resp = client.HTTPResponse(sock, method="HEAD")
696 resp.begin()
697 b = bytearray(5)
698 n = resp.readinto(b)
699 self.assertEqual(n, 0)
700 self.assertEqual(bytes(b), b'\x00'*5)
701 self.assertEqual(resp.status, 200)
702 self.assertEqual(resp.reason, 'OK')
703 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200704 self.assertFalse(resp.closed)
705 resp.close()
706 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100707
Christian Heimesa612dc02008-02-24 13:08:18 +0000708 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000709 sock = FakeSocket(
710 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000711 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000712 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000713 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100714 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000715
Benjamin Peterson6accb982009-03-02 22:50:25 +0000716 def test_incomplete_read(self):
717 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000718 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000719 resp.begin()
720 try:
721 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000722 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000723 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000724 self.assertEqual(repr(i),
725 "IncompleteRead(7 bytes read, 3 more expected)")
726 self.assertEqual(str(i),
727 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100728 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000729 else:
730 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000731
Jeremy Hylton636950f2009-03-28 04:34:21 +0000732 def test_epipe(self):
733 sock = EPipeSocket(
734 "HTTP/1.0 401 Authorization Required\r\n"
735 "Content-type: text/html\r\n"
736 "WWW-Authenticate: Basic realm=\"example\"\r\n",
737 b"Content-Length")
738 conn = client.HTTPConnection("example.com")
739 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200740 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000741 lambda: conn.request("PUT", "/url", "body"))
742 resp = conn.getresponse()
743 self.assertEqual(401, resp.status)
744 self.assertEqual("Basic realm=\"example\"",
745 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000746
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000747 # Test lines overflowing the max line size (_MAXLINE in http.client)
748
749 def test_overflowing_status_line(self):
750 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
751 resp = client.HTTPResponse(FakeSocket(body))
752 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
753
754 def test_overflowing_header_line(self):
755 body = (
756 'HTTP/1.1 200 OK\r\n'
757 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
758 )
759 resp = client.HTTPResponse(FakeSocket(body))
760 self.assertRaises(client.LineTooLong, resp.begin)
761
762 def test_overflowing_chunked_line(self):
763 body = (
764 'HTTP/1.1 200 OK\r\n'
765 'Transfer-Encoding: chunked\r\n\r\n'
766 + '0' * 65536 + 'a\r\n'
767 'hello world\r\n'
768 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000769 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000770 )
771 resp = client.HTTPResponse(FakeSocket(body))
772 resp.begin()
773 self.assertRaises(client.LineTooLong, resp.read)
774
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800775 def test_early_eof(self):
776 # Test httpresponse with no \r\n termination,
777 body = "HTTP/1.1 200 Ok"
778 sock = FakeSocket(body)
779 resp = client.HTTPResponse(sock)
780 resp.begin()
781 self.assertEqual(resp.read(), b'')
782 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200783 self.assertFalse(resp.closed)
784 resp.close()
785 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800786
Serhiy Storchakab491e052014-12-01 13:07:45 +0200787 def test_error_leak(self):
788 # Test that the socket is not leaked if getresponse() fails
789 conn = client.HTTPConnection('example.com')
790 response = None
791 class Response(client.HTTPResponse):
792 def __init__(self, *pos, **kw):
793 nonlocal response
794 response = self # Avoid garbage collector closing the socket
795 client.HTTPResponse.__init__(self, *pos, **kw)
796 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -0400797 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +0200798 conn.request('GET', '/')
799 self.assertRaises(client.BadStatusLine, conn.getresponse)
800 self.assertTrue(response.closed)
801 self.assertTrue(conn.sock.file_closed)
802
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000803 def test_chunked_extension(self):
804 extra = '3;foo=bar\r\n' + 'abc\r\n'
805 expected = chunked_expected + b'abc'
806
807 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
808 resp = client.HTTPResponse(sock, method="GET")
809 resp.begin()
810 self.assertEqual(resp.read(), expected)
811 resp.close()
812
813 def test_chunked_missing_end(self):
814 """some servers may serve up a short chunked encoding stream"""
815 expected = chunked_expected
816 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
817 resp = client.HTTPResponse(sock, method="GET")
818 resp.begin()
819 self.assertEqual(resp.read(), expected)
820 resp.close()
821
822 def test_chunked_trailers(self):
823 """See that trailers are read and ignored"""
824 expected = chunked_expected
825 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
826 resp = client.HTTPResponse(sock, method="GET")
827 resp.begin()
828 self.assertEqual(resp.read(), expected)
829 # we should have reached the end of the file
830 self.assertEqual(sock.file.read(100), b"") #we read to the end
831 resp.close()
832
833 def test_chunked_sync(self):
834 """Check that we don't read past the end of the chunked-encoding stream"""
835 expected = chunked_expected
836 extradata = "extradata"
837 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
838 resp = client.HTTPResponse(sock, method="GET")
839 resp.begin()
840 self.assertEqual(resp.read(), expected)
841 # the file should now have our extradata ready to be read
842 self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end
843 resp.close()
844
845 def test_content_length_sync(self):
846 """Check that we don't read past the end of the Content-Length stream"""
847 extradata = "extradata"
848 expected = b"Hello123\r\n"
849 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello123\r\n' + extradata)
850 resp = client.HTTPResponse(sock, method="GET")
851 resp.begin()
852 self.assertEqual(resp.read(), expected)
853 # the file should now have our extradata ready to be read
854 self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end
855 resp.close()
856
857class ExtendedReadTest(TestCase):
858 """
859 Test peek(), read1(), readline()
860 """
861 lines = (
862 'HTTP/1.1 200 OK\r\n'
863 '\r\n'
864 'hello world!\n'
865 'and now \n'
866 'for something completely different\n'
867 'foo'
868 )
869 lines_expected = lines[lines.find('hello'):].encode("ascii")
870 lines_chunked = (
871 'HTTP/1.1 200 OK\r\n'
872 'Transfer-Encoding: chunked\r\n\r\n'
873 'a\r\n'
874 'hello worl\r\n'
875 '3\r\n'
876 'd!\n\r\n'
877 '9\r\n'
878 'and now \n\r\n'
879 '23\r\n'
880 'for something completely different\n\r\n'
881 '3\r\n'
882 'foo\r\n'
883 '0\r\n' # terminating chunk
884 '\r\n' # end of trailers
885 )
886
887 def setUp(self):
888 sock = FakeSocket(self.lines)
889 resp = client.HTTPResponse(sock, method="GET")
890 resp.begin()
891 resp.fp = io.BufferedReader(resp.fp)
892 self.resp = resp
893
894
895
896 def test_peek(self):
897 resp = self.resp
898 # patch up the buffered peek so that it returns not too much stuff
899 oldpeek = resp.fp.peek
900 def mypeek(n=-1):
901 p = oldpeek(n)
902 if n >= 0:
903 return p[:n]
904 return p[:10]
905 resp.fp.peek = mypeek
906
907 all = []
908 while True:
909 # try a short peek
910 p = resp.peek(3)
911 if p:
912 self.assertGreater(len(p), 0)
913 # then unbounded peek
914 p2 = resp.peek()
915 self.assertGreaterEqual(len(p2), len(p))
916 self.assertTrue(p2.startswith(p))
917 next = resp.read(len(p2))
918 self.assertEqual(next, p2)
919 else:
920 next = resp.read()
921 self.assertFalse(next)
922 all.append(next)
923 if not next:
924 break
925 self.assertEqual(b"".join(all), self.lines_expected)
926
927 def test_readline(self):
928 resp = self.resp
929 self._verify_readline(self.resp.readline, self.lines_expected)
930
931 def _verify_readline(self, readline, expected):
932 all = []
933 while True:
934 # short readlines
935 line = readline(5)
936 if line and line != b"foo":
937 if len(line) < 5:
938 self.assertTrue(line.endswith(b"\n"))
939 all.append(line)
940 if not line:
941 break
942 self.assertEqual(b"".join(all), expected)
943
944 def test_read1(self):
945 resp = self.resp
946 def r():
947 res = resp.read1(4)
948 self.assertLessEqual(len(res), 4)
949 return res
950 readliner = Readliner(r)
951 self._verify_readline(readliner.readline, self.lines_expected)
952
953 def test_read1_unbounded(self):
954 resp = self.resp
955 all = []
956 while True:
957 data = resp.read1()
958 if not data:
959 break
960 all.append(data)
961 self.assertEqual(b"".join(all), self.lines_expected)
962
963 def test_read1_bounded(self):
964 resp = self.resp
965 all = []
966 while True:
967 data = resp.read1(10)
968 if not data:
969 break
970 self.assertLessEqual(len(data), 10)
971 all.append(data)
972 self.assertEqual(b"".join(all), self.lines_expected)
973
974 def test_read1_0(self):
975 self.assertEqual(self.resp.read1(0), b"")
976
977 def test_peek_0(self):
978 p = self.resp.peek(0)
979 self.assertLessEqual(0, len(p))
980
981class ExtendedReadTestChunked(ExtendedReadTest):
982 """
983 Test peek(), read1(), readline() in chunked mode
984 """
985 lines = (
986 'HTTP/1.1 200 OK\r\n'
987 'Transfer-Encoding: chunked\r\n\r\n'
988 'a\r\n'
989 'hello worl\r\n'
990 '3\r\n'
991 'd!\n\r\n'
992 '9\r\n'
993 'and now \n\r\n'
994 '23\r\n'
995 'for something completely different\n\r\n'
996 '3\r\n'
997 'foo\r\n'
998 '0\r\n' # terminating chunk
999 '\r\n' # end of trailers
1000 )
1001
1002
1003class Readliner:
1004 """
1005 a simple readline class that uses an arbitrary read function and buffering
1006 """
1007 def __init__(self, readfunc):
1008 self.readfunc = readfunc
1009 self.remainder = b""
1010
1011 def readline(self, limit):
1012 data = []
1013 datalen = 0
1014 read = self.remainder
1015 try:
1016 while True:
1017 idx = read.find(b'\n')
1018 if idx != -1:
1019 break
1020 if datalen + len(read) >= limit:
1021 idx = limit - datalen - 1
1022 # read more data
1023 data.append(read)
1024 read = self.readfunc()
1025 if not read:
1026 idx = 0 #eof condition
1027 break
1028 idx += 1
1029 data.append(read[:idx])
1030 self.remainder = read[idx:]
1031 return b"".join(data)
1032 except:
1033 self.remainder = b"".join(data)
1034 raise
1035
Berker Peksagbabc6882015-02-20 09:39:38 +02001036
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001037class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001038 def test_all(self):
1039 # Documented objects defined in the module should be in __all__
1040 expected = {"responses"} # White-list documented dict() object
1041 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1042 # intentionally omitted for simplicity
1043 blacklist = {"HTTPMessage", "parse_headers"}
1044 for name in dir(client):
1045 if name in blacklist:
1046 continue
1047 module_object = getattr(client, name)
1048 if getattr(module_object, "__module__", None) == "http.client":
1049 expected.add(name)
1050 self.assertCountEqual(client.__all__, expected)
1051
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001052 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001053 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001054
Berker Peksagabbf0f42015-02-20 14:57:31 +02001055 def test_client_constants(self):
1056 # Make sure we don't break backward compatibility with 3.4
1057 expected = [
1058 'CONTINUE',
1059 'SWITCHING_PROTOCOLS',
1060 'PROCESSING',
1061 'OK',
1062 'CREATED',
1063 'ACCEPTED',
1064 'NON_AUTHORITATIVE_INFORMATION',
1065 'NO_CONTENT',
1066 'RESET_CONTENT',
1067 'PARTIAL_CONTENT',
1068 'MULTI_STATUS',
1069 'IM_USED',
1070 'MULTIPLE_CHOICES',
1071 'MOVED_PERMANENTLY',
1072 'FOUND',
1073 'SEE_OTHER',
1074 'NOT_MODIFIED',
1075 'USE_PROXY',
1076 'TEMPORARY_REDIRECT',
1077 'BAD_REQUEST',
1078 'UNAUTHORIZED',
1079 'PAYMENT_REQUIRED',
1080 'FORBIDDEN',
1081 'NOT_FOUND',
1082 'METHOD_NOT_ALLOWED',
1083 'NOT_ACCEPTABLE',
1084 'PROXY_AUTHENTICATION_REQUIRED',
1085 'REQUEST_TIMEOUT',
1086 'CONFLICT',
1087 'GONE',
1088 'LENGTH_REQUIRED',
1089 'PRECONDITION_FAILED',
1090 'REQUEST_ENTITY_TOO_LARGE',
1091 'REQUEST_URI_TOO_LONG',
1092 'UNSUPPORTED_MEDIA_TYPE',
1093 'REQUESTED_RANGE_NOT_SATISFIABLE',
1094 'EXPECTATION_FAILED',
1095 'UNPROCESSABLE_ENTITY',
1096 'LOCKED',
1097 'FAILED_DEPENDENCY',
1098 'UPGRADE_REQUIRED',
1099 'PRECONDITION_REQUIRED',
1100 'TOO_MANY_REQUESTS',
1101 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1102 'INTERNAL_SERVER_ERROR',
1103 'NOT_IMPLEMENTED',
1104 'BAD_GATEWAY',
1105 'SERVICE_UNAVAILABLE',
1106 'GATEWAY_TIMEOUT',
1107 'HTTP_VERSION_NOT_SUPPORTED',
1108 'INSUFFICIENT_STORAGE',
1109 'NOT_EXTENDED',
1110 'NETWORK_AUTHENTICATION_REQUIRED',
1111 ]
1112 for const in expected:
1113 with self.subTest(constant=const):
1114 self.assertTrue(hasattr(client, const))
1115
Gregory P. Smithb4066372010-01-03 03:28:29 +00001116
1117class SourceAddressTest(TestCase):
1118 def setUp(self):
1119 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1120 self.port = support.bind_port(self.serv)
1121 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001122 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001123 self.conn = None
1124
1125 def tearDown(self):
1126 if self.conn:
1127 self.conn.close()
1128 self.conn = None
1129 self.serv.close()
1130 self.serv = None
1131
1132 def testHTTPConnectionSourceAddress(self):
1133 self.conn = client.HTTPConnection(HOST, self.port,
1134 source_address=('', self.source_port))
1135 self.conn.connect()
1136 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1137
1138 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1139 'http.client.HTTPSConnection not defined')
1140 def testHTTPSConnectionSourceAddress(self):
1141 self.conn = client.HTTPSConnection(HOST, self.port,
1142 source_address=('', self.source_port))
1143 # We don't test anything here other the constructor not barfing as
1144 # this code doesn't deal with setting up an active running SSL server
1145 # for an ssl_wrapped connect() to actually return from.
1146
1147
Guido van Rossumd8faa362007-04-27 19:54:29 +00001148class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001149 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001150
1151 def setUp(self):
1152 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001153 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001154 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155
1156 def tearDown(self):
1157 self.serv.close()
1158 self.serv = None
1159
1160 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001161 # This will prove that the timeout gets through HTTPConnection
1162 # and into the socket.
1163
Georg Brandlf78e02b2008-06-10 17:40:04 +00001164 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001165 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001166 socket.setdefaulttimeout(30)
1167 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001168 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001169 httpConn.connect()
1170 finally:
1171 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001172 self.assertEqual(httpConn.sock.gettimeout(), 30)
1173 httpConn.close()
1174
Georg Brandlf78e02b2008-06-10 17:40:04 +00001175 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001176 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001177 socket.setdefaulttimeout(30)
1178 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001179 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001180 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001181 httpConn.connect()
1182 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001183 socket.setdefaulttimeout(None)
1184 self.assertEqual(httpConn.sock.gettimeout(), None)
1185 httpConn.close()
1186
1187 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001188 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001189 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001190 self.assertEqual(httpConn.sock.gettimeout(), 30)
1191 httpConn.close()
1192
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001193
R David Murraycae7bdb2015-04-05 19:26:29 -04001194class PersistenceTest(TestCase):
1195
1196 def test_reuse_reconnect(self):
1197 # Should reuse or reconnect depending on header from server
1198 tests = (
1199 ('1.0', '', False),
1200 ('1.0', 'Connection: keep-alive\r\n', True),
1201 ('1.1', '', True),
1202 ('1.1', 'Connection: close\r\n', False),
1203 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1204 ('1.1', 'Connection: cloSE\r\n', False),
1205 )
1206 for version, header, reuse in tests:
1207 with self.subTest(version=version, header=header):
1208 msg = (
1209 'HTTP/{} 200 OK\r\n'
1210 '{}'
1211 'Content-Length: 12\r\n'
1212 '\r\n'
1213 'Dummy body\r\n'
1214 ).format(version, header)
1215 conn = FakeSocketHTTPConnection(msg)
1216 self.assertIsNone(conn.sock)
1217 conn.request('GET', '/open-connection')
1218 with conn.getresponse() as response:
1219 self.assertEqual(conn.sock is None, not reuse)
1220 response.read()
1221 self.assertEqual(conn.sock is None, not reuse)
1222 self.assertEqual(conn.connections, 1)
1223 conn.request('GET', '/subsequent-request')
1224 self.assertEqual(conn.connections, 1 if reuse else 2)
1225
1226 def test_disconnected(self):
1227
1228 def make_reset_reader(text):
1229 """Return BufferedReader that raises ECONNRESET at EOF"""
1230 stream = io.BytesIO(text)
1231 def readinto(buffer):
1232 size = io.BytesIO.readinto(stream, buffer)
1233 if size == 0:
1234 raise ConnectionResetError()
1235 return size
1236 stream.readinto = readinto
1237 return io.BufferedReader(stream)
1238
1239 tests = (
1240 (io.BytesIO, client.RemoteDisconnected),
1241 (make_reset_reader, ConnectionResetError),
1242 )
1243 for stream_factory, exception in tests:
1244 with self.subTest(exception=exception):
1245 conn = FakeSocketHTTPConnection(b'', stream_factory)
1246 conn.request('GET', '/eof-response')
1247 self.assertRaises(exception, conn.getresponse)
1248 self.assertIsNone(conn.sock)
1249 # HTTPConnection.connect() should be automatically invoked
1250 conn.request('GET', '/reconnect')
1251 self.assertEqual(conn.connections, 2)
1252
1253 def test_100_close(self):
1254 conn = FakeSocketHTTPConnection(
1255 b'HTTP/1.1 100 Continue\r\n'
1256 b'\r\n'
1257 # Missing final response
1258 )
1259 conn.request('GET', '/', headers={'Expect': '100-continue'})
1260 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1261 self.assertIsNone(conn.sock)
1262 conn.request('GET', '/reconnect')
1263 self.assertEqual(conn.connections, 2)
1264
1265
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001266class HTTPSTest(TestCase):
1267
1268 def setUp(self):
1269 if not hasattr(client, 'HTTPSConnection'):
1270 self.skipTest('ssl support required')
1271
1272 def make_server(self, certfile):
1273 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001274 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001275
1276 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001277 # simple test to check it's storing the timeout
1278 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1279 self.assertEqual(h.timeout, 30)
1280
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001281 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001282 # Default settings: requires a valid cert from a trusted CA
1283 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001284 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001285 with support.transient_internet('self-signed.pythontest.net'):
1286 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1287 with self.assertRaises(ssl.SSLError) as exc_info:
1288 h.request('GET', '/')
1289 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1290
1291 def test_networked_noverification(self):
1292 # Switch off cert verification
1293 import ssl
1294 support.requires('network')
1295 with support.transient_internet('self-signed.pythontest.net'):
1296 context = ssl._create_unverified_context()
1297 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1298 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001299 h.request('GET', '/')
1300 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001301 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001302 self.assertIn('nginx', resp.getheader('server'))
1303
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001304 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001305 def test_networked_trusted_by_default_cert(self):
1306 # Default settings: requires a valid cert from a trusted CA
1307 support.requires('network')
1308 with support.transient_internet('www.python.org'):
1309 h = client.HTTPSConnection('www.python.org', 443)
1310 h.request('GET', '/')
1311 resp = h.getresponse()
1312 content_type = resp.getheader('content-type')
Victor Stinnerb389b482015-02-27 17:47:23 +01001313 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001314 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001315
1316 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001317 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001318 import ssl
1319 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +01001320 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001321 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1322 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +01001323 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
1324 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001325 h.request('GET', '/')
1326 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001327 server_string = resp.getheader('server')
Victor Stinnerb389b482015-02-27 17:47:23 +01001328 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001329 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001330
1331 def test_networked_bad_cert(self):
1332 # We feed a "CA" cert that is unrelated to the server's cert
1333 import ssl
1334 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001335 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001336 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1337 context.verify_mode = ssl.CERT_REQUIRED
1338 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001339 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1340 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001341 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001342 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1343
1344 def test_local_unknown_cert(self):
1345 # The custom cert isn't known to the default trust bundle
1346 import ssl
1347 server = self.make_server(CERT_localhost)
1348 h = client.HTTPSConnection('localhost', server.port)
1349 with self.assertRaises(ssl.SSLError) as exc_info:
1350 h.request('GET', '/')
1351 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001352
1353 def test_local_good_hostname(self):
1354 # The (valid) cert validates the HTTP hostname
1355 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001356 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001357 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1358 context.verify_mode = ssl.CERT_REQUIRED
1359 context.load_verify_locations(CERT_localhost)
1360 h = client.HTTPSConnection('localhost', server.port, context=context)
1361 h.request('GET', '/nonexistent')
1362 resp = h.getresponse()
1363 self.assertEqual(resp.status, 404)
1364
1365 def test_local_bad_hostname(self):
1366 # The (valid) cert doesn't validate the HTTP hostname
1367 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001368 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001369 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1370 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -05001371 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001372 context.load_verify_locations(CERT_fakehostname)
1373 h = client.HTTPSConnection('localhost', server.port, context=context)
1374 with self.assertRaises(ssl.CertificateError):
1375 h.request('GET', '/')
1376 # Same with explicit check_hostname=True
1377 h = client.HTTPSConnection('localhost', server.port, context=context,
1378 check_hostname=True)
1379 with self.assertRaises(ssl.CertificateError):
1380 h.request('GET', '/')
1381 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001382 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001383 h = client.HTTPSConnection('localhost', server.port, context=context,
1384 check_hostname=False)
1385 h.request('GET', '/nonexistent')
1386 resp = h.getresponse()
1387 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001388 # The context's check_hostname setting is used if one isn't passed to
1389 # HTTPSConnection.
1390 context.check_hostname = False
1391 h = client.HTTPSConnection('localhost', server.port, context=context)
1392 h.request('GET', '/nonexistent')
1393 self.assertEqual(h.getresponse().status, 404)
1394 # Passing check_hostname to HTTPSConnection should override the
1395 # context's setting.
1396 h = client.HTTPSConnection('localhost', server.port, context=context,
1397 check_hostname=True)
1398 with self.assertRaises(ssl.CertificateError):
1399 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001400
Petri Lehtinene119c402011-10-26 21:29:15 +03001401 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1402 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001403 def test_host_port(self):
1404 # Check invalid host_port
1405
1406 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1407 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1408
1409 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1410 "fe80::207:e9ff:fe9b", 8000),
1411 ("www.python.org:443", "www.python.org", 443),
1412 ("www.python.org:", "www.python.org", 443),
1413 ("www.python.org", "www.python.org", 443),
1414 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1415 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1416 443)):
1417 c = client.HTTPSConnection(hp)
1418 self.assertEqual(h, c.host)
1419 self.assertEqual(p, c.port)
1420
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001421
Jeremy Hylton236654b2009-03-27 20:24:34 +00001422class RequestBodyTest(TestCase):
1423 """Test cases where a request includes a message body."""
1424
1425 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001426 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001427 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001428 self.conn.sock = self.sock
1429
1430 def get_headers_and_fp(self):
1431 f = io.BytesIO(self.sock.data)
1432 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001433 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001434 return message, f
1435
1436 def test_manual_content_length(self):
1437 # Set an incorrect content-length so that we can verify that
1438 # it will not be over-ridden by the library.
1439 self.conn.request("PUT", "/url", "body",
1440 {"Content-Length": "42"})
1441 message, f = self.get_headers_and_fp()
1442 self.assertEqual("42", message.get("content-length"))
1443 self.assertEqual(4, len(f.read()))
1444
1445 def test_ascii_body(self):
1446 self.conn.request("PUT", "/url", "body")
1447 message, f = self.get_headers_and_fp()
1448 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001449 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001450 self.assertEqual("4", message.get("content-length"))
1451 self.assertEqual(b'body', f.read())
1452
1453 def test_latin1_body(self):
1454 self.conn.request("PUT", "/url", "body\xc1")
1455 message, f = self.get_headers_and_fp()
1456 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001457 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001458 self.assertEqual("5", message.get("content-length"))
1459 self.assertEqual(b'body\xc1', f.read())
1460
1461 def test_bytes_body(self):
1462 self.conn.request("PUT", "/url", b"body\xc1")
1463 message, f = self.get_headers_and_fp()
1464 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001465 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001466 self.assertEqual("5", message.get("content-length"))
1467 self.assertEqual(b'body\xc1', f.read())
1468
1469 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001470 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001471 with open(support.TESTFN, "w") as f:
1472 f.write("body")
1473 with open(support.TESTFN) as f:
1474 self.conn.request("PUT", "/url", f)
1475 message, f = self.get_headers_and_fp()
1476 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001477 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001478 self.assertEqual("4", message.get("content-length"))
1479 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001480
1481 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001482 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001483 with open(support.TESTFN, "wb") as f:
1484 f.write(b"body\xc1")
1485 with open(support.TESTFN, "rb") as f:
1486 self.conn.request("PUT", "/url", f)
1487 message, f = self.get_headers_and_fp()
1488 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001489 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001490 self.assertEqual("5", message.get("content-length"))
1491 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001492
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001493
1494class HTTPResponseTest(TestCase):
1495
1496 def setUp(self):
1497 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1498 second-value\r\n\r\nText"
1499 sock = FakeSocket(body)
1500 self.resp = client.HTTPResponse(sock)
1501 self.resp.begin()
1502
1503 def test_getting_header(self):
1504 header = self.resp.getheader('My-Header')
1505 self.assertEqual(header, 'first-value, second-value')
1506
1507 header = self.resp.getheader('My-Header', 'some default')
1508 self.assertEqual(header, 'first-value, second-value')
1509
1510 def test_getting_nonexistent_header_with_string_default(self):
1511 header = self.resp.getheader('No-Such-Header', 'default-value')
1512 self.assertEqual(header, 'default-value')
1513
1514 def test_getting_nonexistent_header_with_iterable_default(self):
1515 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1516 self.assertEqual(header, 'default, values')
1517
1518 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1519 self.assertEqual(header, 'default, values')
1520
1521 def test_getting_nonexistent_header_without_default(self):
1522 header = self.resp.getheader('No-Such-Header')
1523 self.assertEqual(header, None)
1524
1525 def test_getting_header_defaultint(self):
1526 header = self.resp.getheader('No-Such-Header',default=42)
1527 self.assertEqual(header, 42)
1528
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001529class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001530 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001531 response_text = (
1532 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1533 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1534 'Content-Length: 42\r\n\r\n'
1535 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001536 self.host = 'proxy.com'
1537 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001538 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001539
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001540 def tearDown(self):
1541 self.conn.close()
1542
Berker Peksagab53ab02015-02-03 12:22:11 +02001543 def _create_connection(self, response_text):
1544 def create_connection(address, timeout=None, source_address=None):
1545 return FakeSocket(response_text, host=address[0], port=address[1])
1546 return create_connection
1547
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001548 def test_set_tunnel_host_port_headers(self):
1549 tunnel_host = 'destination.com'
1550 tunnel_port = 8888
1551 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1552 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1553 headers=tunnel_headers)
1554 self.conn.request('HEAD', '/', '')
1555 self.assertEqual(self.conn.sock.host, self.host)
1556 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1557 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1558 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1559 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1560
1561 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001562 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001563 self.conn.connect()
1564 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001565 'destination.com')
1566
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001567 def test_connect_with_tunnel(self):
1568 self.conn.set_tunnel('destination.com')
1569 self.conn.request('HEAD', '/', '')
1570 self.assertEqual(self.conn.sock.host, self.host)
1571 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1572 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001573 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001574 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1575 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001576
1577 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001578 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001579
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001580 def test_connect_put_request(self):
1581 self.conn.set_tunnel('destination.com')
1582 self.conn.request('PUT', '/', '')
1583 self.assertEqual(self.conn.sock.host, self.host)
1584 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1585 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1586 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1587
Berker Peksagab53ab02015-02-03 12:22:11 +02001588 def test_tunnel_debuglog(self):
1589 expected_header = 'X-Dummy: 1'
1590 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1591
1592 self.conn.set_debuglevel(1)
1593 self.conn._create_connection = self._create_connection(response_text)
1594 self.conn.set_tunnel('destination.com')
1595
1596 with support.captured_stdout() as output:
1597 self.conn.request('PUT', '/', '')
1598 lines = output.getvalue().splitlines()
1599 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001600
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001601
Benjamin Peterson9566de12014-12-13 16:13:24 -05001602@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001603def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001604 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
R David Murraycae7bdb2015-04-05 19:26:29 -04001605 PersistenceTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001606 HTTPSTest, RequestBodyTest, SourceAddressTest,
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001607 HTTPResponseTest, ExtendedReadTest,
Senthil Kumaran166214c2014-04-14 13:10:05 -04001608 ExtendedReadTestChunked, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001609
Thomas Wouters89f507f2006-12-13 04:49:30 +00001610if __name__ == '__main__':
1611 test_main()