blob: 155ab0f19b0fdb79befb6b6ee9a294a8da9b87a7 [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
R David Murraydc1650c2016-09-07 17:44:34 -0400286 def test_parse_all_octets(self):
287 # Ensure no valid header field octet breaks the parser
288 body = (
289 b'HTTP/1.1 200 OK\r\n'
290 b"!#$%&'*+-.^_`|~: value\r\n" # Special token characters
291 b'VCHAR: ' + bytes(range(0x21, 0x7E + 1)) + b'\r\n'
292 b'obs-text: ' + bytes(range(0x80, 0xFF + 1)) + b'\r\n'
293 b'obs-fold: text\r\n'
294 b' folded with space\r\n'
295 b'\tfolded with tab\r\n'
296 b'Content-Length: 0\r\n'
297 b'\r\n'
298 )
299 sock = FakeSocket(body)
300 resp = client.HTTPResponse(sock)
301 resp.begin()
302 self.assertEqual(resp.getheader('Content-Length'), '0')
303 self.assertEqual(resp.msg['Content-Length'], '0')
304 self.assertEqual(resp.getheader("!#$%&'*+-.^_`|~"), 'value')
305 self.assertEqual(resp.msg["!#$%&'*+-.^_`|~"], 'value')
306 vchar = ''.join(map(chr, range(0x21, 0x7E + 1)))
307 self.assertEqual(resp.getheader('VCHAR'), vchar)
308 self.assertEqual(resp.msg['VCHAR'], vchar)
309 self.assertIsNotNone(resp.getheader('obs-text'))
310 self.assertIn('obs-text', resp.msg)
311 for folded in (resp.getheader('obs-fold'), resp.msg['obs-fold']):
312 self.assertTrue(folded.startswith('text'))
313 self.assertIn(' folded with space', folded)
314 self.assertTrue(folded.endswith('folded with tab'))
315
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200316 def test_invalid_headers(self):
317 conn = client.HTTPConnection('example.com')
318 conn.sock = FakeSocket('')
319 conn.putrequest('GET', '/')
320
321 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
322 # longer allowed in header names
323 cases = (
324 (b'Invalid\r\nName', b'ValidValue'),
325 (b'Invalid\rName', b'ValidValue'),
326 (b'Invalid\nName', b'ValidValue'),
327 (b'\r\nInvalidName', b'ValidValue'),
328 (b'\rInvalidName', b'ValidValue'),
329 (b'\nInvalidName', b'ValidValue'),
330 (b' InvalidName', b'ValidValue'),
331 (b'\tInvalidName', b'ValidValue'),
332 (b'Invalid:Name', b'ValidValue'),
333 (b':InvalidName', b'ValidValue'),
334 (b'ValidName', b'Invalid\r\nValue'),
335 (b'ValidName', b'Invalid\rValue'),
336 (b'ValidName', b'Invalid\nValue'),
337 (b'ValidName', b'InvalidValue\r\n'),
338 (b'ValidName', b'InvalidValue\r'),
339 (b'ValidName', b'InvalidValue\n'),
340 )
341 for name, value in cases:
342 with self.subTest((name, value)):
343 with self.assertRaisesRegex(ValueError, 'Invalid header'):
344 conn.putheader(name, value)
345
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000346
Thomas Wouters89f507f2006-12-13 04:49:30 +0000347class BasicTest(TestCase):
348 def test_status_lines(self):
349 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000350
Thomas Wouters89f507f2006-12-13 04:49:30 +0000351 body = "HTTP/1.1 200 Ok\r\n\r\nText"
352 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000353 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000354 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200355 self.assertEqual(resp.read(0), b'') # Issue #20007
356 self.assertFalse(resp.isclosed())
357 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000358 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000359 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200360 self.assertFalse(resp.closed)
361 resp.close()
362 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000363
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
365 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000366 resp = client.HTTPResponse(sock)
367 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000368
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000369 def test_bad_status_repr(self):
370 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000371 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000372
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000373 def test_partial_reads(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()
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000376 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
377 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000378 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000379 resp.begin()
380 self.assertEqual(resp.read(2), b'Te')
381 self.assertFalse(resp.isclosed())
382 self.assertEqual(resp.read(2), b'xt')
383 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200384 self.assertFalse(resp.closed)
385 resp.close()
386 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000387
Martin Panterce911c32016-03-17 06:42:48 +0000388 def test_mixed_reads(self):
389 # readline() should update the remaining length, so that read() knows
390 # how much data is left and does not raise IncompleteRead
391 body = "HTTP/1.1 200 Ok\r\nContent-Length: 13\r\n\r\nText\r\nAnother"
392 sock = FakeSocket(body)
393 resp = client.HTTPResponse(sock)
394 resp.begin()
395 self.assertEqual(resp.readline(), b'Text\r\n')
396 self.assertFalse(resp.isclosed())
397 self.assertEqual(resp.read(), b'Another')
398 self.assertTrue(resp.isclosed())
399 self.assertFalse(resp.closed)
400 resp.close()
401 self.assertTrue(resp.closed)
402
Antoine Pitrou38d96432011-12-06 22:33:57 +0100403 def test_partial_readintos(self):
Martin Panterce911c32016-03-17 06:42:48 +0000404 # if we have Content-Length, HTTPResponse knows when to close itself,
405 # the same behaviour as when we read the whole thing with read()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100406 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
407 sock = FakeSocket(body)
408 resp = client.HTTPResponse(sock)
409 resp.begin()
410 b = bytearray(2)
411 n = resp.readinto(b)
412 self.assertEqual(n, 2)
413 self.assertEqual(bytes(b), b'Te')
414 self.assertFalse(resp.isclosed())
415 n = resp.readinto(b)
416 self.assertEqual(n, 2)
417 self.assertEqual(bytes(b), b'xt')
418 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200419 self.assertFalse(resp.closed)
420 resp.close()
421 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100422
Antoine Pitrou084daa22012-12-15 19:11:54 +0100423 def test_partial_reads_no_content_length(self):
424 # when no length is present, the socket should be gracefully closed when
425 # all data was read
426 body = "HTTP/1.1 200 Ok\r\n\r\nText"
427 sock = FakeSocket(body)
428 resp = client.HTTPResponse(sock)
429 resp.begin()
430 self.assertEqual(resp.read(2), b'Te')
431 self.assertFalse(resp.isclosed())
432 self.assertEqual(resp.read(2), b'xt')
433 self.assertEqual(resp.read(1), b'')
434 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200435 self.assertFalse(resp.closed)
436 resp.close()
437 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100438
Antoine Pitroud20e7742012-12-15 19:22:30 +0100439 def test_partial_readintos_no_content_length(self):
440 # when no length is present, the socket should be gracefully closed when
441 # all data was read
442 body = "HTTP/1.1 200 Ok\r\n\r\nText"
443 sock = FakeSocket(body)
444 resp = client.HTTPResponse(sock)
445 resp.begin()
446 b = bytearray(2)
447 n = resp.readinto(b)
448 self.assertEqual(n, 2)
449 self.assertEqual(bytes(b), b'Te')
450 self.assertFalse(resp.isclosed())
451 n = resp.readinto(b)
452 self.assertEqual(n, 2)
453 self.assertEqual(bytes(b), b'xt')
454 n = resp.readinto(b)
455 self.assertEqual(n, 0)
456 self.assertTrue(resp.isclosed())
457
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100458 def test_partial_reads_incomplete_body(self):
459 # if the server shuts down the connection before the whole
460 # content-length is delivered, the socket is gracefully closed
461 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
462 sock = FakeSocket(body)
463 resp = client.HTTPResponse(sock)
464 resp.begin()
465 self.assertEqual(resp.read(2), b'Te')
466 self.assertFalse(resp.isclosed())
467 self.assertEqual(resp.read(2), b'xt')
468 self.assertEqual(resp.read(1), b'')
469 self.assertTrue(resp.isclosed())
470
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100471 def test_partial_readintos_incomplete_body(self):
472 # if the server shuts down the connection before the whole
473 # content-length is delivered, the socket is gracefully closed
474 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
475 sock = FakeSocket(body)
476 resp = client.HTTPResponse(sock)
477 resp.begin()
478 b = bytearray(2)
479 n = resp.readinto(b)
480 self.assertEqual(n, 2)
481 self.assertEqual(bytes(b), b'Te')
482 self.assertFalse(resp.isclosed())
483 n = resp.readinto(b)
484 self.assertEqual(n, 2)
485 self.assertEqual(bytes(b), b'xt')
486 n = resp.readinto(b)
487 self.assertEqual(n, 0)
488 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200489 self.assertFalse(resp.closed)
490 resp.close()
491 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100492
Thomas Wouters89f507f2006-12-13 04:49:30 +0000493 def test_host_port(self):
494 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000495
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200496 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000497 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000498
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000499 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
500 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000501 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200502 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200504 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
505 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000506 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000507 self.assertEqual(h, c.host)
508 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000509
Thomas Wouters89f507f2006-12-13 04:49:30 +0000510 def test_response_headers(self):
511 # test response with multiple message headers with the same field name.
512 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000513 'Set-Cookie: Customer="WILE_E_COYOTE"; '
514 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000515 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
516 ' Path="/acme"\r\n'
517 '\r\n'
518 'No body\r\n')
519 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
520 ', '
521 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
522 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000523 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000524 r.begin()
525 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000526 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000527
Thomas Wouters89f507f2006-12-13 04:49:30 +0000528 def test_read_head(self):
529 # Test that the library doesn't attempt to read any data
530 # from a HEAD request. (Tickles SF bug #622042.)
531 sock = FakeSocket(
532 'HTTP/1.1 200 OK\r\n'
533 'Content-Length: 14432\r\n'
534 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300535 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000536 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000537 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000538 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000539 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000540
Antoine Pitrou38d96432011-12-06 22:33:57 +0100541 def test_readinto_head(self):
542 # Test that the library doesn't attempt to read any data
543 # from a HEAD request. (Tickles SF bug #622042.)
544 sock = FakeSocket(
545 'HTTP/1.1 200 OK\r\n'
546 'Content-Length: 14432\r\n'
547 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300548 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100549 resp = client.HTTPResponse(sock, method="HEAD")
550 resp.begin()
551 b = bytearray(5)
552 if resp.readinto(b) != 0:
553 self.fail("Did not expect response from HEAD request")
554 self.assertEqual(bytes(b), b'\x00'*5)
555
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100556 def test_too_many_headers(self):
557 headers = '\r\n'.join('Header%d: foo' % i
558 for i in range(client._MAXHEADERS + 1)) + '\r\n'
559 text = ('HTTP/1.1 200 OK\r\n' + headers)
560 s = FakeSocket(text)
561 r = client.HTTPResponse(s)
562 self.assertRaisesRegex(client.HTTPException,
563 r"got more than \d+ headers", r.begin)
564
Thomas Wouters89f507f2006-12-13 04:49:30 +0000565 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000566 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
567 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000568
Brett Cannon77b7de62010-10-29 23:31:11 +0000569 with open(__file__, 'rb') as body:
570 conn = client.HTTPConnection('example.com')
571 sock = FakeSocket(body)
572 conn.sock = sock
573 conn.request('GET', '/foo', body)
574 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
575 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000576
Antoine Pitrouead1d622009-09-29 18:44:53 +0000577 def test_send(self):
578 expected = b'this is a test this is only a test'
579 conn = client.HTTPConnection('example.com')
580 sock = FakeSocket(None)
581 conn.sock = sock
582 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000583 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000584 sock.data = b''
585 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000586 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000587 sock.data = b''
588 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000589 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000590
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300591 def test_send_updating_file(self):
592 def data():
593 yield 'data'
594 yield None
595 yield 'data_two'
596
597 class UpdatingFile():
598 mode = 'r'
599 d = data()
600 def read(self, blocksize=-1):
601 return self.d.__next__()
602
603 expected = b'data'
604
605 conn = client.HTTPConnection('example.com')
606 sock = FakeSocket("")
607 conn.sock = sock
608 conn.send(UpdatingFile())
609 self.assertEqual(sock.data, expected)
610
611
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000612 def test_send_iter(self):
613 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
614 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
615 b'\r\nonetwothree'
616
617 def body():
618 yield b"one"
619 yield b"two"
620 yield b"three"
621
622 conn = client.HTTPConnection('example.com')
623 sock = FakeSocket("")
624 conn.sock = sock
625 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000626 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000627
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800628 def test_send_type_error(self):
629 # See: Issue #12676
630 conn = client.HTTPConnection('example.com')
631 conn.sock = FakeSocket('')
632 with self.assertRaises(TypeError):
633 conn.request('POST', 'test', conn)
634
Christian Heimesa612dc02008-02-24 13:08:18 +0000635 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000636 expected = chunked_expected
637 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000638 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000639 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100640 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000641 resp.close()
642
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100643 # Various read sizes
644 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000645 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100646 resp = client.HTTPResponse(sock, method="GET")
647 resp.begin()
648 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
649 resp.close()
650
Christian Heimesa612dc02008-02-24 13:08:18 +0000651 for x in ('', 'foo\r\n'):
652 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000653 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000654 resp.begin()
655 try:
656 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000657 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100658 self.assertEqual(i.partial, expected)
659 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
660 self.assertEqual(repr(i), expected_message)
661 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000662 else:
663 self.fail('IncompleteRead expected')
664 finally:
665 resp.close()
666
Antoine Pitrou38d96432011-12-06 22:33:57 +0100667 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000668
669 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100670 nexpected = len(expected)
671 b = bytearray(128)
672
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000673 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100674 resp = client.HTTPResponse(sock, method="GET")
675 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100676 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100677 self.assertEqual(b[:nexpected], expected)
678 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100679 resp.close()
680
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100681 # Various read sizes
682 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000683 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100684 resp = client.HTTPResponse(sock, method="GET")
685 resp.begin()
686 m = memoryview(b)
687 i = resp.readinto(m[0:n])
688 i += resp.readinto(m[i:n + i])
689 i += resp.readinto(m[i:])
690 self.assertEqual(b[:nexpected], expected)
691 self.assertEqual(i, nexpected)
692 resp.close()
693
Antoine Pitrou38d96432011-12-06 22:33:57 +0100694 for x in ('', 'foo\r\n'):
695 sock = FakeSocket(chunked_start + x)
696 resp = client.HTTPResponse(sock, method="GET")
697 resp.begin()
698 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100699 n = resp.readinto(b)
700 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100701 self.assertEqual(i.partial, expected)
702 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
703 self.assertEqual(repr(i), expected_message)
704 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100705 else:
706 self.fail('IncompleteRead expected')
707 finally:
708 resp.close()
709
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000710 def test_chunked_head(self):
711 chunked_start = (
712 'HTTP/1.1 200 OK\r\n'
713 'Transfer-Encoding: chunked\r\n\r\n'
714 'a\r\n'
715 'hello world\r\n'
716 '1\r\n'
717 'd\r\n'
718 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000719 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000720 resp = client.HTTPResponse(sock, method="HEAD")
721 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000722 self.assertEqual(resp.read(), b'')
723 self.assertEqual(resp.status, 200)
724 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000725 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200726 self.assertFalse(resp.closed)
727 resp.close()
728 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000729
Antoine Pitrou38d96432011-12-06 22:33:57 +0100730 def test_readinto_chunked_head(self):
731 chunked_start = (
732 'HTTP/1.1 200 OK\r\n'
733 'Transfer-Encoding: chunked\r\n\r\n'
734 'a\r\n'
735 'hello world\r\n'
736 '1\r\n'
737 'd\r\n'
738 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000739 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100740 resp = client.HTTPResponse(sock, method="HEAD")
741 resp.begin()
742 b = bytearray(5)
743 n = resp.readinto(b)
744 self.assertEqual(n, 0)
745 self.assertEqual(bytes(b), b'\x00'*5)
746 self.assertEqual(resp.status, 200)
747 self.assertEqual(resp.reason, 'OK')
748 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200749 self.assertFalse(resp.closed)
750 resp.close()
751 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100752
Christian Heimesa612dc02008-02-24 13:08:18 +0000753 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000754 sock = FakeSocket(
755 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000756 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000757 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000758 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100759 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000760
Benjamin Peterson6accb982009-03-02 22:50:25 +0000761 def test_incomplete_read(self):
762 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000763 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000764 resp.begin()
765 try:
766 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000767 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000768 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000769 self.assertEqual(repr(i),
770 "IncompleteRead(7 bytes read, 3 more expected)")
771 self.assertEqual(str(i),
772 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100773 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000774 else:
775 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000776
Jeremy Hylton636950f2009-03-28 04:34:21 +0000777 def test_epipe(self):
778 sock = EPipeSocket(
779 "HTTP/1.0 401 Authorization Required\r\n"
780 "Content-type: text/html\r\n"
781 "WWW-Authenticate: Basic realm=\"example\"\r\n",
782 b"Content-Length")
783 conn = client.HTTPConnection("example.com")
784 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200785 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000786 lambda: conn.request("PUT", "/url", "body"))
787 resp = conn.getresponse()
788 self.assertEqual(401, resp.status)
789 self.assertEqual("Basic realm=\"example\"",
790 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000791
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000792 # Test lines overflowing the max line size (_MAXLINE in http.client)
793
794 def test_overflowing_status_line(self):
795 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
796 resp = client.HTTPResponse(FakeSocket(body))
797 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
798
799 def test_overflowing_header_line(self):
800 body = (
801 'HTTP/1.1 200 OK\r\n'
802 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
803 )
804 resp = client.HTTPResponse(FakeSocket(body))
805 self.assertRaises(client.LineTooLong, resp.begin)
806
807 def test_overflowing_chunked_line(self):
808 body = (
809 'HTTP/1.1 200 OK\r\n'
810 'Transfer-Encoding: chunked\r\n\r\n'
811 + '0' * 65536 + 'a\r\n'
812 'hello world\r\n'
813 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000814 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000815 )
816 resp = client.HTTPResponse(FakeSocket(body))
817 resp.begin()
818 self.assertRaises(client.LineTooLong, resp.read)
819
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800820 def test_early_eof(self):
821 # Test httpresponse with no \r\n termination,
822 body = "HTTP/1.1 200 Ok"
823 sock = FakeSocket(body)
824 resp = client.HTTPResponse(sock)
825 resp.begin()
826 self.assertEqual(resp.read(), b'')
827 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200828 self.assertFalse(resp.closed)
829 resp.close()
830 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800831
Serhiy Storchakab491e052014-12-01 13:07:45 +0200832 def test_error_leak(self):
833 # Test that the socket is not leaked if getresponse() fails
834 conn = client.HTTPConnection('example.com')
835 response = None
836 class Response(client.HTTPResponse):
837 def __init__(self, *pos, **kw):
838 nonlocal response
839 response = self # Avoid garbage collector closing the socket
840 client.HTTPResponse.__init__(self, *pos, **kw)
841 conn.response_class = Response
R David Murraycae7bdb2015-04-05 19:26:29 -0400842 conn.sock = FakeSocket('Invalid status line')
Serhiy Storchakab491e052014-12-01 13:07:45 +0200843 conn.request('GET', '/')
844 self.assertRaises(client.BadStatusLine, conn.getresponse)
845 self.assertTrue(response.closed)
846 self.assertTrue(conn.sock.file_closed)
847
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000848 def test_chunked_extension(self):
849 extra = '3;foo=bar\r\n' + 'abc\r\n'
850 expected = chunked_expected + b'abc'
851
852 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
853 resp = client.HTTPResponse(sock, method="GET")
854 resp.begin()
855 self.assertEqual(resp.read(), expected)
856 resp.close()
857
858 def test_chunked_missing_end(self):
859 """some servers may serve up a short chunked encoding stream"""
860 expected = chunked_expected
861 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
862 resp = client.HTTPResponse(sock, method="GET")
863 resp.begin()
864 self.assertEqual(resp.read(), expected)
865 resp.close()
866
867 def test_chunked_trailers(self):
868 """See that trailers are read and ignored"""
869 expected = chunked_expected
870 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
871 resp = client.HTTPResponse(sock, method="GET")
872 resp.begin()
873 self.assertEqual(resp.read(), expected)
874 # we should have reached the end of the file
Martin Panterce911c32016-03-17 06:42:48 +0000875 self.assertEqual(sock.file.read(), b"") #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000876 resp.close()
877
878 def test_chunked_sync(self):
879 """Check that we don't read past the end of the chunked-encoding stream"""
880 expected = chunked_expected
881 extradata = "extradata"
882 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
883 resp = client.HTTPResponse(sock, method="GET")
884 resp.begin()
885 self.assertEqual(resp.read(), expected)
886 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +0000887 self.assertEqual(sock.file.read(), extradata.encode("ascii")) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000888 resp.close()
889
890 def test_content_length_sync(self):
891 """Check that we don't read past the end of the Content-Length stream"""
Martin Panterce911c32016-03-17 06:42:48 +0000892 extradata = b"extradata"
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000893 expected = b"Hello123\r\n"
Martin Panterce911c32016-03-17 06:42:48 +0000894 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 +0000895 resp = client.HTTPResponse(sock, method="GET")
896 resp.begin()
897 self.assertEqual(resp.read(), expected)
898 # the file should now have our extradata ready to be read
Martin Panterce911c32016-03-17 06:42:48 +0000899 self.assertEqual(sock.file.read(), extradata) #we read to the end
900 resp.close()
901
902 def test_readlines_content_length(self):
903 extradata = b"extradata"
904 expected = b"Hello123\r\n"
905 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
906 resp = client.HTTPResponse(sock, method="GET")
907 resp.begin()
908 self.assertEqual(resp.readlines(2000), [expected])
909 # the file should now have our extradata ready to be read
910 self.assertEqual(sock.file.read(), extradata) #we read to the end
911 resp.close()
912
913 def test_read1_content_length(self):
914 extradata = b"extradata"
915 expected = b"Hello123\r\n"
916 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
917 resp = client.HTTPResponse(sock, method="GET")
918 resp.begin()
919 self.assertEqual(resp.read1(2000), expected)
920 # the file should now have our extradata ready to be read
921 self.assertEqual(sock.file.read(), extradata) #we read to the end
922 resp.close()
923
924 def test_readline_bound_content_length(self):
925 extradata = b"extradata"
926 expected = b"Hello123\r\n"
927 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\n' + expected + extradata)
928 resp = client.HTTPResponse(sock, method="GET")
929 resp.begin()
930 self.assertEqual(resp.readline(10), expected)
931 self.assertEqual(resp.readline(10), b"")
932 # the file should now have our extradata ready to be read
933 self.assertEqual(sock.file.read(), extradata) #we read to the end
934 resp.close()
935
936 def test_read1_bound_content_length(self):
937 extradata = b"extradata"
938 expected = b"Hello123\r\n"
939 sock = FakeSocket(b'HTTP/1.1 200 OK\r\nContent-Length: 30\r\n\r\n' + expected*3 + extradata)
940 resp = client.HTTPResponse(sock, method="GET")
941 resp.begin()
942 self.assertEqual(resp.read1(20), expected*2)
943 self.assertEqual(resp.read(), expected)
944 # the file should now have our extradata ready to be read
945 self.assertEqual(sock.file.read(), extradata) #we read to the end
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000946 resp.close()
947
Martin Panterd979b2c2016-04-09 14:03:17 +0000948 def test_response_fileno(self):
949 # Make sure fd returned by fileno is valid.
950 threading = support.import_module("threading")
951
952 serv = socket.socket(
953 socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)
954 self.addCleanup(serv.close)
955 serv.bind((HOST, 0))
956 serv.listen()
957
958 result = None
959 def run_server():
960 [conn, address] = serv.accept()
961 with conn, conn.makefile("rb") as reader:
962 # Read the request header until a blank line
963 while True:
964 line = reader.readline()
965 if not line.rstrip(b"\r\n"):
966 break
967 conn.sendall(b"HTTP/1.1 200 Connection established\r\n\r\n")
968 nonlocal result
969 result = reader.read()
970
971 thread = threading.Thread(target=run_server)
972 thread.start()
973 conn = client.HTTPConnection(*serv.getsockname())
974 conn.request("CONNECT", "dummy:1234")
975 response = conn.getresponse()
976 try:
977 self.assertEqual(response.status, client.OK)
978 s = socket.socket(fileno=response.fileno())
979 try:
980 s.sendall(b"proxied data\n")
981 finally:
982 s.detach()
983 finally:
984 response.close()
985 conn.close()
986 thread.join()
987 self.assertEqual(result, b"proxied data\n")
988
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000989class ExtendedReadTest(TestCase):
990 """
991 Test peek(), read1(), readline()
992 """
993 lines = (
994 'HTTP/1.1 200 OK\r\n'
995 '\r\n'
996 'hello world!\n'
997 'and now \n'
998 'for something completely different\n'
999 'foo'
1000 )
1001 lines_expected = lines[lines.find('hello'):].encode("ascii")
1002 lines_chunked = (
1003 'HTTP/1.1 200 OK\r\n'
1004 'Transfer-Encoding: chunked\r\n\r\n'
1005 'a\r\n'
1006 'hello worl\r\n'
1007 '3\r\n'
1008 'd!\n\r\n'
1009 '9\r\n'
1010 'and now \n\r\n'
1011 '23\r\n'
1012 'for something completely different\n\r\n'
1013 '3\r\n'
1014 'foo\r\n'
1015 '0\r\n' # terminating chunk
1016 '\r\n' # end of trailers
1017 )
1018
1019 def setUp(self):
1020 sock = FakeSocket(self.lines)
1021 resp = client.HTTPResponse(sock, method="GET")
1022 resp.begin()
1023 resp.fp = io.BufferedReader(resp.fp)
1024 self.resp = resp
1025
1026
1027
1028 def test_peek(self):
1029 resp = self.resp
1030 # patch up the buffered peek so that it returns not too much stuff
1031 oldpeek = resp.fp.peek
1032 def mypeek(n=-1):
1033 p = oldpeek(n)
1034 if n >= 0:
1035 return p[:n]
1036 return p[:10]
1037 resp.fp.peek = mypeek
1038
1039 all = []
1040 while True:
1041 # try a short peek
1042 p = resp.peek(3)
1043 if p:
1044 self.assertGreater(len(p), 0)
1045 # then unbounded peek
1046 p2 = resp.peek()
1047 self.assertGreaterEqual(len(p2), len(p))
1048 self.assertTrue(p2.startswith(p))
1049 next = resp.read(len(p2))
1050 self.assertEqual(next, p2)
1051 else:
1052 next = resp.read()
1053 self.assertFalse(next)
1054 all.append(next)
1055 if not next:
1056 break
1057 self.assertEqual(b"".join(all), self.lines_expected)
1058
1059 def test_readline(self):
1060 resp = self.resp
1061 self._verify_readline(self.resp.readline, self.lines_expected)
1062
1063 def _verify_readline(self, readline, expected):
1064 all = []
1065 while True:
1066 # short readlines
1067 line = readline(5)
1068 if line and line != b"foo":
1069 if len(line) < 5:
1070 self.assertTrue(line.endswith(b"\n"))
1071 all.append(line)
1072 if not line:
1073 break
1074 self.assertEqual(b"".join(all), expected)
1075
1076 def test_read1(self):
1077 resp = self.resp
1078 def r():
1079 res = resp.read1(4)
1080 self.assertLessEqual(len(res), 4)
1081 return res
1082 readliner = Readliner(r)
1083 self._verify_readline(readliner.readline, self.lines_expected)
1084
1085 def test_read1_unbounded(self):
1086 resp = self.resp
1087 all = []
1088 while True:
1089 data = resp.read1()
1090 if not data:
1091 break
1092 all.append(data)
1093 self.assertEqual(b"".join(all), self.lines_expected)
1094
1095 def test_read1_bounded(self):
1096 resp = self.resp
1097 all = []
1098 while True:
1099 data = resp.read1(10)
1100 if not data:
1101 break
1102 self.assertLessEqual(len(data), 10)
1103 all.append(data)
1104 self.assertEqual(b"".join(all), self.lines_expected)
1105
1106 def test_read1_0(self):
1107 self.assertEqual(self.resp.read1(0), b"")
1108
1109 def test_peek_0(self):
1110 p = self.resp.peek(0)
1111 self.assertLessEqual(0, len(p))
1112
1113class ExtendedReadTestChunked(ExtendedReadTest):
1114 """
1115 Test peek(), read1(), readline() in chunked mode
1116 """
1117 lines = (
1118 'HTTP/1.1 200 OK\r\n'
1119 'Transfer-Encoding: chunked\r\n\r\n'
1120 'a\r\n'
1121 'hello worl\r\n'
1122 '3\r\n'
1123 'd!\n\r\n'
1124 '9\r\n'
1125 'and now \n\r\n'
1126 '23\r\n'
1127 'for something completely different\n\r\n'
1128 '3\r\n'
1129 'foo\r\n'
1130 '0\r\n' # terminating chunk
1131 '\r\n' # end of trailers
1132 )
1133
1134
1135class Readliner:
1136 """
1137 a simple readline class that uses an arbitrary read function and buffering
1138 """
1139 def __init__(self, readfunc):
1140 self.readfunc = readfunc
1141 self.remainder = b""
1142
1143 def readline(self, limit):
1144 data = []
1145 datalen = 0
1146 read = self.remainder
1147 try:
1148 while True:
1149 idx = read.find(b'\n')
1150 if idx != -1:
1151 break
1152 if datalen + len(read) >= limit:
1153 idx = limit - datalen - 1
1154 # read more data
1155 data.append(read)
1156 read = self.readfunc()
1157 if not read:
1158 idx = 0 #eof condition
1159 break
1160 idx += 1
1161 data.append(read[:idx])
1162 self.remainder = read[idx:]
1163 return b"".join(data)
1164 except:
1165 self.remainder = b"".join(data)
1166 raise
1167
Berker Peksagbabc6882015-02-20 09:39:38 +02001168
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001169class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001170 def test_all(self):
1171 # Documented objects defined in the module should be in __all__
1172 expected = {"responses"} # White-list documented dict() object
1173 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1174 # intentionally omitted for simplicity
1175 blacklist = {"HTTPMessage", "parse_headers"}
1176 for name in dir(client):
Martin Panter44391482016-02-09 10:20:52 +00001177 if name.startswith("_") or name in blacklist:
Berker Peksagbabc6882015-02-20 09:39:38 +02001178 continue
1179 module_object = getattr(client, name)
1180 if getattr(module_object, "__module__", None) == "http.client":
1181 expected.add(name)
1182 self.assertCountEqual(client.__all__, expected)
1183
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001184 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001185 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001186
Berker Peksagabbf0f42015-02-20 14:57:31 +02001187 def test_client_constants(self):
1188 # Make sure we don't break backward compatibility with 3.4
1189 expected = [
1190 'CONTINUE',
1191 'SWITCHING_PROTOCOLS',
1192 'PROCESSING',
1193 'OK',
1194 'CREATED',
1195 'ACCEPTED',
1196 'NON_AUTHORITATIVE_INFORMATION',
1197 'NO_CONTENT',
1198 'RESET_CONTENT',
1199 'PARTIAL_CONTENT',
1200 'MULTI_STATUS',
1201 'IM_USED',
1202 'MULTIPLE_CHOICES',
1203 'MOVED_PERMANENTLY',
1204 'FOUND',
1205 'SEE_OTHER',
1206 'NOT_MODIFIED',
1207 'USE_PROXY',
1208 'TEMPORARY_REDIRECT',
1209 'BAD_REQUEST',
1210 'UNAUTHORIZED',
1211 'PAYMENT_REQUIRED',
1212 'FORBIDDEN',
1213 'NOT_FOUND',
1214 'METHOD_NOT_ALLOWED',
1215 'NOT_ACCEPTABLE',
1216 'PROXY_AUTHENTICATION_REQUIRED',
1217 'REQUEST_TIMEOUT',
1218 'CONFLICT',
1219 'GONE',
1220 'LENGTH_REQUIRED',
1221 'PRECONDITION_FAILED',
1222 'REQUEST_ENTITY_TOO_LARGE',
1223 'REQUEST_URI_TOO_LONG',
1224 'UNSUPPORTED_MEDIA_TYPE',
1225 'REQUESTED_RANGE_NOT_SATISFIABLE',
1226 'EXPECTATION_FAILED',
1227 'UNPROCESSABLE_ENTITY',
1228 'LOCKED',
1229 'FAILED_DEPENDENCY',
1230 'UPGRADE_REQUIRED',
1231 'PRECONDITION_REQUIRED',
1232 'TOO_MANY_REQUESTS',
1233 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1234 'INTERNAL_SERVER_ERROR',
1235 'NOT_IMPLEMENTED',
1236 'BAD_GATEWAY',
1237 'SERVICE_UNAVAILABLE',
1238 'GATEWAY_TIMEOUT',
1239 'HTTP_VERSION_NOT_SUPPORTED',
1240 'INSUFFICIENT_STORAGE',
1241 'NOT_EXTENDED',
1242 'NETWORK_AUTHENTICATION_REQUIRED',
1243 ]
1244 for const in expected:
1245 with self.subTest(constant=const):
1246 self.assertTrue(hasattr(client, const))
1247
Gregory P. Smithb4066372010-01-03 03:28:29 +00001248
1249class SourceAddressTest(TestCase):
1250 def setUp(self):
1251 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1252 self.port = support.bind_port(self.serv)
1253 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001254 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001255 self.conn = None
1256
1257 def tearDown(self):
1258 if self.conn:
1259 self.conn.close()
1260 self.conn = None
1261 self.serv.close()
1262 self.serv = None
1263
1264 def testHTTPConnectionSourceAddress(self):
1265 self.conn = client.HTTPConnection(HOST, self.port,
1266 source_address=('', self.source_port))
1267 self.conn.connect()
1268 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1269
1270 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1271 'http.client.HTTPSConnection not defined')
1272 def testHTTPSConnectionSourceAddress(self):
1273 self.conn = client.HTTPSConnection(HOST, self.port,
1274 source_address=('', self.source_port))
1275 # We don't test anything here other the constructor not barfing as
1276 # this code doesn't deal with setting up an active running SSL server
1277 # for an ssl_wrapped connect() to actually return from.
1278
1279
Guido van Rossumd8faa362007-04-27 19:54:29 +00001280class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001281 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001282
1283 def setUp(self):
1284 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001285 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001286 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001287
1288 def tearDown(self):
1289 self.serv.close()
1290 self.serv = None
1291
1292 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001293 # This will prove that the timeout gets through HTTPConnection
1294 # and into the socket.
1295
Georg Brandlf78e02b2008-06-10 17:40:04 +00001296 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001297 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001298 socket.setdefaulttimeout(30)
1299 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001300 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001301 httpConn.connect()
1302 finally:
1303 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001304 self.assertEqual(httpConn.sock.gettimeout(), 30)
1305 httpConn.close()
1306
Georg Brandlf78e02b2008-06-10 17:40:04 +00001307 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001308 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001309 socket.setdefaulttimeout(30)
1310 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001311 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001312 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001313 httpConn.connect()
1314 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001315 socket.setdefaulttimeout(None)
1316 self.assertEqual(httpConn.sock.gettimeout(), None)
1317 httpConn.close()
1318
1319 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001320 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001321 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001322 self.assertEqual(httpConn.sock.gettimeout(), 30)
1323 httpConn.close()
1324
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001325
R David Murraycae7bdb2015-04-05 19:26:29 -04001326class PersistenceTest(TestCase):
1327
1328 def test_reuse_reconnect(self):
1329 # Should reuse or reconnect depending on header from server
1330 tests = (
1331 ('1.0', '', False),
1332 ('1.0', 'Connection: keep-alive\r\n', True),
1333 ('1.1', '', True),
1334 ('1.1', 'Connection: close\r\n', False),
1335 ('1.0', 'Connection: keep-ALIVE\r\n', True),
1336 ('1.1', 'Connection: cloSE\r\n', False),
1337 )
1338 for version, header, reuse in tests:
1339 with self.subTest(version=version, header=header):
1340 msg = (
1341 'HTTP/{} 200 OK\r\n'
1342 '{}'
1343 'Content-Length: 12\r\n'
1344 '\r\n'
1345 'Dummy body\r\n'
1346 ).format(version, header)
1347 conn = FakeSocketHTTPConnection(msg)
1348 self.assertIsNone(conn.sock)
1349 conn.request('GET', '/open-connection')
1350 with conn.getresponse() as response:
1351 self.assertEqual(conn.sock is None, not reuse)
1352 response.read()
1353 self.assertEqual(conn.sock is None, not reuse)
1354 self.assertEqual(conn.connections, 1)
1355 conn.request('GET', '/subsequent-request')
1356 self.assertEqual(conn.connections, 1 if reuse else 2)
1357
1358 def test_disconnected(self):
1359
1360 def make_reset_reader(text):
1361 """Return BufferedReader that raises ECONNRESET at EOF"""
1362 stream = io.BytesIO(text)
1363 def readinto(buffer):
1364 size = io.BytesIO.readinto(stream, buffer)
1365 if size == 0:
1366 raise ConnectionResetError()
1367 return size
1368 stream.readinto = readinto
1369 return io.BufferedReader(stream)
1370
1371 tests = (
1372 (io.BytesIO, client.RemoteDisconnected),
1373 (make_reset_reader, ConnectionResetError),
1374 )
1375 for stream_factory, exception in tests:
1376 with self.subTest(exception=exception):
1377 conn = FakeSocketHTTPConnection(b'', stream_factory)
1378 conn.request('GET', '/eof-response')
1379 self.assertRaises(exception, conn.getresponse)
1380 self.assertIsNone(conn.sock)
1381 # HTTPConnection.connect() should be automatically invoked
1382 conn.request('GET', '/reconnect')
1383 self.assertEqual(conn.connections, 2)
1384
1385 def test_100_close(self):
1386 conn = FakeSocketHTTPConnection(
1387 b'HTTP/1.1 100 Continue\r\n'
1388 b'\r\n'
1389 # Missing final response
1390 )
1391 conn.request('GET', '/', headers={'Expect': '100-continue'})
1392 self.assertRaises(client.RemoteDisconnected, conn.getresponse)
1393 self.assertIsNone(conn.sock)
1394 conn.request('GET', '/reconnect')
1395 self.assertEqual(conn.connections, 2)
1396
1397
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001398class HTTPSTest(TestCase):
1399
1400 def setUp(self):
1401 if not hasattr(client, 'HTTPSConnection'):
1402 self.skipTest('ssl support required')
1403
1404 def make_server(self, certfile):
1405 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001406 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001407
1408 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001409 # simple test to check it's storing the timeout
1410 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1411 self.assertEqual(h.timeout, 30)
1412
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001413 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001414 # Default settings: requires a valid cert from a trusted CA
1415 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001416 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001417 with support.transient_internet('self-signed.pythontest.net'):
1418 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1419 with self.assertRaises(ssl.SSLError) as exc_info:
1420 h.request('GET', '/')
1421 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1422
1423 def test_networked_noverification(self):
1424 # Switch off cert verification
1425 import ssl
1426 support.requires('network')
1427 with support.transient_internet('self-signed.pythontest.net'):
1428 context = ssl._create_unverified_context()
1429 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1430 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001431 h.request('GET', '/')
1432 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001433 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001434 self.assertIn('nginx', resp.getheader('server'))
Martin Panterb63c5602016-08-12 11:59:52 +00001435 resp.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001436
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001437 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001438 def test_networked_trusted_by_default_cert(self):
1439 # Default settings: requires a valid cert from a trusted CA
1440 support.requires('network')
1441 with support.transient_internet('www.python.org'):
1442 h = client.HTTPSConnection('www.python.org', 443)
1443 h.request('GET', '/')
1444 resp = h.getresponse()
1445 content_type = resp.getheader('content-type')
Martin Panterb63c5602016-08-12 11:59:52 +00001446 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001447 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001448 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001449
1450 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001451 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001452 import ssl
1453 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +01001454 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001455 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1456 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +01001457 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
1458 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001459 h.request('GET', '/')
1460 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001461 server_string = resp.getheader('server')
Martin Panterb63c5602016-08-12 11:59:52 +00001462 resp.close()
Victor Stinnerb389b482015-02-27 17:47:23 +01001463 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001464 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001465
1466 def test_networked_bad_cert(self):
1467 # We feed a "CA" cert that is unrelated to the server's cert
1468 import ssl
1469 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001470 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001471 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1472 context.verify_mode = ssl.CERT_REQUIRED
1473 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001474 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1475 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001476 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001477 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1478
1479 def test_local_unknown_cert(self):
1480 # The custom cert isn't known to the default trust bundle
1481 import ssl
1482 server = self.make_server(CERT_localhost)
1483 h = client.HTTPSConnection('localhost', server.port)
1484 with self.assertRaises(ssl.SSLError) as exc_info:
1485 h.request('GET', '/')
1486 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001487
1488 def test_local_good_hostname(self):
1489 # The (valid) cert validates the HTTP hostname
1490 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001491 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001492 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1493 context.verify_mode = ssl.CERT_REQUIRED
1494 context.load_verify_locations(CERT_localhost)
1495 h = client.HTTPSConnection('localhost', server.port, context=context)
Martin Panterb63c5602016-08-12 11:59:52 +00001496 self.addCleanup(h.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001497 h.request('GET', '/nonexistent')
1498 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001499 self.addCleanup(resp.close)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001500 self.assertEqual(resp.status, 404)
1501
1502 def test_local_bad_hostname(self):
1503 # The (valid) cert doesn't validate the HTTP hostname
1504 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001505 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001506 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1507 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -05001508 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001509 context.load_verify_locations(CERT_fakehostname)
1510 h = client.HTTPSConnection('localhost', server.port, context=context)
1511 with self.assertRaises(ssl.CertificateError):
1512 h.request('GET', '/')
1513 # Same with explicit check_hostname=True
1514 h = client.HTTPSConnection('localhost', server.port, context=context,
1515 check_hostname=True)
1516 with self.assertRaises(ssl.CertificateError):
1517 h.request('GET', '/')
1518 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001519 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001520 h = client.HTTPSConnection('localhost', server.port, context=context,
1521 check_hostname=False)
1522 h.request('GET', '/nonexistent')
1523 resp = h.getresponse()
Martin Panterb63c5602016-08-12 11:59:52 +00001524 resp.close()
1525 h.close()
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001526 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001527 # The context's check_hostname setting is used if one isn't passed to
1528 # HTTPSConnection.
1529 context.check_hostname = False
1530 h = client.HTTPSConnection('localhost', server.port, context=context)
1531 h.request('GET', '/nonexistent')
Martin Panterb63c5602016-08-12 11:59:52 +00001532 resp = h.getresponse()
1533 self.assertEqual(resp.status, 404)
1534 resp.close()
1535 h.close()
Benjamin Petersona090f012014-12-07 13:18:25 -05001536 # Passing check_hostname to HTTPSConnection should override the
1537 # context's setting.
1538 h = client.HTTPSConnection('localhost', server.port, context=context,
1539 check_hostname=True)
1540 with self.assertRaises(ssl.CertificateError):
1541 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001542
Petri Lehtinene119c402011-10-26 21:29:15 +03001543 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1544 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001545 def test_host_port(self):
1546 # Check invalid host_port
1547
1548 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1549 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1550
1551 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1552 "fe80::207:e9ff:fe9b", 8000),
1553 ("www.python.org:443", "www.python.org", 443),
1554 ("www.python.org:", "www.python.org", 443),
1555 ("www.python.org", "www.python.org", 443),
1556 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1557 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1558 443)):
1559 c = client.HTTPSConnection(hp)
1560 self.assertEqual(h, c.host)
1561 self.assertEqual(p, c.port)
1562
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001563
Jeremy Hylton236654b2009-03-27 20:24:34 +00001564class RequestBodyTest(TestCase):
1565 """Test cases where a request includes a message body."""
1566
1567 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001568 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001569 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001570 self.conn.sock = self.sock
1571
1572 def get_headers_and_fp(self):
1573 f = io.BytesIO(self.sock.data)
1574 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001575 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001576 return message, f
1577
1578 def test_manual_content_length(self):
1579 # Set an incorrect content-length so that we can verify that
1580 # it will not be over-ridden by the library.
1581 self.conn.request("PUT", "/url", "body",
1582 {"Content-Length": "42"})
1583 message, f = self.get_headers_and_fp()
1584 self.assertEqual("42", message.get("content-length"))
1585 self.assertEqual(4, len(f.read()))
1586
1587 def test_ascii_body(self):
1588 self.conn.request("PUT", "/url", "body")
1589 message, f = self.get_headers_and_fp()
1590 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001591 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001592 self.assertEqual("4", message.get("content-length"))
1593 self.assertEqual(b'body', f.read())
1594
1595 def test_latin1_body(self):
1596 self.conn.request("PUT", "/url", "body\xc1")
1597 message, f = self.get_headers_and_fp()
1598 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001599 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001600 self.assertEqual("5", message.get("content-length"))
1601 self.assertEqual(b'body\xc1', f.read())
1602
1603 def test_bytes_body(self):
1604 self.conn.request("PUT", "/url", b"body\xc1")
1605 message, f = self.get_headers_and_fp()
1606 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001607 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001608 self.assertEqual("5", message.get("content-length"))
1609 self.assertEqual(b'body\xc1', f.read())
1610
1611 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001612 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001613 with open(support.TESTFN, "w") as f:
1614 f.write("body")
1615 with open(support.TESTFN) as f:
1616 self.conn.request("PUT", "/url", f)
1617 message, f = self.get_headers_and_fp()
1618 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001619 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001620 self.assertEqual("4", message.get("content-length"))
1621 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001622
1623 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001624 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001625 with open(support.TESTFN, "wb") as f:
1626 f.write(b"body\xc1")
1627 with open(support.TESTFN, "rb") as f:
1628 self.conn.request("PUT", "/url", f)
1629 message, f = self.get_headers_and_fp()
1630 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001631 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001632 self.assertEqual("5", message.get("content-length"))
1633 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001634
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001635
1636class HTTPResponseTest(TestCase):
1637
1638 def setUp(self):
1639 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1640 second-value\r\n\r\nText"
1641 sock = FakeSocket(body)
1642 self.resp = client.HTTPResponse(sock)
1643 self.resp.begin()
1644
1645 def test_getting_header(self):
1646 header = self.resp.getheader('My-Header')
1647 self.assertEqual(header, 'first-value, second-value')
1648
1649 header = self.resp.getheader('My-Header', 'some default')
1650 self.assertEqual(header, 'first-value, second-value')
1651
1652 def test_getting_nonexistent_header_with_string_default(self):
1653 header = self.resp.getheader('No-Such-Header', 'default-value')
1654 self.assertEqual(header, 'default-value')
1655
1656 def test_getting_nonexistent_header_with_iterable_default(self):
1657 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1658 self.assertEqual(header, 'default, values')
1659
1660 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1661 self.assertEqual(header, 'default, values')
1662
1663 def test_getting_nonexistent_header_without_default(self):
1664 header = self.resp.getheader('No-Such-Header')
1665 self.assertEqual(header, None)
1666
1667 def test_getting_header_defaultint(self):
1668 header = self.resp.getheader('No-Such-Header',default=42)
1669 self.assertEqual(header, 42)
1670
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001671class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001672 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001673 response_text = (
1674 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1675 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1676 'Content-Length: 42\r\n\r\n'
1677 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001678 self.host = 'proxy.com'
1679 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001680 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001681
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001682 def tearDown(self):
1683 self.conn.close()
1684
Berker Peksagab53ab02015-02-03 12:22:11 +02001685 def _create_connection(self, response_text):
1686 def create_connection(address, timeout=None, source_address=None):
1687 return FakeSocket(response_text, host=address[0], port=address[1])
1688 return create_connection
1689
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001690 def test_set_tunnel_host_port_headers(self):
1691 tunnel_host = 'destination.com'
1692 tunnel_port = 8888
1693 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1694 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1695 headers=tunnel_headers)
1696 self.conn.request('HEAD', '/', '')
1697 self.assertEqual(self.conn.sock.host, self.host)
1698 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1699 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1700 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1701 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1702
1703 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001704 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001705 self.conn.connect()
1706 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001707 'destination.com')
1708
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001709 def test_connect_with_tunnel(self):
1710 self.conn.set_tunnel('destination.com')
1711 self.conn.request('HEAD', '/', '')
1712 self.assertEqual(self.conn.sock.host, self.host)
1713 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1714 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001715 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001716 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1717 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001718
1719 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001720 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001721
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001722 def test_connect_put_request(self):
1723 self.conn.set_tunnel('destination.com')
1724 self.conn.request('PUT', '/', '')
1725 self.assertEqual(self.conn.sock.host, self.host)
1726 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1727 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1728 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1729
Berker Peksagab53ab02015-02-03 12:22:11 +02001730 def test_tunnel_debuglog(self):
1731 expected_header = 'X-Dummy: 1'
1732 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1733
1734 self.conn.set_debuglevel(1)
1735 self.conn._create_connection = self._create_connection(response_text)
1736 self.conn.set_tunnel('destination.com')
1737
1738 with support.captured_stdout() as output:
1739 self.conn.request('PUT', '/', '')
1740 lines = output.getvalue().splitlines()
1741 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001742
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001743
Benjamin Peterson9566de12014-12-13 16:13:24 -05001744@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001745def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001746 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
R David Murraycae7bdb2015-04-05 19:26:29 -04001747 PersistenceTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001748 HTTPSTest, RequestBodyTest, SourceAddressTest,
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001749 HTTPResponseTest, ExtendedReadTest,
Senthil Kumaran166214c2014-04-14 13:10:05 -04001750 ExtendedReadTestChunked, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001751
Thomas Wouters89f507f2006-12-13 04:49:30 +00001752if __name__ == '__main__':
1753 test_main()