blob: b4ec63ce208615f92ce2c1a41ca2d1929c1782cc [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
Jeremy Hylton2c178252004-08-07 16:28:14 +0000110class HeaderTests(TestCase):
111 def test_auto_headers(self):
112 # Some headers are added automatically, but should not be added by
113 # .request() if they are explicitly set.
114
Jeremy Hylton2c178252004-08-07 16:28:14 +0000115 class HeaderCountingBuffer(list):
116 def __init__(self):
117 self.count = {}
118 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000119 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000120 if len(kv) > 1:
121 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000122 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000123 self.count.setdefault(lcKey, 0)
124 self.count[lcKey] += 1
125 list.append(self, item)
126
127 for explicit_header in True, False:
128 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000129 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000130 conn.sock = FakeSocket('blahblahblah')
131 conn._buffer = HeaderCountingBuffer()
132
133 body = 'spamspamspam'
134 headers = {}
135 if explicit_header:
136 headers[header] = str(len(body))
137 conn.request('POST', '/', body, headers)
138 self.assertEqual(conn._buffer.count[header.lower()], 1)
139
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800140 def test_content_length_0(self):
141
142 class ContentLengthChecker(list):
143 def __init__(self):
144 list.__init__(self)
145 self.content_length = None
146 def append(self, item):
147 kv = item.split(b':', 1)
148 if len(kv) > 1 and kv[0].lower() == b'content-length':
149 self.content_length = kv[1].strip()
150 list.append(self, item)
151
R David Murraybeed8402015-03-22 15:18:23 -0400152 # Here, we're testing that methods expecting a body get a
153 # content-length set to zero if the body is empty (either None or '')
154 bodies = (None, '')
155 methods_with_body = ('PUT', 'POST', 'PATCH')
156 for method, body in itertools.product(methods_with_body, bodies):
157 conn = client.HTTPConnection('example.com')
158 conn.sock = FakeSocket(None)
159 conn._buffer = ContentLengthChecker()
160 conn.request(method, '/', body)
161 self.assertEqual(
162 conn._buffer.content_length, b'0',
163 'Header Content-Length incorrect on {}'.format(method)
164 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800165
R David Murraybeed8402015-03-22 15:18:23 -0400166 # For these methods, we make sure that content-length is not set when
167 # the body is None because it might cause unexpected behaviour on the
168 # server.
169 methods_without_body = (
170 'GET', 'CONNECT', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE',
171 )
172 for method in methods_without_body:
173 conn = client.HTTPConnection('example.com')
174 conn.sock = FakeSocket(None)
175 conn._buffer = ContentLengthChecker()
176 conn.request(method, '/', None)
177 self.assertEqual(
178 conn._buffer.content_length, None,
179 'Header Content-Length set for empty body on {}'.format(method)
180 )
181
182 # If the body is set to '', that's considered to be "present but
183 # empty" rather than "missing", so content length would be set, even
184 # for methods that don't expect a body.
185 for method in methods_without_body:
186 conn = client.HTTPConnection('example.com')
187 conn.sock = FakeSocket(None)
188 conn._buffer = ContentLengthChecker()
189 conn.request(method, '/', '')
190 self.assertEqual(
191 conn._buffer.content_length, b'0',
192 'Header Content-Length incorrect on {}'.format(method)
193 )
194
195 # If the body is set, make sure Content-Length is set.
196 for method in itertools.chain(methods_without_body, methods_with_body):
197 conn = client.HTTPConnection('example.com')
198 conn.sock = FakeSocket(None)
199 conn._buffer = ContentLengthChecker()
200 conn.request(method, '/', ' ')
201 self.assertEqual(
202 conn._buffer.content_length, b'1',
203 'Header Content-Length incorrect on {}'.format(method)
204 )
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800205
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000206 def test_putheader(self):
207 conn = client.HTTPConnection('example.com')
208 conn.sock = FakeSocket(None)
209 conn.putrequest('GET','/')
210 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200211 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000212
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200213 conn.putheader('Foo', ' bar ')
214 self.assertIn(b'Foo: bar ', conn._buffer)
215 conn.putheader('Bar', '\tbaz\t')
216 self.assertIn(b'Bar: \tbaz\t', conn._buffer)
217 conn.putheader('Authorization', 'Bearer mytoken')
218 self.assertIn(b'Authorization: Bearer mytoken', conn._buffer)
219 conn.putheader('IterHeader', 'IterA', 'IterB')
220 self.assertIn(b'IterHeader: IterA\r\n\tIterB', conn._buffer)
221 conn.putheader('LatinHeader', b'\xFF')
222 self.assertIn(b'LatinHeader: \xFF', conn._buffer)
223 conn.putheader('Utf8Header', b'\xc3\x80')
224 self.assertIn(b'Utf8Header: \xc3\x80', conn._buffer)
225 conn.putheader('C1-Control', b'next\x85line')
226 self.assertIn(b'C1-Control: next\x85line', conn._buffer)
227 conn.putheader('Embedded-Fold-Space', 'is\r\n allowed')
228 self.assertIn(b'Embedded-Fold-Space: is\r\n allowed', conn._buffer)
229 conn.putheader('Embedded-Fold-Tab', 'is\r\n\tallowed')
230 self.assertIn(b'Embedded-Fold-Tab: is\r\n\tallowed', conn._buffer)
231 conn.putheader('Key Space', 'value')
232 self.assertIn(b'Key Space: value', conn._buffer)
233 conn.putheader('KeySpace ', 'value')
234 self.assertIn(b'KeySpace : value', conn._buffer)
235 conn.putheader(b'Nonbreak\xa0Space', 'value')
236 self.assertIn(b'Nonbreak\xa0Space: value', conn._buffer)
237 conn.putheader(b'\xa0NonbreakSpace', 'value')
238 self.assertIn(b'\xa0NonbreakSpace: value', conn._buffer)
239
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000240 def test_ipv6host_header(self):
241 # Default host header on IPv6 transaction should wrapped by [] if
242 # its actual IPv6 address
243 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
244 b'Accept-Encoding: identity\r\n\r\n'
245 conn = client.HTTPConnection('[2001::]:81')
246 sock = FakeSocket('')
247 conn.sock = sock
248 conn.request('GET', '/foo')
249 self.assertTrue(sock.data.startswith(expected))
250
251 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
252 b'Accept-Encoding: identity\r\n\r\n'
253 conn = client.HTTPConnection('[2001:102A::]')
254 sock = FakeSocket('')
255 conn.sock = sock
256 conn.request('GET', '/foo')
257 self.assertTrue(sock.data.startswith(expected))
258
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500259 def test_malformed_headers_coped_with(self):
260 # Issue 19996
261 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
262 sock = FakeSocket(body)
263 resp = client.HTTPResponse(sock)
264 resp.begin()
265
266 self.assertEqual(resp.getheader('First'), 'val')
267 self.assertEqual(resp.getheader('Second'), 'val')
268
Serhiy Storchakaa112a8a2015-03-12 11:13:36 +0200269 def test_invalid_headers(self):
270 conn = client.HTTPConnection('example.com')
271 conn.sock = FakeSocket('')
272 conn.putrequest('GET', '/')
273
274 # http://tools.ietf.org/html/rfc7230#section-3.2.4, whitespace is no
275 # longer allowed in header names
276 cases = (
277 (b'Invalid\r\nName', b'ValidValue'),
278 (b'Invalid\rName', b'ValidValue'),
279 (b'Invalid\nName', b'ValidValue'),
280 (b'\r\nInvalidName', b'ValidValue'),
281 (b'\rInvalidName', b'ValidValue'),
282 (b'\nInvalidName', b'ValidValue'),
283 (b' InvalidName', b'ValidValue'),
284 (b'\tInvalidName', b'ValidValue'),
285 (b'Invalid:Name', b'ValidValue'),
286 (b':InvalidName', b'ValidValue'),
287 (b'ValidName', b'Invalid\r\nValue'),
288 (b'ValidName', b'Invalid\rValue'),
289 (b'ValidName', b'Invalid\nValue'),
290 (b'ValidName', b'InvalidValue\r\n'),
291 (b'ValidName', b'InvalidValue\r'),
292 (b'ValidName', b'InvalidValue\n'),
293 )
294 for name, value in cases:
295 with self.subTest((name, value)):
296 with self.assertRaisesRegex(ValueError, 'Invalid header'):
297 conn.putheader(name, value)
298
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000299
Thomas Wouters89f507f2006-12-13 04:49:30 +0000300class BasicTest(TestCase):
301 def test_status_lines(self):
302 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000303
Thomas Wouters89f507f2006-12-13 04:49:30 +0000304 body = "HTTP/1.1 200 Ok\r\n\r\nText"
305 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000306 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000307 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200308 self.assertEqual(resp.read(0), b'') # Issue #20007
309 self.assertFalse(resp.isclosed())
310 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000311 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000312 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200313 self.assertFalse(resp.closed)
314 resp.close()
315 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000316
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
318 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000319 resp = client.HTTPResponse(sock)
320 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000321
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000322 def test_bad_status_repr(self):
323 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000324 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000325
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000326 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100327 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000328 # same behaviour than when we read the whole thing with read()
329 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
330 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000331 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000332 resp.begin()
333 self.assertEqual(resp.read(2), b'Te')
334 self.assertFalse(resp.isclosed())
335 self.assertEqual(resp.read(2), b'xt')
336 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200337 self.assertFalse(resp.closed)
338 resp.close()
339 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000340
Antoine Pitrou38d96432011-12-06 22:33:57 +0100341 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100342 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100343 # same behaviour than when we read the whole thing with read()
344 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
345 sock = FakeSocket(body)
346 resp = client.HTTPResponse(sock)
347 resp.begin()
348 b = bytearray(2)
349 n = resp.readinto(b)
350 self.assertEqual(n, 2)
351 self.assertEqual(bytes(b), b'Te')
352 self.assertFalse(resp.isclosed())
353 n = resp.readinto(b)
354 self.assertEqual(n, 2)
355 self.assertEqual(bytes(b), b'xt')
356 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200357 self.assertFalse(resp.closed)
358 resp.close()
359 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100360
Antoine Pitrou084daa22012-12-15 19:11:54 +0100361 def test_partial_reads_no_content_length(self):
362 # when no length is present, the socket should be gracefully closed when
363 # all data was read
364 body = "HTTP/1.1 200 Ok\r\n\r\nText"
365 sock = FakeSocket(body)
366 resp = client.HTTPResponse(sock)
367 resp.begin()
368 self.assertEqual(resp.read(2), b'Te')
369 self.assertFalse(resp.isclosed())
370 self.assertEqual(resp.read(2), b'xt')
371 self.assertEqual(resp.read(1), b'')
372 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200373 self.assertFalse(resp.closed)
374 resp.close()
375 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100376
Antoine Pitroud20e7742012-12-15 19:22:30 +0100377 def test_partial_readintos_no_content_length(self):
378 # when no length is present, the socket should be gracefully closed when
379 # all data was read
380 body = "HTTP/1.1 200 Ok\r\n\r\nText"
381 sock = FakeSocket(body)
382 resp = client.HTTPResponse(sock)
383 resp.begin()
384 b = bytearray(2)
385 n = resp.readinto(b)
386 self.assertEqual(n, 2)
387 self.assertEqual(bytes(b), b'Te')
388 self.assertFalse(resp.isclosed())
389 n = resp.readinto(b)
390 self.assertEqual(n, 2)
391 self.assertEqual(bytes(b), b'xt')
392 n = resp.readinto(b)
393 self.assertEqual(n, 0)
394 self.assertTrue(resp.isclosed())
395
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100396 def test_partial_reads_incomplete_body(self):
397 # if the server shuts down the connection before the whole
398 # content-length is delivered, the socket is gracefully closed
399 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
400 sock = FakeSocket(body)
401 resp = client.HTTPResponse(sock)
402 resp.begin()
403 self.assertEqual(resp.read(2), b'Te')
404 self.assertFalse(resp.isclosed())
405 self.assertEqual(resp.read(2), b'xt')
406 self.assertEqual(resp.read(1), b'')
407 self.assertTrue(resp.isclosed())
408
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100409 def test_partial_readintos_incomplete_body(self):
410 # if the server shuts down the connection before the whole
411 # content-length is delivered, the socket is gracefully closed
412 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
413 sock = FakeSocket(body)
414 resp = client.HTTPResponse(sock)
415 resp.begin()
416 b = bytearray(2)
417 n = resp.readinto(b)
418 self.assertEqual(n, 2)
419 self.assertEqual(bytes(b), b'Te')
420 self.assertFalse(resp.isclosed())
421 n = resp.readinto(b)
422 self.assertEqual(n, 2)
423 self.assertEqual(bytes(b), b'xt')
424 n = resp.readinto(b)
425 self.assertEqual(n, 0)
426 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200427 self.assertFalse(resp.closed)
428 resp.close()
429 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100430
Thomas Wouters89f507f2006-12-13 04:49:30 +0000431 def test_host_port(self):
432 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000433
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200434 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000435 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000436
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000437 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
438 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000439 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200440 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000441 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200442 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
443 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000444 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000445 self.assertEqual(h, c.host)
446 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000447
Thomas Wouters89f507f2006-12-13 04:49:30 +0000448 def test_response_headers(self):
449 # test response with multiple message headers with the same field name.
450 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000451 'Set-Cookie: Customer="WILE_E_COYOTE"; '
452 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000453 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
454 ' Path="/acme"\r\n'
455 '\r\n'
456 'No body\r\n')
457 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
458 ', '
459 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
460 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000461 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000462 r.begin()
463 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000464 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000465
Thomas Wouters89f507f2006-12-13 04:49:30 +0000466 def test_read_head(self):
467 # Test that the library doesn't attempt to read any data
468 # from a HEAD request. (Tickles SF bug #622042.)
469 sock = FakeSocket(
470 'HTTP/1.1 200 OK\r\n'
471 'Content-Length: 14432\r\n'
472 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300473 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000474 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000475 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000476 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000477 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000478
Antoine Pitrou38d96432011-12-06 22:33:57 +0100479 def test_readinto_head(self):
480 # Test that the library doesn't attempt to read any data
481 # from a HEAD request. (Tickles SF bug #622042.)
482 sock = FakeSocket(
483 'HTTP/1.1 200 OK\r\n'
484 'Content-Length: 14432\r\n'
485 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300486 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100487 resp = client.HTTPResponse(sock, method="HEAD")
488 resp.begin()
489 b = bytearray(5)
490 if resp.readinto(b) != 0:
491 self.fail("Did not expect response from HEAD request")
492 self.assertEqual(bytes(b), b'\x00'*5)
493
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100494 def test_too_many_headers(self):
495 headers = '\r\n'.join('Header%d: foo' % i
496 for i in range(client._MAXHEADERS + 1)) + '\r\n'
497 text = ('HTTP/1.1 200 OK\r\n' + headers)
498 s = FakeSocket(text)
499 r = client.HTTPResponse(s)
500 self.assertRaisesRegex(client.HTTPException,
501 r"got more than \d+ headers", r.begin)
502
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000504 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
505 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000506
Brett Cannon77b7de62010-10-29 23:31:11 +0000507 with open(__file__, 'rb') as body:
508 conn = client.HTTPConnection('example.com')
509 sock = FakeSocket(body)
510 conn.sock = sock
511 conn.request('GET', '/foo', body)
512 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
513 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000514
Antoine Pitrouead1d622009-09-29 18:44:53 +0000515 def test_send(self):
516 expected = b'this is a test this is only a test'
517 conn = client.HTTPConnection('example.com')
518 sock = FakeSocket(None)
519 conn.sock = sock
520 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000521 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000522 sock.data = b''
523 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000524 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000525 sock.data = b''
526 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000527 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000528
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300529 def test_send_updating_file(self):
530 def data():
531 yield 'data'
532 yield None
533 yield 'data_two'
534
535 class UpdatingFile():
536 mode = 'r'
537 d = data()
538 def read(self, blocksize=-1):
539 return self.d.__next__()
540
541 expected = b'data'
542
543 conn = client.HTTPConnection('example.com')
544 sock = FakeSocket("")
545 conn.sock = sock
546 conn.send(UpdatingFile())
547 self.assertEqual(sock.data, expected)
548
549
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000550 def test_send_iter(self):
551 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
552 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
553 b'\r\nonetwothree'
554
555 def body():
556 yield b"one"
557 yield b"two"
558 yield b"three"
559
560 conn = client.HTTPConnection('example.com')
561 sock = FakeSocket("")
562 conn.sock = sock
563 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000564 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000565
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800566 def test_send_type_error(self):
567 # See: Issue #12676
568 conn = client.HTTPConnection('example.com')
569 conn.sock = FakeSocket('')
570 with self.assertRaises(TypeError):
571 conn.request('POST', 'test', conn)
572
Christian Heimesa612dc02008-02-24 13:08:18 +0000573 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000574 expected = chunked_expected
575 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000576 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000577 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100578 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000579 resp.close()
580
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100581 # Various read sizes
582 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000583 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100584 resp = client.HTTPResponse(sock, method="GET")
585 resp.begin()
586 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
587 resp.close()
588
Christian Heimesa612dc02008-02-24 13:08:18 +0000589 for x in ('', 'foo\r\n'):
590 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000591 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000592 resp.begin()
593 try:
594 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000595 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100596 self.assertEqual(i.partial, expected)
597 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
598 self.assertEqual(repr(i), expected_message)
599 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000600 else:
601 self.fail('IncompleteRead expected')
602 finally:
603 resp.close()
604
Antoine Pitrou38d96432011-12-06 22:33:57 +0100605 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000606
607 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100608 nexpected = len(expected)
609 b = bytearray(128)
610
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000611 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100612 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):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000621 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100622 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 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000657 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000658 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 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000677 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100678 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'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000752 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000753 )
754 resp = client.HTTPResponse(FakeSocket(body))
755 resp.begin()
756 self.assertRaises(client.LineTooLong, resp.read)
757
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800758 def test_early_eof(self):
759 # Test httpresponse with no \r\n termination,
760 body = "HTTP/1.1 200 Ok"
761 sock = FakeSocket(body)
762 resp = client.HTTPResponse(sock)
763 resp.begin()
764 self.assertEqual(resp.read(), b'')
765 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200766 self.assertFalse(resp.closed)
767 resp.close()
768 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800769
Serhiy Storchakab491e052014-12-01 13:07:45 +0200770 def test_error_leak(self):
771 # Test that the socket is not leaked if getresponse() fails
772 conn = client.HTTPConnection('example.com')
773 response = None
774 class Response(client.HTTPResponse):
775 def __init__(self, *pos, **kw):
776 nonlocal response
777 response = self # Avoid garbage collector closing the socket
778 client.HTTPResponse.__init__(self, *pos, **kw)
779 conn.response_class = Response
780 conn.sock = FakeSocket('') # Emulate server dropping connection
781 conn.request('GET', '/')
782 self.assertRaises(client.BadStatusLine, conn.getresponse)
783 self.assertTrue(response.closed)
784 self.assertTrue(conn.sock.file_closed)
785
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000786 def test_chunked_extension(self):
787 extra = '3;foo=bar\r\n' + 'abc\r\n'
788 expected = chunked_expected + b'abc'
789
790 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
791 resp = client.HTTPResponse(sock, method="GET")
792 resp.begin()
793 self.assertEqual(resp.read(), expected)
794 resp.close()
795
796 def test_chunked_missing_end(self):
797 """some servers may serve up a short chunked encoding stream"""
798 expected = chunked_expected
799 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
800 resp = client.HTTPResponse(sock, method="GET")
801 resp.begin()
802 self.assertEqual(resp.read(), expected)
803 resp.close()
804
805 def test_chunked_trailers(self):
806 """See that trailers are read and ignored"""
807 expected = chunked_expected
808 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
809 resp = client.HTTPResponse(sock, method="GET")
810 resp.begin()
811 self.assertEqual(resp.read(), expected)
812 # we should have reached the end of the file
813 self.assertEqual(sock.file.read(100), b"") #we read to the end
814 resp.close()
815
816 def test_chunked_sync(self):
817 """Check that we don't read past the end of the chunked-encoding stream"""
818 expected = chunked_expected
819 extradata = "extradata"
820 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
821 resp = client.HTTPResponse(sock, method="GET")
822 resp.begin()
823 self.assertEqual(resp.read(), expected)
824 # the file should now have our extradata ready to be read
825 self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end
826 resp.close()
827
828 def test_content_length_sync(self):
829 """Check that we don't read past the end of the Content-Length stream"""
830 extradata = "extradata"
831 expected = b"Hello123\r\n"
832 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello123\r\n' + extradata)
833 resp = client.HTTPResponse(sock, method="GET")
834 resp.begin()
835 self.assertEqual(resp.read(), expected)
836 # the file should now have our extradata ready to be read
837 self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end
838 resp.close()
839
840class ExtendedReadTest(TestCase):
841 """
842 Test peek(), read1(), readline()
843 """
844 lines = (
845 'HTTP/1.1 200 OK\r\n'
846 '\r\n'
847 'hello world!\n'
848 'and now \n'
849 'for something completely different\n'
850 'foo'
851 )
852 lines_expected = lines[lines.find('hello'):].encode("ascii")
853 lines_chunked = (
854 'HTTP/1.1 200 OK\r\n'
855 'Transfer-Encoding: chunked\r\n\r\n'
856 'a\r\n'
857 'hello worl\r\n'
858 '3\r\n'
859 'd!\n\r\n'
860 '9\r\n'
861 'and now \n\r\n'
862 '23\r\n'
863 'for something completely different\n\r\n'
864 '3\r\n'
865 'foo\r\n'
866 '0\r\n' # terminating chunk
867 '\r\n' # end of trailers
868 )
869
870 def setUp(self):
871 sock = FakeSocket(self.lines)
872 resp = client.HTTPResponse(sock, method="GET")
873 resp.begin()
874 resp.fp = io.BufferedReader(resp.fp)
875 self.resp = resp
876
877
878
879 def test_peek(self):
880 resp = self.resp
881 # patch up the buffered peek so that it returns not too much stuff
882 oldpeek = resp.fp.peek
883 def mypeek(n=-1):
884 p = oldpeek(n)
885 if n >= 0:
886 return p[:n]
887 return p[:10]
888 resp.fp.peek = mypeek
889
890 all = []
891 while True:
892 # try a short peek
893 p = resp.peek(3)
894 if p:
895 self.assertGreater(len(p), 0)
896 # then unbounded peek
897 p2 = resp.peek()
898 self.assertGreaterEqual(len(p2), len(p))
899 self.assertTrue(p2.startswith(p))
900 next = resp.read(len(p2))
901 self.assertEqual(next, p2)
902 else:
903 next = resp.read()
904 self.assertFalse(next)
905 all.append(next)
906 if not next:
907 break
908 self.assertEqual(b"".join(all), self.lines_expected)
909
910 def test_readline(self):
911 resp = self.resp
912 self._verify_readline(self.resp.readline, self.lines_expected)
913
914 def _verify_readline(self, readline, expected):
915 all = []
916 while True:
917 # short readlines
918 line = readline(5)
919 if line and line != b"foo":
920 if len(line) < 5:
921 self.assertTrue(line.endswith(b"\n"))
922 all.append(line)
923 if not line:
924 break
925 self.assertEqual(b"".join(all), expected)
926
927 def test_read1(self):
928 resp = self.resp
929 def r():
930 res = resp.read1(4)
931 self.assertLessEqual(len(res), 4)
932 return res
933 readliner = Readliner(r)
934 self._verify_readline(readliner.readline, self.lines_expected)
935
936 def test_read1_unbounded(self):
937 resp = self.resp
938 all = []
939 while True:
940 data = resp.read1()
941 if not data:
942 break
943 all.append(data)
944 self.assertEqual(b"".join(all), self.lines_expected)
945
946 def test_read1_bounded(self):
947 resp = self.resp
948 all = []
949 while True:
950 data = resp.read1(10)
951 if not data:
952 break
953 self.assertLessEqual(len(data), 10)
954 all.append(data)
955 self.assertEqual(b"".join(all), self.lines_expected)
956
957 def test_read1_0(self):
958 self.assertEqual(self.resp.read1(0), b"")
959
960 def test_peek_0(self):
961 p = self.resp.peek(0)
962 self.assertLessEqual(0, len(p))
963
964class ExtendedReadTestChunked(ExtendedReadTest):
965 """
966 Test peek(), read1(), readline() in chunked mode
967 """
968 lines = (
969 'HTTP/1.1 200 OK\r\n'
970 'Transfer-Encoding: chunked\r\n\r\n'
971 'a\r\n'
972 'hello worl\r\n'
973 '3\r\n'
974 'd!\n\r\n'
975 '9\r\n'
976 'and now \n\r\n'
977 '23\r\n'
978 'for something completely different\n\r\n'
979 '3\r\n'
980 'foo\r\n'
981 '0\r\n' # terminating chunk
982 '\r\n' # end of trailers
983 )
984
985
986class Readliner:
987 """
988 a simple readline class that uses an arbitrary read function and buffering
989 """
990 def __init__(self, readfunc):
991 self.readfunc = readfunc
992 self.remainder = b""
993
994 def readline(self, limit):
995 data = []
996 datalen = 0
997 read = self.remainder
998 try:
999 while True:
1000 idx = read.find(b'\n')
1001 if idx != -1:
1002 break
1003 if datalen + len(read) >= limit:
1004 idx = limit - datalen - 1
1005 # read more data
1006 data.append(read)
1007 read = self.readfunc()
1008 if not read:
1009 idx = 0 #eof condition
1010 break
1011 idx += 1
1012 data.append(read[:idx])
1013 self.remainder = read[idx:]
1014 return b"".join(data)
1015 except:
1016 self.remainder = b"".join(data)
1017 raise
1018
Berker Peksagbabc6882015-02-20 09:39:38 +02001019
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001020class OfflineTest(TestCase):
Berker Peksagbabc6882015-02-20 09:39:38 +02001021 def test_all(self):
1022 # Documented objects defined in the module should be in __all__
1023 expected = {"responses"} # White-list documented dict() object
1024 # HTTPMessage, parse_headers(), and the HTTP status code constants are
1025 # intentionally omitted for simplicity
1026 blacklist = {"HTTPMessage", "parse_headers"}
1027 for name in dir(client):
1028 if name in blacklist:
1029 continue
1030 module_object = getattr(client, name)
1031 if getattr(module_object, "__module__", None) == "http.client":
1032 expected.add(name)
1033 self.assertCountEqual(client.__all__, expected)
1034
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001035 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +00001036 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +00001037
Berker Peksagabbf0f42015-02-20 14:57:31 +02001038 def test_client_constants(self):
1039 # Make sure we don't break backward compatibility with 3.4
1040 expected = [
1041 'CONTINUE',
1042 'SWITCHING_PROTOCOLS',
1043 'PROCESSING',
1044 'OK',
1045 'CREATED',
1046 'ACCEPTED',
1047 'NON_AUTHORITATIVE_INFORMATION',
1048 'NO_CONTENT',
1049 'RESET_CONTENT',
1050 'PARTIAL_CONTENT',
1051 'MULTI_STATUS',
1052 'IM_USED',
1053 'MULTIPLE_CHOICES',
1054 'MOVED_PERMANENTLY',
1055 'FOUND',
1056 'SEE_OTHER',
1057 'NOT_MODIFIED',
1058 'USE_PROXY',
1059 'TEMPORARY_REDIRECT',
1060 'BAD_REQUEST',
1061 'UNAUTHORIZED',
1062 'PAYMENT_REQUIRED',
1063 'FORBIDDEN',
1064 'NOT_FOUND',
1065 'METHOD_NOT_ALLOWED',
1066 'NOT_ACCEPTABLE',
1067 'PROXY_AUTHENTICATION_REQUIRED',
1068 'REQUEST_TIMEOUT',
1069 'CONFLICT',
1070 'GONE',
1071 'LENGTH_REQUIRED',
1072 'PRECONDITION_FAILED',
1073 'REQUEST_ENTITY_TOO_LARGE',
1074 'REQUEST_URI_TOO_LONG',
1075 'UNSUPPORTED_MEDIA_TYPE',
1076 'REQUESTED_RANGE_NOT_SATISFIABLE',
1077 'EXPECTATION_FAILED',
1078 'UNPROCESSABLE_ENTITY',
1079 'LOCKED',
1080 'FAILED_DEPENDENCY',
1081 'UPGRADE_REQUIRED',
1082 'PRECONDITION_REQUIRED',
1083 'TOO_MANY_REQUESTS',
1084 'REQUEST_HEADER_FIELDS_TOO_LARGE',
1085 'INTERNAL_SERVER_ERROR',
1086 'NOT_IMPLEMENTED',
1087 'BAD_GATEWAY',
1088 'SERVICE_UNAVAILABLE',
1089 'GATEWAY_TIMEOUT',
1090 'HTTP_VERSION_NOT_SUPPORTED',
1091 'INSUFFICIENT_STORAGE',
1092 'NOT_EXTENDED',
1093 'NETWORK_AUTHENTICATION_REQUIRED',
1094 ]
1095 for const in expected:
1096 with self.subTest(constant=const):
1097 self.assertTrue(hasattr(client, const))
1098
Gregory P. Smithb4066372010-01-03 03:28:29 +00001099
1100class SourceAddressTest(TestCase):
1101 def setUp(self):
1102 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1103 self.port = support.bind_port(self.serv)
1104 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +01001105 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +00001106 self.conn = None
1107
1108 def tearDown(self):
1109 if self.conn:
1110 self.conn.close()
1111 self.conn = None
1112 self.serv.close()
1113 self.serv = None
1114
1115 def testHTTPConnectionSourceAddress(self):
1116 self.conn = client.HTTPConnection(HOST, self.port,
1117 source_address=('', self.source_port))
1118 self.conn.connect()
1119 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
1120
1121 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1122 'http.client.HTTPSConnection not defined')
1123 def testHTTPSConnectionSourceAddress(self):
1124 self.conn = client.HTTPSConnection(HOST, self.port,
1125 source_address=('', self.source_port))
1126 # We don't test anything here other the constructor not barfing as
1127 # this code doesn't deal with setting up an active running SSL server
1128 # for an ssl_wrapped connect() to actually return from.
1129
1130
Guido van Rossumd8faa362007-04-27 19:54:29 +00001131class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +00001132 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +00001133
1134 def setUp(self):
1135 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001136 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +01001137 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001138
1139 def tearDown(self):
1140 self.serv.close()
1141 self.serv = None
1142
1143 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +00001144 # This will prove that the timeout gets through HTTPConnection
1145 # and into the socket.
1146
Georg Brandlf78e02b2008-06-10 17:40:04 +00001147 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001148 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +00001149 socket.setdefaulttimeout(30)
1150 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001151 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001152 httpConn.connect()
1153 finally:
1154 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001155 self.assertEqual(httpConn.sock.gettimeout(), 30)
1156 httpConn.close()
1157
Georg Brandlf78e02b2008-06-10 17:40:04 +00001158 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +02001159 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +00001160 socket.setdefaulttimeout(30)
1161 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001162 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +00001163 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +00001164 httpConn.connect()
1165 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001166 socket.setdefaulttimeout(None)
1167 self.assertEqual(httpConn.sock.gettimeout(), None)
1168 httpConn.close()
1169
1170 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001171 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001172 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +00001173 self.assertEqual(httpConn.sock.gettimeout(), 30)
1174 httpConn.close()
1175
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001176
1177class HTTPSTest(TestCase):
1178
1179 def setUp(self):
1180 if not hasattr(client, 'HTTPSConnection'):
1181 self.skipTest('ssl support required')
1182
1183 def make_server(self, certfile):
1184 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001185 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001186
1187 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001188 # simple test to check it's storing the timeout
1189 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1190 self.assertEqual(h.timeout, 30)
1191
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001192 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001193 # Default settings: requires a valid cert from a trusted CA
1194 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001195 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001196 with support.transient_internet('self-signed.pythontest.net'):
1197 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
1198 with self.assertRaises(ssl.SSLError) as exc_info:
1199 h.request('GET', '/')
1200 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1201
1202 def test_networked_noverification(self):
1203 # Switch off cert verification
1204 import ssl
1205 support.requires('network')
1206 with support.transient_internet('self-signed.pythontest.net'):
1207 context = ssl._create_unverified_context()
1208 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
1209 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001210 h.request('GET', '/')
1211 resp = h.getresponse()
Victor Stinnerb389b482015-02-27 17:47:23 +01001212 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001213 self.assertIn('nginx', resp.getheader('server'))
1214
Benjamin Peterson2615e9e2014-11-25 15:16:55 -06001215 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001216 def test_networked_trusted_by_default_cert(self):
1217 # Default settings: requires a valid cert from a trusted CA
1218 support.requires('network')
1219 with support.transient_internet('www.python.org'):
1220 h = client.HTTPSConnection('www.python.org', 443)
1221 h.request('GET', '/')
1222 resp = h.getresponse()
1223 content_type = resp.getheader('content-type')
Victor Stinnerb389b482015-02-27 17:47:23 +01001224 h.close()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001225 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001226
1227 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +01001228 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001229 import ssl
1230 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +01001231 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001232 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1233 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +01001234 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
1235 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001236 h.request('GET', '/')
1237 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001238 server_string = resp.getheader('server')
Victor Stinnerb389b482015-02-27 17:47:23 +01001239 h.close()
Georg Brandlfbaf9312014-11-05 20:37:40 +01001240 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001241
1242 def test_networked_bad_cert(self):
1243 # We feed a "CA" cert that is unrelated to the server's cert
1244 import ssl
1245 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001246 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001247 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1248 context.verify_mode = ssl.CERT_REQUIRED
1249 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001250 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
1251 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001252 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -05001253 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
1254
1255 def test_local_unknown_cert(self):
1256 # The custom cert isn't known to the default trust bundle
1257 import ssl
1258 server = self.make_server(CERT_localhost)
1259 h = client.HTTPSConnection('localhost', server.port)
1260 with self.assertRaises(ssl.SSLError) as exc_info:
1261 h.request('GET', '/')
1262 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001263
1264 def test_local_good_hostname(self):
1265 # The (valid) cert validates the HTTP hostname
1266 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001267 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001268 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1269 context.verify_mode = ssl.CERT_REQUIRED
1270 context.load_verify_locations(CERT_localhost)
1271 h = client.HTTPSConnection('localhost', server.port, context=context)
1272 h.request('GET', '/nonexistent')
1273 resp = h.getresponse()
1274 self.assertEqual(resp.status, 404)
1275
1276 def test_local_bad_hostname(self):
1277 # The (valid) cert doesn't validate the HTTP hostname
1278 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001279 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001280 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1281 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -05001282 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001283 context.load_verify_locations(CERT_fakehostname)
1284 h = client.HTTPSConnection('localhost', server.port, context=context)
1285 with self.assertRaises(ssl.CertificateError):
1286 h.request('GET', '/')
1287 # Same with explicit check_hostname=True
1288 h = client.HTTPSConnection('localhost', server.port, context=context,
1289 check_hostname=True)
1290 with self.assertRaises(ssl.CertificateError):
1291 h.request('GET', '/')
1292 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -05001293 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001294 h = client.HTTPSConnection('localhost', server.port, context=context,
1295 check_hostname=False)
1296 h.request('GET', '/nonexistent')
1297 resp = h.getresponse()
1298 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -05001299 # The context's check_hostname setting is used if one isn't passed to
1300 # HTTPSConnection.
1301 context.check_hostname = False
1302 h = client.HTTPSConnection('localhost', server.port, context=context)
1303 h.request('GET', '/nonexistent')
1304 self.assertEqual(h.getresponse().status, 404)
1305 # Passing check_hostname to HTTPSConnection should override the
1306 # context's setting.
1307 h = client.HTTPSConnection('localhost', server.port, context=context,
1308 check_hostname=True)
1309 with self.assertRaises(ssl.CertificateError):
1310 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001311
Petri Lehtinene119c402011-10-26 21:29:15 +03001312 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1313 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001314 def test_host_port(self):
1315 # Check invalid host_port
1316
1317 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1318 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1319
1320 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1321 "fe80::207:e9ff:fe9b", 8000),
1322 ("www.python.org:443", "www.python.org", 443),
1323 ("www.python.org:", "www.python.org", 443),
1324 ("www.python.org", "www.python.org", 443),
1325 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1326 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1327 443)):
1328 c = client.HTTPSConnection(hp)
1329 self.assertEqual(h, c.host)
1330 self.assertEqual(p, c.port)
1331
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001332
Jeremy Hylton236654b2009-03-27 20:24:34 +00001333class RequestBodyTest(TestCase):
1334 """Test cases where a request includes a message body."""
1335
1336 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001337 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001338 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001339 self.conn.sock = self.sock
1340
1341 def get_headers_and_fp(self):
1342 f = io.BytesIO(self.sock.data)
1343 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001344 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001345 return message, f
1346
1347 def test_manual_content_length(self):
1348 # Set an incorrect content-length so that we can verify that
1349 # it will not be over-ridden by the library.
1350 self.conn.request("PUT", "/url", "body",
1351 {"Content-Length": "42"})
1352 message, f = self.get_headers_and_fp()
1353 self.assertEqual("42", message.get("content-length"))
1354 self.assertEqual(4, len(f.read()))
1355
1356 def test_ascii_body(self):
1357 self.conn.request("PUT", "/url", "body")
1358 message, f = self.get_headers_and_fp()
1359 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001360 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001361 self.assertEqual("4", message.get("content-length"))
1362 self.assertEqual(b'body', f.read())
1363
1364 def test_latin1_body(self):
1365 self.conn.request("PUT", "/url", "body\xc1")
1366 message, f = self.get_headers_and_fp()
1367 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001368 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001369 self.assertEqual("5", message.get("content-length"))
1370 self.assertEqual(b'body\xc1', f.read())
1371
1372 def test_bytes_body(self):
1373 self.conn.request("PUT", "/url", b"body\xc1")
1374 message, f = self.get_headers_and_fp()
1375 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001376 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001377 self.assertEqual("5", message.get("content-length"))
1378 self.assertEqual(b'body\xc1', f.read())
1379
1380 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001381 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001382 with open(support.TESTFN, "w") as f:
1383 f.write("body")
1384 with open(support.TESTFN) as f:
1385 self.conn.request("PUT", "/url", f)
1386 message, f = self.get_headers_and_fp()
1387 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001388 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001389 self.assertEqual("4", message.get("content-length"))
1390 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001391
1392 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001393 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001394 with open(support.TESTFN, "wb") as f:
1395 f.write(b"body\xc1")
1396 with open(support.TESTFN, "rb") as f:
1397 self.conn.request("PUT", "/url", f)
1398 message, f = self.get_headers_and_fp()
1399 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001400 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001401 self.assertEqual("5", message.get("content-length"))
1402 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001403
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001404
1405class HTTPResponseTest(TestCase):
1406
1407 def setUp(self):
1408 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1409 second-value\r\n\r\nText"
1410 sock = FakeSocket(body)
1411 self.resp = client.HTTPResponse(sock)
1412 self.resp.begin()
1413
1414 def test_getting_header(self):
1415 header = self.resp.getheader('My-Header')
1416 self.assertEqual(header, 'first-value, second-value')
1417
1418 header = self.resp.getheader('My-Header', 'some default')
1419 self.assertEqual(header, 'first-value, second-value')
1420
1421 def test_getting_nonexistent_header_with_string_default(self):
1422 header = self.resp.getheader('No-Such-Header', 'default-value')
1423 self.assertEqual(header, 'default-value')
1424
1425 def test_getting_nonexistent_header_with_iterable_default(self):
1426 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1427 self.assertEqual(header, 'default, values')
1428
1429 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1430 self.assertEqual(header, 'default, values')
1431
1432 def test_getting_nonexistent_header_without_default(self):
1433 header = self.resp.getheader('No-Such-Header')
1434 self.assertEqual(header, None)
1435
1436 def test_getting_header_defaultint(self):
1437 header = self.resp.getheader('No-Such-Header',default=42)
1438 self.assertEqual(header, 42)
1439
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001440class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001441 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001442 response_text = (
1443 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1444 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1445 'Content-Length: 42\r\n\r\n'
1446 )
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001447 self.host = 'proxy.com'
1448 self.conn = client.HTTPConnection(self.host)
Berker Peksagab53ab02015-02-03 12:22:11 +02001449 self.conn._create_connection = self._create_connection(response_text)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001450
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001451 def tearDown(self):
1452 self.conn.close()
1453
Berker Peksagab53ab02015-02-03 12:22:11 +02001454 def _create_connection(self, response_text):
1455 def create_connection(address, timeout=None, source_address=None):
1456 return FakeSocket(response_text, host=address[0], port=address[1])
1457 return create_connection
1458
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001459 def test_set_tunnel_host_port_headers(self):
1460 tunnel_host = 'destination.com'
1461 tunnel_port = 8888
1462 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1463 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1464 headers=tunnel_headers)
1465 self.conn.request('HEAD', '/', '')
1466 self.assertEqual(self.conn.sock.host, self.host)
1467 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1468 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1469 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1470 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1471
1472 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001473 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001474 self.conn.connect()
1475 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001476 'destination.com')
1477
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001478 def test_connect_with_tunnel(self):
1479 self.conn.set_tunnel('destination.com')
1480 self.conn.request('HEAD', '/', '')
1481 self.assertEqual(self.conn.sock.host, self.host)
1482 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1483 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001484 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001485 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1486 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001487
1488 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001489 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001490
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001491 def test_connect_put_request(self):
1492 self.conn.set_tunnel('destination.com')
1493 self.conn.request('PUT', '/', '')
1494 self.assertEqual(self.conn.sock.host, self.host)
1495 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1496 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1497 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1498
Berker Peksagab53ab02015-02-03 12:22:11 +02001499 def test_tunnel_debuglog(self):
1500 expected_header = 'X-Dummy: 1'
1501 response_text = 'HTTP/1.0 200 OK\r\n{}\r\n\r\n'.format(expected_header)
1502
1503 self.conn.set_debuglevel(1)
1504 self.conn._create_connection = self._create_connection(response_text)
1505 self.conn.set_tunnel('destination.com')
1506
1507 with support.captured_stdout() as output:
1508 self.conn.request('PUT', '/', '')
1509 lines = output.getvalue().splitlines()
1510 self.assertIn('header: {}'.format(expected_header), lines)
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001511
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001512
Benjamin Peterson9566de12014-12-13 16:13:24 -05001513@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001514def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001515 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001516 HTTPSTest, RequestBodyTest, SourceAddressTest,
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001517 HTTPResponseTest, ExtendedReadTest,
Senthil Kumaran166214c2014-04-14 13:10:05 -04001518 ExtendedReadTestChunked, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001519
Thomas Wouters89f507f2006-12-13 04:49:30 +00001520if __name__ == '__main__':
1521 test_main()