blob: df9a9e3cbdabc2d67915d8e5fcadbb1b69a05616 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +000022HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000023
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000024class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040025 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000026 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000027 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000028 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000029 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000030 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010031 self.sendall_calls = 0
Serhiy Storchakab491e052014-12-01 13:07:45 +020032 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040033 self.host = host
34 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000035
Jeremy Hylton2c178252004-08-07 16:28:14 +000036 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010037 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000038 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000039
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000040 def makefile(self, mode, bufsize=None):
41 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000042 raise client.UnimplementedFileMode()
Serhiy Storchakab491e052014-12-01 13:07:45 +020043 # keep the file around so we can check how much was read from it
44 self.file = self.fileclass(self.text)
45 self.file.close = self.file_close #nerf close ()
46 return self.file
47
48 def file_close(self):
49 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000050
Senthil Kumaran9da047b2014-04-14 13:07:56 -040051 def close(self):
52 pass
53
Jeremy Hylton636950f2009-03-28 04:34:21 +000054class EPipeSocket(FakeSocket):
55
56 def __init__(self, text, pipe_trigger):
57 # When sendall() is called with pipe_trigger, raise EPIPE.
58 FakeSocket.__init__(self, text)
59 self.pipe_trigger = pipe_trigger
60
61 def sendall(self, data):
62 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020063 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000064 self.data += data
65
66 def close(self):
67 pass
68
Serhiy Storchaka50254c52013-08-29 11:35:43 +030069class NoEOFBytesIO(io.BytesIO):
70 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000071
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000072 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000073 more from the underlying file than it should.
74 """
75 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000076 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000077 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000078 raise AssertionError('caller tried to read past EOF')
79 return data
80
81 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000082 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000083 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000084 raise AssertionError('caller tried to read past EOF')
85 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000086
Jeremy Hylton2c178252004-08-07 16:28:14 +000087class HeaderTests(TestCase):
88 def test_auto_headers(self):
89 # Some headers are added automatically, but should not be added by
90 # .request() if they are explicitly set.
91
Jeremy Hylton2c178252004-08-07 16:28:14 +000092 class HeaderCountingBuffer(list):
93 def __init__(self):
94 self.count = {}
95 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000096 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000097 if len(kv) > 1:
98 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000099 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000100 self.count.setdefault(lcKey, 0)
101 self.count[lcKey] += 1
102 list.append(self, item)
103
104 for explicit_header in True, False:
105 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000106 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000107 conn.sock = FakeSocket('blahblahblah')
108 conn._buffer = HeaderCountingBuffer()
109
110 body = 'spamspamspam'
111 headers = {}
112 if explicit_header:
113 headers[header] = str(len(body))
114 conn.request('POST', '/', body, headers)
115 self.assertEqual(conn._buffer.count[header.lower()], 1)
116
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800117 def test_content_length_0(self):
118
119 class ContentLengthChecker(list):
120 def __init__(self):
121 list.__init__(self)
122 self.content_length = None
123 def append(self, item):
124 kv = item.split(b':', 1)
125 if len(kv) > 1 and kv[0].lower() == b'content-length':
126 self.content_length = kv[1].strip()
127 list.append(self, item)
128
R David Murraybeed8402015-03-22 15:18:23 -0400129 # Here, we're testing that methods expecting a body get a
130 # content-length set to zero if the body is empty (either None or '')
131 bodies = (None, '')
132 methods_with_body = ('PUT', 'POST', 'PATCH')
133 for method, body in itertools.product(methods_with_body, bodies):
134 conn = client.HTTPConnection('example.com')
135 conn.sock = FakeSocket(None)
136 conn._buffer = ContentLengthChecker()
137 conn.request(method, '/', body)
138 self.assertEqual(
139 conn._buffer.content_length, b'0',
140 'Header Content-Length incorrect on {}'.format(method)
141 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800142
R David Murraybeed8402015-03-22 15:18:23 -0400143 # For these methods, we make sure that content-length is not set when
144 # the body is None because it might cause unexpected behaviour on the
145 # server.
146 methods_without_body = (
147 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
148 )
149 for method in methods_without_body:
150 conn = client.HTTPConnection('example.com')
151 conn.sock = FakeSocket(None)
152 conn._buffer = ContentLengthChecker()
153 conn.request(method, '/', None)
154 self.assertEqual(
155 conn._buffer.content_length, None,
156 'Header Content-Length set for empty body on {}'.format(method)
157 )
158
159 # If the body is set to '', that's considered to be "present but
160 # empty" rather than "missing", so content length would be set, even
161 # for methods that don't expect a body.
162 for method in methods_without_body:
163 conn = client.HTTPConnection('example.com')
164 conn.sock = FakeSocket(None)
165 conn._buffer = ContentLengthChecker()
166 conn.request(method, '/', '')
167 self.assertEqual(
168 conn._buffer.content_length, b'0',
169 'Header Content-Length incorrect on {}'.format(method)
170 )
171
172 # If the body is set, make sure Content-Length is set.
173 for method in itertools.chain(methods_without_body, methods_with_body):
174 conn = client.HTTPConnection('example.com')
175 conn.sock = FakeSocket(None)
176 conn._buffer = ContentLengthChecker()
177 conn.request(method, '/', ' ')
178 self.assertEqual(
179 conn._buffer.content_length, b'1',
180 'Header Content-Length incorrect on {}'.format(method)
181 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800182
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000183 def test_putheader(self):
184 conn = client.HTTPConnection('example.com')
185 conn.sock = FakeSocket(None)
186 conn.putrequest('GET','/')
187 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200188 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000189
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200190 conn.putheader('Foo', ' bar ')
191 self.assertIn(b'Foo: bar ', conn._buffer)
192 conn.putheader('Bar', '\tbaz\t')
193 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
194 conn.putheader('Authorization', 'Bearer mytoken')
195 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
196 conn.putheader('IterHeader', 'IterA', 'IterB')
197 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
198 conn.putheader('LatinHeader', b'\xFF')
199 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
200 conn.putheader('Utf8Header', b'\xc3\x80')
201 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
202 conn.putheader('C1-Control', b'next\x85line')
203 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
204 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
205 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
206 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
207 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
208 conn.putheader('Key Space', 'value')
209 self.assertIn(b'Key Space: value', conn._buffer)
210 conn.putheader('KeySpace ', 'value')
211 self.assertIn(b'KeySpace : value', conn._buffer)
212 conn.putheader(b'Nonbreak\xa0Space', 'value')
213 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
214 conn.putheader(b'\xa0NonbreakSpace', 'value')
215 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
216
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000217 def test_ipv6host_header(self):
218 # Default host header on IPv6 transaction should wrapped by [] if
219 # its actual IPv6 address
220 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
221 b'Accept-Encoding: identity\r\n\r\n'
222 conn = client.HTTPConnection('[2001::]:81')
223 sock = FakeSocket('')
224 conn.sock = sock
225 conn.request('GET', '/foo')
226 self.assertTrue(sock.data.startswith(expected))
227
228 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
229 b'Accept-Encoding: identity\r\n\r\n'
230 conn = client.HTTPConnection('[2001:102A::]')
231 sock = FakeSocket('')
232 conn.sock = sock
233 conn.request('GET', '/foo')
234 self.assertTrue(sock.data.startswith(expected))
235
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500236 def test_malformed_headers_coped_with(self):
237 # Issue 19996
238 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
239 sock = FakeSocket(body)
240 resp = client.HTTPResponse(sock)
241 resp.begin()
242
243 self.assertEqual(resp.getheader('First'), 'val')
244 self.assertEqual(resp.getheader('Second'), 'val')
245
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200246 def test_invalid_headers(self):
247 conn = client.HTTPConnection('example.com')
248 conn.sock = FakeSocket('')
249 conn.putrequest('GET', '/')
250
251 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
252 # longer allowed in header names
253 cases = (
254 (b'Invalid\r\nName', b'ValidValue'),
255 (b'Invalid\rName', b'ValidValue'),
256 (b'Invalid\nName', b'ValidValue'),
257 (b'\r\nInvalidName', b'ValidValue'),
258 (b'\rInvalidName', b'ValidValue'),
259 (b'\nInvalidName', b'ValidValue'),
260 (b' InvalidName', b'ValidValue'),
261 (b'\tInvalidName', b'ValidValue'),
262 (b'Invalid:Name', b'ValidValue'),
263 (b':InvalidName', b'ValidValue'),
264 (b'ValidName', b'Invalid\r\nValue'),
265 (b'ValidName', b'Invalid\rValue'),
266 (b'ValidName', b'Invalid\nValue'),
267 (b'ValidName', b'InvalidValue\r\n'),
268 (b'ValidName', b'InvalidValue\r'),
269 (b'ValidName', b'InvalidValue\n'),
270 )
271 for name, value in cases:
272 with self.subTest((name, value)):
273 with self.assertRaisesRegex(ValueError, 'Invalid header'):
274 conn.putheader(name, value)
275
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000276
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277class BasicTest(TestCase):
278 def test_status_lines(self):
279 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000280
Thomas Wouters89f507f2006-12-13 04:49:30 +0000281 body = "HTTP/1.1 200 Ok\r\n\r\nText"
282 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000283 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000284 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200285 self.assertEqual(resp.read(0), b'') # Issue #20007
286 self.assertFalse(resp.isclosed())
287 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000288 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000289 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200290 self.assertFalse(resp.closed)
291 resp.close()
292 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000293
Thomas Wouters89f507f2006-12-13 04:49:30 +0000294 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
295 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000296 resp = client.HTTPResponse(sock)
297 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000298
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000299 def test_bad_status_repr(self):
300 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000301 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000302
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000303 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100304 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000305 # same behaviour than when we read the whole thing with read()
306 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
307 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000308 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000309 resp.begin()
310 self.assertEqual(resp.read(2), b'Te')
311 self.assertFalse(resp.isclosed())
312 self.assertEqual(resp.read(2), b'xt')
313 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200314 self.assertFalse(resp.closed)
315 resp.close()
316 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000317
Antoine Pitrou38d96432011-12-06 22:33:57 +0100318 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100319 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100320 # same behaviour than when we read the whole thing with read()
321 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
322 sock = FakeSocket(body)
323 resp = client.HTTPResponse(sock)
324 resp.begin()
325 b = bytearray(2)
326 n = resp.readinto(b)
327 self.assertEqual(n, 2)
328 self.assertEqual(bytes(b), b'Te')
329 self.assertFalse(resp.isclosed())
330 n = resp.readinto(b)
331 self.assertEqual(n, 2)
332 self.assertEqual(bytes(b), b'xt')
333 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200334 self.assertFalse(resp.closed)
335 resp.close()
336 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100337
Antoine Pitrou084daa22012-12-15 19:11:54 +0100338 def test_partial_reads_no_content_length(self):
339 # when no length is present, the socket should be gracefully closed when
340 # all data was read
341 body = "HTTP/1.1 200 Ok\r\n\r\nText"
342 sock = FakeSocket(body)
343 resp = client.HTTPResponse(sock)
344 resp.begin()
345 self.assertEqual(resp.read(2), b'Te')
346 self.assertFalse(resp.isclosed())
347 self.assertEqual(resp.read(2), b'xt')
348 self.assertEqual(resp.read(1), b'')
349 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200350 self.assertFalse(resp.closed)
351 resp.close()
352 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100353
Antoine Pitroud20e7742012-12-15 19:22:30 +0100354 def test_partial_readintos_no_content_length(self):
355 # when no length is present, the socket should be gracefully closed when
356 # all data was read
357 body = "HTTP/1.1 200 Ok\r\n\r\nText"
358 sock = FakeSocket(body)
359 resp = client.HTTPResponse(sock)
360 resp.begin()
361 b = bytearray(2)
362 n = resp.readinto(b)
363 self.assertEqual(n, 2)
364 self.assertEqual(bytes(b), b'Te')
365 self.assertFalse(resp.isclosed())
366 n = resp.readinto(b)
367 self.assertEqual(n, 2)
368 self.assertEqual(bytes(b), b'xt')
369 n = resp.readinto(b)
370 self.assertEqual(n, 0)
371 self.assertTrue(resp.isclosed())
372
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100373 def test_partial_reads_incomplete_body(self):
374 # if the server shuts down the connection before the whole
375 # content-length is delivered, the socket is gracefully closed
376 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
377 sock = FakeSocket(body)
378 resp = client.HTTPResponse(sock)
379 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.assertEqual(resp.read(1), b'')
384 self.assertTrue(resp.isclosed())
385
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100386 def test_partial_readintos_incomplete_body(self):
387 # if the server shuts down the connection before the whole
388 # content-length is delivered, the socket is gracefully closed
389 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
390 sock = FakeSocket(body)
391 resp = client.HTTPResponse(sock)
392 resp.begin()
393 b = bytearray(2)
394 n = resp.readinto(b)
395 self.assertEqual(n, 2)
396 self.assertEqual(bytes(b), b'Te')
397 self.assertFalse(resp.isclosed())
398 n = resp.readinto(b)
399 self.assertEqual(n, 2)
400 self.assertEqual(bytes(b), b'xt')
401 n = resp.readinto(b)
402 self.assertEqual(n, 0)
403 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200404 self.assertFalse(resp.closed)
405 resp.close()
406 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100407
Thomas Wouters89f507f2006-12-13 04:49:30 +0000408 def test_host_port(self):
409 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000410
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200411 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000412 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000413
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000414 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
415 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000416 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200417 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000418 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200419 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
420 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000421 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000422 self.assertEqual(h, c.host)
423 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000424
Thomas Wouters89f507f2006-12-13 04:49:30 +0000425 def test_response_headers(self):
426 # test response with multiple message headers with the same field name.
427 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000428 'Set-Cookie: Customer="WILE_E_COYOTE"; '
429 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000430 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
431 ' Path="/acme"\r\n'
432 '\r\n'
433 'No body\r\n')
434 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
435 ', '
436 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
437 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000438 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439 r.begin()
440 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000441 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000442
Thomas Wouters89f507f2006-12-13 04:49:30 +0000443 def test_read_head(self):
444 # Test that the library doesn't attempt to read any data
445 # from a HEAD request. (Tickles SF bug #622042.)
446 sock = FakeSocket(
447 'HTTP/1.1 200 OK\r\n'
448 'Content-Length: 14432\r\n'
449 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300450 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000451 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000452 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000453 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000454 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000455
Antoine Pitrou38d96432011-12-06 22:33:57 +0100456 def test_readinto_head(self):
457 # Test that the library doesn't attempt to read any data
458 # from a HEAD request. (Tickles SF bug #622042.)
459 sock = FakeSocket(
460 'HTTP/1.1 200 OK\r\n'
461 'Content-Length: 14432\r\n'
462 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300463 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100464 resp = client.HTTPResponse(sock, method="HEAD")
465 resp.begin()
466 b = bytearray(5)
467 if resp.readinto(b) != 0:
468 self.fail("Did not expect response from HEAD request")
469 self.assertEqual(bytes(b), b'\x00'*5)
470
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100471 def test_too_many_headers(self):
472 headers = '\r\n'.join('Header%d: foo' % i
473 for i in range(client._MAXHEADERS + 1)) + '\r\n'
474 text = ('HTTP/1.1 200 OK\r\n' + headers)
475 s = FakeSocket(text)
476 r = client.HTTPResponse(s)
477 self.assertRaisesRegex(client.HTTPException,
478 r"got more than \d+ headers", r.begin)
479
Thomas Wouters89f507f2006-12-13 04:49:30 +0000480 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000481 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
482 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000483
Brett Cannon77b7de62010-10-29 23:31:11 +0000484 with open(__file__, 'rb') as body:
485 conn = client.HTTPConnection('example.com')
486 sock = FakeSocket(body)
487 conn.sock = sock
488 conn.request('GET', '/foo', body)
489 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
490 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000491
Antoine Pitrouead1d622009-09-29 18:44:53 +0000492 def test_send(self):
493 expected = b'this is a test this is only a test'
494 conn = client.HTTPConnection('example.com')
495 sock = FakeSocket(None)
496 conn.sock = sock
497 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000498 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000499 sock.data = b''
500 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000501 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000502 sock.data = b''
503 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000504 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000505
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300506 def test_send_updating_file(self):
507 def data():
508 yield 'data'
509 yield None
510 yield 'data_two'
511
512 class UpdatingFile():
513 mode = 'r'
514 d = data()
515 def read(self, blocksize=-1):
516 return self.d.__next__()
517
518 expected = b'data'
519
520 conn = client.HTTPConnection('example.com')
521 sock = FakeSocket("")
522 conn.sock = sock
523 conn.send(UpdatingFile())
524 self.assertEqual(sock.data, expected)
525
526
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000527 def test_send_iter(self):
528 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
529 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
530 b'\r\nonetwothree'
531
532 def body():
533 yield b"one"
534 yield b"two"
535 yield b"three"
536
537 conn = client.HTTPConnection('example.com')
538 sock = FakeSocket("")
539 conn.sock = sock
540 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000541 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000542
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800543 def test_send_type_error(self):
544 # See: Issue #12676
545 conn = client.HTTPConnection('example.com')
546 conn.sock = FakeSocket('')
547 with self.assertRaises(TypeError):
548 conn.request('POST', 'test', conn)
549
Christian Heimesa612dc02008-02-24 13:08:18 +0000550 def test_chunked(self):
551 chunked_start = (
552 'HTTP/1.1 200 OK\r\n'
553 'Transfer-Encoding: chunked\r\n\r\n'
554 'a\r\n'
555 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100556 '3\r\n'
557 'd! \r\n'
558 '8\r\n'
559 'and now \r\n'
560 '22\r\n'
561 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000562 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100563 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000564 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000565 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000566 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100567 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000568 resp.close()
569
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100570 # Various read sizes
571 for n in range(1, 12):
572 sock = FakeSocket(chunked_start + '0\r\n')
573 resp = client.HTTPResponse(sock, method="GET")
574 resp.begin()
575 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
576 resp.close()
577
Christian Heimesa612dc02008-02-24 13:08:18 +0000578 for x in ('', 'foo\r\n'):
579 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000580 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000581 resp.begin()
582 try:
583 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000584 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100585 self.assertEqual(i.partial, expected)
586 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
587 self.assertEqual(repr(i), expected_message)
588 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000589 else:
590 self.fail('IncompleteRead expected')
591 finally:
592 resp.close()
593
Antoine Pitrou38d96432011-12-06 22:33:57 +0100594 def test_readinto_chunked(self):
595 chunked_start = (
596 'HTTP/1.1 200 OK\r\n'
597 'Transfer-Encoding: chunked\r\n\r\n'
598 'a\r\n'
599 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100600 '3\r\n'
601 'd! \r\n'
602 '8\r\n'
603 'and now \r\n'
604 '22\r\n'
605 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100606 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100607 expected = b'hello world! and now for something completely different'
608 nexpected = len(expected)
609 b = bytearray(128)
610
Antoine Pitrou38d96432011-12-06 22:33:57 +0100611 sock = FakeSocket(chunked_start + '0\r\n')
612 resp = client.HTTPResponse(sock, method="GET")
613 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100614 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100615 self.assertEqual(b[:nexpected], expected)
616 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100617 resp.close()
618
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100619 # Various read sizes
620 for n in range(1, 12):
621 sock = FakeSocket(chunked_start + '0\r\n')
622 resp = client.HTTPResponse(sock, method="GET")
623 resp.begin()
624 m = memoryview(b)
625 i = resp.readinto(m[0:n])
626 i += resp.readinto(m[i:n + i])
627 i += resp.readinto(m[i:])
628 self.assertEqual(b[:nexpected], expected)
629 self.assertEqual(i, nexpected)
630 resp.close()
631
Antoine Pitrou38d96432011-12-06 22:33:57 +0100632 for x in ('', 'foo\r\n'):
633 sock = FakeSocket(chunked_start + x)
634 resp = client.HTTPResponse(sock, method="GET")
635 resp.begin()
636 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100637 n = resp.readinto(b)
638 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100639 self.assertEqual(i.partial, expected)
640 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
641 self.assertEqual(repr(i), expected_message)
642 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100643 else:
644 self.fail('IncompleteRead expected')
645 finally:
646 resp.close()
647
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000648 def test_chunked_head(self):
649 chunked_start = (
650 'HTTP/1.1 200 OK\r\n'
651 'Transfer-Encoding: chunked\r\n\r\n'
652 'a\r\n'
653 'hello world\r\n'
654 '1\r\n'
655 'd\r\n'
656 )
657 sock = FakeSocket(chunked_start + '0\r\n')
658 resp = client.HTTPResponse(sock, method="HEAD")
659 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000660 self.assertEqual(resp.read(), b'')
661 self.assertEqual(resp.status, 200)
662 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000663 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200664 self.assertFalse(resp.closed)
665 resp.close()
666 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000667
Antoine Pitrou38d96432011-12-06 22:33:57 +0100668 def test_readinto_chunked_head(self):
669 chunked_start = (
670 'HTTP/1.1 200 OK\r\n'
671 'Transfer-Encoding: chunked\r\n\r\n'
672 'a\r\n'
673 'hello world\r\n'
674 '1\r\n'
675 'd\r\n'
676 )
677 sock = FakeSocket(chunked_start + '0\r\n')
678 resp = client.HTTPResponse(sock, method="HEAD")
679 resp.begin()
680 b = bytearray(5)
681 n = resp.readinto(b)
682 self.assertEqual(n, 0)
683 self.assertEqual(bytes(b), b'\x00'*5)
684 self.assertEqual(resp.status, 200)
685 self.assertEqual(resp.reason, 'OK')
686 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200687 self.assertFalse(resp.closed)
688 resp.close()
689 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100690
Christian Heimesa612dc02008-02-24 13:08:18 +0000691 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000692 sock = FakeSocket(
693 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000694 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000695 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000696 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100697 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000698
Benjamin Peterson6accb982009-03-02 22:50:25 +0000699 def test_incomplete_read(self):
700 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000701 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000702 resp.begin()
703 try:
704 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000705 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000706 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000707 self.assertEqual(repr(i),
708 "IncompleteRead(7 bytes read, 3 more expected)")
709 self.assertEqual(str(i),
710 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100711 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000712 else:
713 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000714
Jeremy Hylton636950f2009-03-28 04:34:21 +0000715 def test_epipe(self):
716 sock = EPipeSocket(
717 "HTTP/1.0 401 Authorization Required\r\n"
718 "Content-type: text/html\r\n"
719 "WWW-Authenticate: Basic realm=\"example\"\r\n",
720 b"Content-Length")
721 conn = client.HTTPConnection("example.com")
722 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200723 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000724 lambda: conn.request("PUT", "/url", "body"))
725 resp = conn.getresponse()
726 self.assertEqual(401, resp.status)
727 self.assertEqual("Basic realm=\"example\"",
728 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000729
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000730 # Test lines overflowing the max line size (_MAXLINE in http.client)
731
732 def test_overflowing_status_line(self):
733 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
734 resp = client.HTTPResponse(FakeSocket(body))
735 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
736
737 def test_overflowing_header_line(self):
738 body = (
739 'HTTP/1.1 200 OK\r\n'
740 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
741 )
742 resp = client.HTTPResponse(FakeSocket(body))
743 self.assertRaises(client.LineTooLong, resp.begin)
744
745 def test_overflowing_chunked_line(self):
746 body = (
747 'HTTP/1.1 200 OK\r\n'
748 'Transfer-Encoding: chunked\r\n\r\n'
749 + '0' * 65536 + 'a\r\n'
750 'hello world\r\n'
751 '0\r\n'
752 )
753 resp = client.HTTPResponse(FakeSocket(body))
754 resp.begin()
755 self.assertRaises(client.LineTooLong, resp.read)
756
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800757 def test_early_eof(self):
758 # Test httpresponse with no \r\n termination,
759 body = "HTTP/1.1 200 Ok"
760 sock = FakeSocket(body)
761 resp = client.HTTPResponse(sock)
762 resp.begin()
763 self.assertEqual(resp.read(), b'')
764 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200765 self.assertFalse(resp.closed)
766 resp.close()
767 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800768
Antoine Pitrou90e47742013-01-02 22:10:47 +0100769 def test_delayed_ack_opt(self):
770 # Test that Nagle/delayed_ack optimistaion works correctly.
771
772 # For small payloads, it should coalesce the body with
773 # headers, resulting in a single sendall() call
774 conn = client.HTTPConnection('example.com')
775 sock = FakeSocket(None)
776 conn.sock = sock
777 body = b'x' * (conn.mss - 1)
778 conn.request('POST', '/', body)
779 self.assertEqual(sock.sendall_calls, 1)
780
781 # For large payloads, it should send the headers and
782 # then the body, resulting in more than one sendall()
783 # call
784 conn = client.HTTPConnection('example.com')
785 sock = FakeSocket(None)
786 conn.sock = sock
787 body = b'x' * conn.mss
788 conn.request('POST', '/', body)
789 self.assertGreater(sock.sendall_calls, 1)
790
Serhiy Storchakab491e052014-12-01 13:07:45 +0200791 def test_error_leak(self):
792 # Test that the socket is not leaked if getresponse() fails
793 conn = client.HTTPConnection('example.com')
794 response = None
795 class Response(client.HTTPResponse):
796 def __init__(self, *pos, **kw):
797 nonlocal response
798 response = self # Avoid garbage collector closing the socket
799 client.HTTPResponse.__init__(self, *pos, **kw)
800 conn.response_class = Response
801 conn.sock = FakeSocket('') # Emulate server dropping connection
802 conn.request('GET', '/')
803 self.assertRaises(client.BadStatusLine, conn.getresponse)
804 self.assertTrue(response.closed)
805 self.assertTrue(conn.sock.file_closed)
806
Berker Peksagbabc6882015-02-20 09:39:38 +0200807
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000808class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +0200809 def test_all(self):
810 # Documented objects defined in the module should be in __all__
811 expected = {"responses"} # White-list documented dict() object
812 # HTTPMessage, parse_headers(), and the HTTP status code constants are
813 # intentionally omitted for simplicity
814 blacklist = {"HTTPMessage", "parse_headers"}
815 for name in dir(client):
816 if name in blacklist:
817 continue
818 module_object = getattr(client, name)
819 if getattr(module_object, "__module__", None) == "http.client":
820 expected.add(name)
821 self.assertCountEqual(client.__all__, expected)
822
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000823 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000824 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000825
Gregory P. Smithb4066372010-01-03 03:28:29 +0000826
827class SourceAddressTest(TestCase):
828 def setUp(self):
829 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
830 self.port = support.bind_port(self.serv)
831 self.source_port = support.find_unused_port()
832 self.serv.listen(5)
833 self.conn = None
834
835 def tearDown(self):
836 if self.conn:
837 self.conn.close()
838 self.conn = None
839 self.serv.close()
840 self.serv = None
841
842 def testHTTPConnectionSourceAddress(self):
843 self.conn = client.HTTPConnection(HOST, self.port,
844 source_address=('', self.source_port))
845 self.conn.connect()
846 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
847
848 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
849 'http.client.HTTPSConnection not defined')
850 def testHTTPSConnectionSourceAddress(self):
851 self.conn = client.HTTPSConnection(HOST, self.port,
852 source_address=('', self.source_port))
853 # We don't test anything here other the constructor not barfing as
854 # this code doesn't deal with setting up an active running SSL server
855 # for an ssl_wrapped connect() to actually return from.
856
857
Guido van Rossumd8faa362007-04-27 19:54:29 +0000858class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000859 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000860
861 def setUp(self):
862 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000863 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000864 self.serv.listen(5)
865
866 def tearDown(self):
867 self.serv.close()
868 self.serv = None
869
870 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000871 # This will prove that the timeout gets through HTTPConnection
872 # and into the socket.
873
Georg Brandlf78e02b2008-06-10 17:40:04 +0000874 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200875 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000876 socket.setdefaulttimeout(30)
877 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000878 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000879 httpConn.connect()
880 finally:
881 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000882 self.assertEqual(httpConn.sock.gettimeout(), 30)
883 httpConn.close()
884
Georg Brandlf78e02b2008-06-10 17:40:04 +0000885 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200886 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000887 socket.setdefaulttimeout(30)
888 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000889 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000890 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000891 httpConn.connect()
892 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000893 socket.setdefaulttimeout(None)
894 self.assertEqual(httpConn.sock.gettimeout(), None)
895 httpConn.close()
896
897 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000898 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000899 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000900 self.assertEqual(httpConn.sock.gettimeout(), 30)
901 httpConn.close()
902
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000903
904class HTTPSTest(TestCase):
905
906 def setUp(self):
907 if not hasattr(client, 'HTTPSConnection'):
908 self.skipTest('ssl support required')
909
910 def make_server(self, certfile):
911 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100912 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000913
914 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000915 # simple test to check it's storing the timeout
916 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
917 self.assertEqual(h.timeout, 30)
918
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000919 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500920 # Default settings: requires a valid cert from a trusted CA
921 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000922 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500923 with support.transient_internet('self-signed.pythontest.net'):
924 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
925 with self.assertRaises(ssl.SSLError) as exc_info:
926 h.request('GET', '/')
927 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
928
929 def test_networked_noverification(self):
930 # Switch off cert verification
931 import ssl
932 support.requires('network')
933 with support.transient_internet('self-signed.pythontest.net'):
934 context = ssl._create_unverified_context()
935 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
936 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000937 h.request('GET', '/')
938 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +0100939 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500940 self.assertIn('nginx', resp.getheader('server'))
941
Benjamin Peterson2615e9e2014-11-25 15:16:55 -0600942 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500943 def test_networked_trusted_by_default_cert(self):
944 # Default settings: requires a valid cert from a trusted CA
945 support.requires('network')
946 with support.transient_internet('www.python.org'):
947 h = client.HTTPSConnection('www.python.org', 443)
948 h.request('GET', '/')
949 resp = h.getresponse()
950 content_type = resp.getheader('content-type')
Victor Stinnerb389b482015-02-27 17:47:23 +0100951 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500952 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000953
954 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +0100955 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000956 import ssl
957 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +0100958 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000959 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
960 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +0100961 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
962 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000963 h.request('GET', '/')
964 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +0100965 server_string = resp.getheader('server')
Victor Stinnerb389b482015-02-27 17:47:23 +0100966 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +0100967 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000968
969 def test_networked_bad_cert(self):
970 # We feed a "CA" cert that is unrelated to the server's cert
971 import ssl
972 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500973 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000974 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
975 context.verify_mode = ssl.CERT_REQUIRED
976 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500977 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
978 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000979 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500980 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
981
982 def test_local_unknown_cert(self):
983 # The custom cert isn't known to the default trust bundle
984 import ssl
985 server = self.make_server(CERT_localhost)
986 h = client.HTTPSConnection('localhost', server.port)
987 with self.assertRaises(ssl.SSLError) as exc_info:
988 h.request('GET', '/')
989 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000990
991 def test_local_good_hostname(self):
992 # The (valid) cert validates the HTTP hostname
993 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700994 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000995 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
996 context.verify_mode = ssl.CERT_REQUIRED
997 context.load_verify_locations(CERT_localhost)
998 h = client.HTTPSConnection('localhost', server.port, context=context)
999 h.request('GET', '/nonexistent')
1000 resp = h.getresponse()
1001 self.assertEqual(resp.status, 404)
1002
1003 def test_local_bad_hostname(self):
1004 # The (valid) cert doesn't validate the HTTP hostname
1005 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001006 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001007 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1008 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -05001009 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001010 context.load_verify_locations(CERT_fakehostname)
1011 h = client.HTTPSConnection('localhost', server.port, context=context)
1012 with self.assertRaises(ssl.CertificateError):
1013 h.request('GET', '/')
1014 # Same with explicit check_hostname=True
1015 h = client.HTTPSConnection('localhost', server.port, context=context,
1016 check_hostname=True)
1017 with self.assertRaises(ssl.CertificateError):
1018 h.request('GET', '/')
1019 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001020 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001021 h = client.HTTPSConnection('localhost', server.port, context=context,
1022 check_hostname=False)
1023 h.request('GET', '/nonexistent')
1024 resp = h.getresponse()
1025 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001026 # The context's check_hostname setting is used if one isn't passed to
1027 # HTTPSConnection.
1028 context.check_hostname = False
1029 h = client.HTTPSConnection('localhost', server.port, context=context)
1030 h.request('GET', '/nonexistent')
1031 self.assertEqual(h.getresponse().status, 404)
1032 # Passing check_hostname to HTTPSConnection should override the
1033 # context's setting.
1034 h = client.HTTPSConnection('localhost', server.port, context=context,
1035 check_hostname=True)
1036 with self.assertRaises(ssl.CertificateError):
1037 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001038
Petri Lehtinene119c402011-10-26 21:29:15 +03001039 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1040 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001041 def test_host_port(self):
1042 # Check invalid host_port
1043
1044 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1045 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1046
1047 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1048 "fe80::207:e9ff:fe9b", 8000),
1049 ("www.python.org:443", "www.python.org", 443),
1050 ("www.python.org:", "www.python.org", 443),
1051 ("www.python.org", "www.python.org", 443),
1052 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1053 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1054 443)):
1055 c = client.HTTPSConnection(hp)
1056 self.assertEqual(h, c.host)
1057 self.assertEqual(p, c.port)
1058
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001059
Jeremy Hylton236654b2009-03-27 20:24:34 +00001060class RequestBodyTest(TestCase):
1061 """Test cases where a request includes a message body."""
1062
1063 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001064 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001065 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001066 self.conn.sock = self.sock
1067
1068 def get_headers_and_fp(self):
1069 f = io.BytesIO(self.sock.data)
1070 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001071 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001072 return message, f
1073
1074 def test_manual_content_length(self):
1075 # Set an incorrect content-length so that we can verify that
1076 # it will not be over-ridden by the library.
1077 self.conn.request("PUT", "/url", "body",
1078 {"Content-Length": "42"})
1079 message, f = self.get_headers_and_fp()
1080 self.assertEqual("42", message.get("content-length"))
1081 self.assertEqual(4, len(f.read()))
1082
1083 def test_ascii_body(self):
1084 self.conn.request("PUT", "/url", "body")
1085 message, f = self.get_headers_and_fp()
1086 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001087 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001088 self.assertEqual("4", message.get("content-length"))
1089 self.assertEqual(b'body', f.read())
1090
1091 def test_latin1_body(self):
1092 self.conn.request("PUT", "/url", "body\xc1")
1093 message, f = self.get_headers_and_fp()
1094 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001095 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001096 self.assertEqual("5", message.get("content-length"))
1097 self.assertEqual(b'body\xc1', f.read())
1098
1099 def test_bytes_body(self):
1100 self.conn.request("PUT", "/url", b"body\xc1")
1101 message, f = self.get_headers_and_fp()
1102 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001103 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001104 self.assertEqual("5", message.get("content-length"))
1105 self.assertEqual(b'body\xc1', f.read())
1106
1107 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001108 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001109 with open(support.TESTFN, "w") as f:
1110 f.write("body")
1111 with open(support.TESTFN) as f:
1112 self.conn.request("PUT", "/url", f)
1113 message, f = self.get_headers_and_fp()
1114 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001115 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001116 self.assertEqual("4", message.get("content-length"))
1117 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001118
1119 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001120 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001121 with open(support.TESTFN, "wb") as f:
1122 f.write(b"body\xc1")
1123 with open(support.TESTFN, "rb") as f:
1124 self.conn.request("PUT", "/url", f)
1125 message, f = self.get_headers_and_fp()
1126 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001127 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001128 self.assertEqual("5", message.get("content-length"))
1129 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001130
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001131
1132class HTTPResponseTest(TestCase):
1133
1134 def setUp(self):
1135 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1136 second-value\r\n\r\nText"
1137 sock = FakeSocket(body)
1138 self.resp = client.HTTPResponse(sock)
1139 self.resp.begin()
1140
1141 def test_getting_header(self):
1142 header = self.resp.getheader('My-Header')
1143 self.assertEqual(header, 'first-value, second-value')
1144
1145 header = self.resp.getheader('My-Header', 'some default')
1146 self.assertEqual(header, 'first-value, second-value')
1147
1148 def test_getting_nonexistent_header_with_string_default(self):
1149 header = self.resp.getheader('No-Such-Header', 'default-value')
1150 self.assertEqual(header, 'default-value')
1151
1152 def test_getting_nonexistent_header_with_iterable_default(self):
1153 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1154 self.assertEqual(header, 'default, values')
1155
1156 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1157 self.assertEqual(header, 'default, values')
1158
1159 def test_getting_nonexistent_header_without_default(self):
1160 header = self.resp.getheader('No-Such-Header')
1161 self.assertEqual(header, None)
1162
1163 def test_getting_header_defaultint(self):
1164 header = self.resp.getheader('No-Such-Header',default=42)
1165 self.assertEqual(header, 42)
1166
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001167class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001168 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001169 response_text = (
1170 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1171 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1172 'Content-Length: 42\r\n\r\n'
1173 )
1174
1175 def create_connection(address, timeout=None, source_address=None):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001176 return FakeSocket(response_text, host=address[0], port=address[1])
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001177
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001178 self.host = 'proxy.com'
1179 self.conn = client.HTTPConnection(self.host)
1180 self.conn._create_connection = create_connection
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001181
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001182 def tearDown(self):
1183 self.conn.close()
1184
1185 def test_set_tunnel_host_port_headers(self):
1186 tunnel_host = 'destination.com'
1187 tunnel_port = 8888
1188 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1189 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1190 headers=tunnel_headers)
1191 self.conn.request('HEAD', '/', '')
1192 self.assertEqual(self.conn.sock.host, self.host)
1193 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1194 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1195 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1196 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1197
1198 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001199 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001200 self.conn.connect()
1201 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001202 'destination.com')
1203
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001204 def test_connect_with_tunnel(self):
1205 self.conn.set_tunnel('destination.com')
1206 self.conn.request('HEAD', '/', '')
1207 self.assertEqual(self.conn.sock.host, self.host)
1208 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1209 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001210 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001211 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1212 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001213
1214 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001215 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001216
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001217 def test_connect_put_request(self):
1218 self.conn.set_tunnel('destination.com')
1219 self.conn.request('PUT', '/', '')
1220 self.assertEqual(self.conn.sock.host, self.host)
1221 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1222 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1223 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1224
1225
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001226
Benjamin Peterson9566de12014-12-13 16:13:24 -05001227@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001228def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001229 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001230 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001231 HTTPResponseTest, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001232
Thomas Wouters89f507f2006-12-13 04:49:30 +00001233if __name__ == '__main__':
1234 test_main()