blob: 00c272c1f55af6552045b223cc6d2c0c450fbed8 [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
Antoine Pitrou803e6d62010-10-13 10:36:15 +00004import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00005import array
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import socket
Jeremy Hylton121d34a2003-07-08 12:36:58 +00007
Gregory P. Smithb4066372010-01-03 03:28:29 +00008import unittest
9TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000010
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000012
Antoine Pitrou803e6d62010-10-13 10:36:15 +000013here = os.path.dirname(__file__)
14# Self-signed cert file for 'localhost'
15CERT_localhost = os.path.join(here, 'keycert.pem')
16# Self-signed cert file for 'fakehostname'
17CERT_fakehostname = os.path.join(here, 'keycert2.pem')
18# Root cert file (CA) for svn.python.org's cert
19CACERT_svn_python_org = os.path.join(here, 'https_svn_python_org_root.pem')
20
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000021# constants for testing chunked encoding
22chunked_start = (
23 'HTTP/1.1 200 OK\r\n'
24 'Transfer-Encoding: chunked\r\n\r\n'
25 'a\r\n'
26 'hello worl\r\n'
27 '3\r\n'
28 'd! \r\n'
29 '8\r\n'
30 'and now \r\n'
31 '22\r\n'
32 'for something completely different\r\n'
33)
34chunked_expected = b'hello world! and now for something completely different'
35chunk_extension = ";foo=bar"
36last_chunk = "0\r\n"
37last_chunk_extended = "0" + chunk_extension + "\r\n"
38trailers = "X-Dummy: foo\r\nX-Dumm2: bar\r\n"
39chunked_end = "\r\n"
40
Benjamin Petersonee8712c2008-05-20 21:35:26 +000041HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000042
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000043class FakeSocket:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040044 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000045 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000046 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000047 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000048 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000049 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010050 self.sendall_calls = 0
Senthil Kumaran9da047b2014-04-14 13:07:56 -040051 self.host = host
52 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000053
Jeremy Hylton2c178252004-08-07 16:28:14 +000054 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010055 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000056 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000057
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000058 def makefile(self, mode, bufsize=None):
59 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000060 raise client.UnimplementedFileMode()
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +000061 # keep the file around so we can check how much was read from it
62 self.file = self.fileclass(self.text)
63 self.file.close = lambda:None #nerf close ()
64 return self.file
Jeremy Hylton121d34a2003-07-08 12:36:58 +000065
Senthil Kumaran9da047b2014-04-14 13:07:56 -040066 def close(self):
67 pass
68
Jeremy Hylton636950f2009-03-28 04:34:21 +000069class EPipeSocket(FakeSocket):
70
71 def __init__(self, text, pipe_trigger):
72 # When sendall() is called with pipe_trigger, raise EPIPE.
73 FakeSocket.__init__(self, text)
74 self.pipe_trigger = pipe_trigger
75
76 def sendall(self, data):
77 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020078 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000079 self.data += data
80
81 def close(self):
82 pass
83
Serhiy Storchaka50254c52013-08-29 11:35:43 +030084class NoEOFBytesIO(io.BytesIO):
85 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000086
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000087 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000088 more from the underlying file than it should.
89 """
90 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000091 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000092 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000093 raise AssertionError('caller tried to read past EOF')
94 return data
95
96 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000097 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000098 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000099 raise AssertionError('caller tried to read past EOF')
100 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000101
Jeremy Hylton2c178252004-08-07 16:28:14 +0000102class HeaderTests(TestCase):
103 def test_auto_headers(self):
104 # Some headers are added automatically, but should not be added by
105 # .request() if they are explicitly set.
106
Jeremy Hylton2c178252004-08-07 16:28:14 +0000107 class HeaderCountingBuffer(list):
108 def __init__(self):
109 self.count = {}
110 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +0000111 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000112 if len(kv) > 1:
113 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +0000114 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +0000115 self.count.setdefault(lcKey, 0)
116 self.count[lcKey] += 1
117 list.append(self, item)
118
119 for explicit_header in True, False:
120 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000121 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000122 conn.sock = FakeSocket('blahblahblah')
123 conn._buffer = HeaderCountingBuffer()
124
125 body = 'spamspamspam'
126 headers = {}
127 if explicit_header:
128 headers[header] = str(len(body))
129 conn.request('POST', '/', body, headers)
130 self.assertEqual(conn._buffer.count[header.lower()], 1)
131
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800132 def test_content_length_0(self):
133
134 class ContentLengthChecker(list):
135 def __init__(self):
136 list.__init__(self)
137 self.content_length = None
138 def append(self, item):
139 kv = item.split(b':', 1)
140 if len(kv) > 1 and kv[0].lower() == b'content-length':
141 self.content_length = kv[1].strip()
142 list.append(self, item)
143
144 # POST with empty body
145 conn = client.HTTPConnection('example.com')
146 conn.sock = FakeSocket(None)
147 conn._buffer = ContentLengthChecker()
148 conn.request('POST', '/', '')
149 self.assertEqual(conn._buffer.content_length, b'0',
150 'Header Content-Length not set')
151
152 # PUT request with empty body
153 conn = client.HTTPConnection('example.com')
154 conn.sock = FakeSocket(None)
155 conn._buffer = ContentLengthChecker()
156 conn.request('PUT', '/', '')
157 self.assertEqual(conn._buffer.content_length, b'0',
158 'Header Content-Length not set')
159
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000160 def test_putheader(self):
161 conn = client.HTTPConnection('example.com')
162 conn.sock = FakeSocket(None)
163 conn.putrequest('GET','/')
164 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200165 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000166
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000167 def test_ipv6host_header(self):
168 # Default host header on IPv6 transaction should wrapped by [] if
169 # its actual IPv6 address
170 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
171 b'Accept-Encoding: identity\r\n\r\n'
172 conn = client.HTTPConnection('[2001::]:81')
173 sock = FakeSocket('')
174 conn.sock = sock
175 conn.request('GET', '/foo')
176 self.assertTrue(sock.data.startswith(expected))
177
178 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
179 b'Accept-Encoding: identity\r\n\r\n'
180 conn = client.HTTPConnection('[2001:102A::]')
181 sock = FakeSocket('')
182 conn.sock = sock
183 conn.request('GET', '/foo')
184 self.assertTrue(sock.data.startswith(expected))
185
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000186
Thomas Wouters89f507f2006-12-13 04:49:30 +0000187class BasicTest(TestCase):
188 def test_status_lines(self):
189 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000190
Thomas Wouters89f507f2006-12-13 04:49:30 +0000191 body = "HTTP/1.1 200 Ok\r\n\r\nText"
192 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000193 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000194 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200195 self.assertEqual(resp.read(0), b'') # Issue #20007
196 self.assertFalse(resp.isclosed())
197 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000198 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000199 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200200 self.assertFalse(resp.closed)
201 resp.close()
202 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000203
Thomas Wouters89f507f2006-12-13 04:49:30 +0000204 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
205 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000206 resp = client.HTTPResponse(sock)
207 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000208
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000209 def test_bad_status_repr(self):
210 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000211 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000212
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000213 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100214 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000215 # same behaviour than when we read the whole thing with read()
216 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
217 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000218 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000219 resp.begin()
220 self.assertEqual(resp.read(2), b'Te')
221 self.assertFalse(resp.isclosed())
222 self.assertEqual(resp.read(2), b'xt')
223 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200224 self.assertFalse(resp.closed)
225 resp.close()
226 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000227
Antoine Pitrou38d96432011-12-06 22:33:57 +0100228 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100229 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100230 # same behaviour than when we read the whole thing with read()
231 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
232 sock = FakeSocket(body)
233 resp = client.HTTPResponse(sock)
234 resp.begin()
235 b = bytearray(2)
236 n = resp.readinto(b)
237 self.assertEqual(n, 2)
238 self.assertEqual(bytes(b), b'Te')
239 self.assertFalse(resp.isclosed())
240 n = resp.readinto(b)
241 self.assertEqual(n, 2)
242 self.assertEqual(bytes(b), b'xt')
243 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200244 self.assertFalse(resp.closed)
245 resp.close()
246 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100247
Antoine Pitrou084daa22012-12-15 19:11:54 +0100248 def test_partial_reads_no_content_length(self):
249 # when no length is present, the socket should be gracefully closed when
250 # all data was read
251 body = "HTTP/1.1 200 Ok\r\n\r\nText"
252 sock = FakeSocket(body)
253 resp = client.HTTPResponse(sock)
254 resp.begin()
255 self.assertEqual(resp.read(2), b'Te')
256 self.assertFalse(resp.isclosed())
257 self.assertEqual(resp.read(2), b'xt')
258 self.assertEqual(resp.read(1), b'')
259 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200260 self.assertFalse(resp.closed)
261 resp.close()
262 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100263
Antoine Pitroud20e7742012-12-15 19:22:30 +0100264 def test_partial_readintos_no_content_length(self):
265 # when no length is present, the socket should be gracefully closed when
266 # all data was read
267 body = "HTTP/1.1 200 Ok\r\n\r\nText"
268 sock = FakeSocket(body)
269 resp = client.HTTPResponse(sock)
270 resp.begin()
271 b = bytearray(2)
272 n = resp.readinto(b)
273 self.assertEqual(n, 2)
274 self.assertEqual(bytes(b), b'Te')
275 self.assertFalse(resp.isclosed())
276 n = resp.readinto(b)
277 self.assertEqual(n, 2)
278 self.assertEqual(bytes(b), b'xt')
279 n = resp.readinto(b)
280 self.assertEqual(n, 0)
281 self.assertTrue(resp.isclosed())
282
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100283 def test_partial_reads_incomplete_body(self):
284 # if the server shuts down the connection before the whole
285 # content-length is delivered, the socket is gracefully closed
286 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
287 sock = FakeSocket(body)
288 resp = client.HTTPResponse(sock)
289 resp.begin()
290 self.assertEqual(resp.read(2), b'Te')
291 self.assertFalse(resp.isclosed())
292 self.assertEqual(resp.read(2), b'xt')
293 self.assertEqual(resp.read(1), b'')
294 self.assertTrue(resp.isclosed())
295
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100296 def test_partial_readintos_incomplete_body(self):
297 # if the server shuts down the connection before the whole
298 # content-length is delivered, the socket is gracefully closed
299 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
300 sock = FakeSocket(body)
301 resp = client.HTTPResponse(sock)
302 resp.begin()
303 b = bytearray(2)
304 n = resp.readinto(b)
305 self.assertEqual(n, 2)
306 self.assertEqual(bytes(b), b'Te')
307 self.assertFalse(resp.isclosed())
308 n = resp.readinto(b)
309 self.assertEqual(n, 2)
310 self.assertEqual(bytes(b), b'xt')
311 n = resp.readinto(b)
312 self.assertEqual(n, 0)
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)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100317
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 def test_host_port(self):
319 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000320
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200321 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000322 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000324 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
325 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200327 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000328 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200329 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
330 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000331 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000332 self.assertEqual(h, c.host)
333 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000334
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 def test_response_headers(self):
336 # test response with multiple message headers with the same field name.
337 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000338 'Set-Cookie: Customer="WILE_E_COYOTE"; '
339 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000340 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
341 ' Path="/acme"\r\n'
342 '\r\n'
343 'No body\r\n')
344 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
345 ', '
346 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
347 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000348 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000349 r.begin()
350 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000351 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000352
Thomas Wouters89f507f2006-12-13 04:49:30 +0000353 def test_read_head(self):
354 # Test that the library doesn't attempt to read any data
355 # from a HEAD request. (Tickles SF bug #622042.)
356 sock = FakeSocket(
357 'HTTP/1.1 200 OK\r\n'
358 'Content-Length: 14432\r\n'
359 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300360 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000361 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000363 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000364 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000365
Antoine Pitrou38d96432011-12-06 22:33:57 +0100366 def test_readinto_head(self):
367 # Test that the library doesn't attempt to read any data
368 # from a HEAD request. (Tickles SF bug #622042.)
369 sock = FakeSocket(
370 'HTTP/1.1 200 OK\r\n'
371 'Content-Length: 14432\r\n'
372 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300373 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100374 resp = client.HTTPResponse(sock, method="HEAD")
375 resp.begin()
376 b = bytearray(5)
377 if resp.readinto(b) != 0:
378 self.fail("Did not expect response from HEAD request")
379 self.assertEqual(bytes(b), b'\x00'*5)
380
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100381 def test_too_many_headers(self):
382 headers = '\r\n'.join('Header%d: foo' % i
383 for i in range(client._MAXHEADERS + 1)) + '\r\n'
384 text = ('HTTP/1.1 200 OK\r\n' + headers)
385 s = FakeSocket(text)
386 r = client.HTTPResponse(s)
387 self.assertRaisesRegex(client.HTTPException,
388 r"got more than \d+ headers", r.begin)
389
Thomas Wouters89f507f2006-12-13 04:49:30 +0000390 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000391 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
392 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000393
Brett Cannon77b7de62010-10-29 23:31:11 +0000394 with open(__file__, 'rb') as body:
395 conn = client.HTTPConnection('example.com')
396 sock = FakeSocket(body)
397 conn.sock = sock
398 conn.request('GET', '/foo', body)
399 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
400 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000401
Antoine Pitrouead1d622009-09-29 18:44:53 +0000402 def test_send(self):
403 expected = b'this is a test this is only a test'
404 conn = client.HTTPConnection('example.com')
405 sock = FakeSocket(None)
406 conn.sock = sock
407 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000408 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000409 sock.data = b''
410 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000411 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000412 sock.data = b''
413 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000414 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000415
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300416 def test_send_updating_file(self):
417 def data():
418 yield 'data'
419 yield None
420 yield 'data_two'
421
422 class UpdatingFile():
423 mode = 'r'
424 d = data()
425 def read(self, blocksize=-1):
426 return self.d.__next__()
427
428 expected = b'data'
429
430 conn = client.HTTPConnection('example.com')
431 sock = FakeSocket("")
432 conn.sock = sock
433 conn.send(UpdatingFile())
434 self.assertEqual(sock.data, expected)
435
436
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000437 def test_send_iter(self):
438 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
439 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
440 b'\r\nonetwothree'
441
442 def body():
443 yield b"one"
444 yield b"two"
445 yield b"three"
446
447 conn = client.HTTPConnection('example.com')
448 sock = FakeSocket("")
449 conn.sock = sock
450 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000451 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000452
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800453 def test_send_type_error(self):
454 # See: Issue #12676
455 conn = client.HTTPConnection('example.com')
456 conn.sock = FakeSocket('')
457 with self.assertRaises(TypeError):
458 conn.request('POST', 'test', conn)
459
Christian Heimesa612dc02008-02-24 13:08:18 +0000460 def test_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000461 expected = chunked_expected
462 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000463 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000464 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100465 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000466 resp.close()
467
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100468 # Various read sizes
469 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000470 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100471 resp = client.HTTPResponse(sock, method="GET")
472 resp.begin()
473 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
474 resp.close()
475
Christian Heimesa612dc02008-02-24 13:08:18 +0000476 for x in ('', 'foo\r\n'):
477 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000478 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000479 resp.begin()
480 try:
481 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000482 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100483 self.assertEqual(i.partial, expected)
484 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
485 self.assertEqual(repr(i), expected_message)
486 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000487 else:
488 self.fail('IncompleteRead expected')
489 finally:
490 resp.close()
491
Antoine Pitrou38d96432011-12-06 22:33:57 +0100492 def test_readinto_chunked(self):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000493
494 expected = chunked_expected
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100495 nexpected = len(expected)
496 b = bytearray(128)
497
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000498 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100499 resp = client.HTTPResponse(sock, method="GET")
500 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100501 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100502 self.assertEqual(b[:nexpected], expected)
503 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100504 resp.close()
505
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100506 # Various read sizes
507 for n in range(1, 12):
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000508 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100509 resp = client.HTTPResponse(sock, method="GET")
510 resp.begin()
511 m = memoryview(b)
512 i = resp.readinto(m[0:n])
513 i += resp.readinto(m[i:n + i])
514 i += resp.readinto(m[i:])
515 self.assertEqual(b[:nexpected], expected)
516 self.assertEqual(i, nexpected)
517 resp.close()
518
Antoine Pitrou38d96432011-12-06 22:33:57 +0100519 for x in ('', 'foo\r\n'):
520 sock = FakeSocket(chunked_start + x)
521 resp = client.HTTPResponse(sock, method="GET")
522 resp.begin()
523 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100524 n = resp.readinto(b)
525 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100526 self.assertEqual(i.partial, expected)
527 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
528 self.assertEqual(repr(i), expected_message)
529 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100530 else:
531 self.fail('IncompleteRead expected')
532 finally:
533 resp.close()
534
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000535 def test_chunked_head(self):
536 chunked_start = (
537 'HTTP/1.1 200 OK\r\n'
538 'Transfer-Encoding: chunked\r\n\r\n'
539 'a\r\n'
540 'hello world\r\n'
541 '1\r\n'
542 'd\r\n'
543 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000544 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000545 resp = client.HTTPResponse(sock, method="HEAD")
546 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000547 self.assertEqual(resp.read(), b'')
548 self.assertEqual(resp.status, 200)
549 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000550 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200551 self.assertFalse(resp.closed)
552 resp.close()
553 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000554
Antoine Pitrou38d96432011-12-06 22:33:57 +0100555 def test_readinto_chunked_head(self):
556 chunked_start = (
557 'HTTP/1.1 200 OK\r\n'
558 'Transfer-Encoding: chunked\r\n\r\n'
559 'a\r\n'
560 'hello world\r\n'
561 '1\r\n'
562 'd\r\n'
563 )
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000564 sock = FakeSocket(chunked_start + last_chunk + chunked_end)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100565 resp = client.HTTPResponse(sock, method="HEAD")
566 resp.begin()
567 b = bytearray(5)
568 n = resp.readinto(b)
569 self.assertEqual(n, 0)
570 self.assertEqual(bytes(b), b'\x00'*5)
571 self.assertEqual(resp.status, 200)
572 self.assertEqual(resp.reason, 'OK')
573 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200574 self.assertFalse(resp.closed)
575 resp.close()
576 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100577
Christian Heimesa612dc02008-02-24 13:08:18 +0000578 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000579 sock = FakeSocket(
580 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000581 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000582 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000583 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100584 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000585
Benjamin Peterson6accb982009-03-02 22:50:25 +0000586 def test_incomplete_read(self):
587 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000588 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000589 resp.begin()
590 try:
591 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000592 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000593 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000594 self.assertEqual(repr(i),
595 "IncompleteRead(7 bytes read, 3 more expected)")
596 self.assertEqual(str(i),
597 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100598 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000599 else:
600 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000601
Jeremy Hylton636950f2009-03-28 04:34:21 +0000602 def test_epipe(self):
603 sock = EPipeSocket(
604 "HTTP/1.0 401 Authorization Required\r\n"
605 "Content-type: text/html\r\n"
606 "WWW-Authenticate: Basic realm=\"example\"\r\n",
607 b"Content-Length")
608 conn = client.HTTPConnection("example.com")
609 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200610 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000611 lambda: conn.request("PUT", "/url", "body"))
612 resp = conn.getresponse()
613 self.assertEqual(401, resp.status)
614 self.assertEqual("Basic realm=\"example\"",
615 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000616
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000617 # Test lines overflowing the max line size (_MAXLINE in http.client)
618
619 def test_overflowing_status_line(self):
620 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
621 resp = client.HTTPResponse(FakeSocket(body))
622 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
623
624 def test_overflowing_header_line(self):
625 body = (
626 'HTTP/1.1 200 OK\r\n'
627 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
628 )
629 resp = client.HTTPResponse(FakeSocket(body))
630 self.assertRaises(client.LineTooLong, resp.begin)
631
632 def test_overflowing_chunked_line(self):
633 body = (
634 'HTTP/1.1 200 OK\r\n'
635 'Transfer-Encoding: chunked\r\n\r\n'
636 + '0' * 65536 + 'a\r\n'
637 'hello world\r\n'
638 '0\r\n'
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000639 '\r\n'
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000640 )
641 resp = client.HTTPResponse(FakeSocket(body))
642 resp.begin()
643 self.assertRaises(client.LineTooLong, resp.read)
644
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800645 def test_early_eof(self):
646 # Test httpresponse with no \r\n termination,
647 body = "HTTP/1.1 200 Ok"
648 sock = FakeSocket(body)
649 resp = client.HTTPResponse(sock)
650 resp.begin()
651 self.assertEqual(resp.read(), b'')
652 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200653 self.assertFalse(resp.closed)
654 resp.close()
655 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800656
Antoine Pitrou90e47742013-01-02 22:10:47 +0100657 def test_delayed_ack_opt(self):
658 # Test that Nagle/delayed_ack optimistaion works correctly.
659
660 # For small payloads, it should coalesce the body with
661 # headers, resulting in a single sendall() call
662 conn = client.HTTPConnection('example.com')
663 sock = FakeSocket(None)
664 conn.sock = sock
665 body = b'x' * (conn.mss - 1)
666 conn.request('POST', '/', body)
667 self.assertEqual(sock.sendall_calls, 1)
668
669 # For large payloads, it should send the headers and
670 # then the body, resulting in more than one sendall()
671 # call
672 conn = client.HTTPConnection('example.com')
673 sock = FakeSocket(None)
674 conn.sock = sock
675 body = b'x' * conn.mss
676 conn.request('POST', '/', body)
677 self.assertGreater(sock.sendall_calls, 1)
678
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +0000679 def test_chunked_extension(self):
680 extra = '3;foo=bar\r\n' + 'abc\r\n'
681 expected = chunked_expected + b'abc'
682
683 sock = FakeSocket(chunked_start + extra + last_chunk_extended + chunked_end)
684 resp = client.HTTPResponse(sock, method="GET")
685 resp.begin()
686 self.assertEqual(resp.read(), expected)
687 resp.close()
688
689 def test_chunked_missing_end(self):
690 """some servers may serve up a short chunked encoding stream"""
691 expected = chunked_expected
692 sock = FakeSocket(chunked_start + last_chunk) #no terminating crlf
693 resp = client.HTTPResponse(sock, method="GET")
694 resp.begin()
695 self.assertEqual(resp.read(), expected)
696 resp.close()
697
698 def test_chunked_trailers(self):
699 """See that trailers are read and ignored"""
700 expected = chunked_expected
701 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end)
702 resp = client.HTTPResponse(sock, method="GET")
703 resp.begin()
704 self.assertEqual(resp.read(), expected)
705 # we should have reached the end of the file
706 self.assertEqual(sock.file.read(100), b"") #we read to the end
707 resp.close()
708
709 def test_chunked_sync(self):
710 """Check that we don't read past the end of the chunked-encoding stream"""
711 expected = chunked_expected
712 extradata = "extradata"
713 sock = FakeSocket(chunked_start + last_chunk + trailers + chunked_end + extradata)
714 resp = client.HTTPResponse(sock, method="GET")
715 resp.begin()
716 self.assertEqual(resp.read(), expected)
717 # the file should now have our extradata ready to be read
718 self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end
719 resp.close()
720
721 def test_content_length_sync(self):
722 """Check that we don't read past the end of the Content-Length stream"""
723 extradata = "extradata"
724 expected = b"Hello123\r\n"
725 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello123\r\n' + extradata)
726 resp = client.HTTPResponse(sock, method="GET")
727 resp.begin()
728 self.assertEqual(resp.read(), expected)
729 # the file should now have our extradata ready to be read
730 self.assertEqual(sock.file.read(100), extradata.encode("ascii")) #we read to the end
731 resp.close()
732
733class ExtendedReadTest(TestCase):
734 """
735 Test peek(), read1(), readline()
736 """
737 lines = (
738 'HTTP/1.1 200 OK\r\n'
739 '\r\n'
740 'hello world!\n'
741 'and now \n'
742 'for something completely different\n'
743 'foo'
744 )
745 lines_expected = lines[lines.find('hello'):].encode("ascii")
746 lines_chunked = (
747 'HTTP/1.1 200 OK\r\n'
748 'Transfer-Encoding: chunked\r\n\r\n'
749 'a\r\n'
750 'hello worl\r\n'
751 '3\r\n'
752 'd!\n\r\n'
753 '9\r\n'
754 'and now \n\r\n'
755 '23\r\n'
756 'for something completely different\n\r\n'
757 '3\r\n'
758 'foo\r\n'
759 '0\r\n' # terminating chunk
760 '\r\n' # end of trailers
761 )
762
763 def setUp(self):
764 sock = FakeSocket(self.lines)
765 resp = client.HTTPResponse(sock, method="GET")
766 resp.begin()
767 resp.fp = io.BufferedReader(resp.fp)
768 self.resp = resp
769
770
771
772 def test_peek(self):
773 resp = self.resp
774 # patch up the buffered peek so that it returns not too much stuff
775 oldpeek = resp.fp.peek
776 def mypeek(n=-1):
777 p = oldpeek(n)
778 if n >= 0:
779 return p[:n]
780 return p[:10]
781 resp.fp.peek = mypeek
782
783 all = []
784 while True:
785 # try a short peek
786 p = resp.peek(3)
787 if p:
788 self.assertGreater(len(p), 0)
789 # then unbounded peek
790 p2 = resp.peek()
791 self.assertGreaterEqual(len(p2), len(p))
792 self.assertTrue(p2.startswith(p))
793 next = resp.read(len(p2))
794 self.assertEqual(next, p2)
795 else:
796 next = resp.read()
797 self.assertFalse(next)
798 all.append(next)
799 if not next:
800 break
801 self.assertEqual(b"".join(all), self.lines_expected)
802
803 def test_readline(self):
804 resp = self.resp
805 self._verify_readline(self.resp.readline, self.lines_expected)
806
807 def _verify_readline(self, readline, expected):
808 all = []
809 while True:
810 # short readlines
811 line = readline(5)
812 if line and line != b"foo":
813 if len(line) < 5:
814 self.assertTrue(line.endswith(b"\n"))
815 all.append(line)
816 if not line:
817 break
818 self.assertEqual(b"".join(all), expected)
819
820 def test_read1(self):
821 resp = self.resp
822 def r():
823 res = resp.read1(4)
824 self.assertLessEqual(len(res), 4)
825 return res
826 readliner = Readliner(r)
827 self._verify_readline(readliner.readline, self.lines_expected)
828
829 def test_read1_unbounded(self):
830 resp = self.resp
831 all = []
832 while True:
833 data = resp.read1()
834 if not data:
835 break
836 all.append(data)
837 self.assertEqual(b"".join(all), self.lines_expected)
838
839 def test_read1_bounded(self):
840 resp = self.resp
841 all = []
842 while True:
843 data = resp.read1(10)
844 if not data:
845 break
846 self.assertLessEqual(len(data), 10)
847 all.append(data)
848 self.assertEqual(b"".join(all), self.lines_expected)
849
850 def test_read1_0(self):
851 self.assertEqual(self.resp.read1(0), b"")
852
853 def test_peek_0(self):
854 p = self.resp.peek(0)
855 self.assertLessEqual(0, len(p))
856
857class ExtendedReadTestChunked(ExtendedReadTest):
858 """
859 Test peek(), read1(), readline() in chunked mode
860 """
861 lines = (
862 'HTTP/1.1 200 OK\r\n'
863 'Transfer-Encoding: chunked\r\n\r\n'
864 'a\r\n'
865 'hello worl\r\n'
866 '3\r\n'
867 'd!\n\r\n'
868 '9\r\n'
869 'and now \n\r\n'
870 '23\r\n'
871 'for something completely different\n\r\n'
872 '3\r\n'
873 'foo\r\n'
874 '0\r\n' # terminating chunk
875 '\r\n' # end of trailers
876 )
877
878
879class Readliner:
880 """
881 a simple readline class that uses an arbitrary read function and buffering
882 """
883 def __init__(self, readfunc):
884 self.readfunc = readfunc
885 self.remainder = b""
886
887 def readline(self, limit):
888 data = []
889 datalen = 0
890 read = self.remainder
891 try:
892 while True:
893 idx = read.find(b'\n')
894 if idx != -1:
895 break
896 if datalen + len(read) >= limit:
897 idx = limit - datalen - 1
898 # read more data
899 data.append(read)
900 read = self.readfunc()
901 if not read:
902 idx = 0 #eof condition
903 break
904 idx += 1
905 data.append(read[:idx])
906 self.remainder = read[idx:]
907 return b"".join(data)
908 except:
909 self.remainder = b"".join(data)
910 raise
911
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000912class OfflineTest(TestCase):
913 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000914 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000915
Gregory P. Smithb4066372010-01-03 03:28:29 +0000916
917class SourceAddressTest(TestCase):
918 def setUp(self):
919 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
920 self.port = support.bind_port(self.serv)
921 self.source_port = support.find_unused_port()
Charles-François Natali6e204602014-07-23 19:28:13 +0100922 self.serv.listen()
Gregory P. Smithb4066372010-01-03 03:28:29 +0000923 self.conn = None
924
925 def tearDown(self):
926 if self.conn:
927 self.conn.close()
928 self.conn = None
929 self.serv.close()
930 self.serv = None
931
932 def testHTTPConnectionSourceAddress(self):
933 self.conn = client.HTTPConnection(HOST, self.port,
934 source_address=('', self.source_port))
935 self.conn.connect()
936 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
937
938 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
939 'http.client.HTTPSConnection not defined')
940 def testHTTPSConnectionSourceAddress(self):
941 self.conn = client.HTTPSConnection(HOST, self.port,
942 source_address=('', self.source_port))
943 # We don't test anything here other the constructor not barfing as
944 # this code doesn't deal with setting up an active running SSL server
945 # for an ssl_wrapped connect() to actually return from.
946
947
Guido van Rossumd8faa362007-04-27 19:54:29 +0000948class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000949 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000950
951 def setUp(self):
952 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000953 TimeoutTest.PORT = support.bind_port(self.serv)
Charles-François Natali6e204602014-07-23 19:28:13 +0100954 self.serv.listen()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000955
956 def tearDown(self):
957 self.serv.close()
958 self.serv = None
959
960 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000961 # This will prove that the timeout gets through HTTPConnection
962 # and into the socket.
963
Georg Brandlf78e02b2008-06-10 17:40:04 +0000964 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200965 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000966 socket.setdefaulttimeout(30)
967 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000968 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000969 httpConn.connect()
970 finally:
971 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000972 self.assertEqual(httpConn.sock.gettimeout(), 30)
973 httpConn.close()
974
Georg Brandlf78e02b2008-06-10 17:40:04 +0000975 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200976 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000977 socket.setdefaulttimeout(30)
978 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000979 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000980 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000981 httpConn.connect()
982 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000983 socket.setdefaulttimeout(None)
984 self.assertEqual(httpConn.sock.gettimeout(), None)
985 httpConn.close()
986
987 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000988 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000989 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000990 self.assertEqual(httpConn.sock.gettimeout(), 30)
991 httpConn.close()
992
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000993
994class HTTPSTest(TestCase):
995
996 def setUp(self):
997 if not hasattr(client, 'HTTPSConnection'):
998 self.skipTest('ssl support required')
999
1000 def make_server(self, certfile):
1001 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +01001002 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001003
1004 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001005 # simple test to check it's storing the timeout
1006 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
1007 self.assertEqual(h.timeout, 30)
1008
1009 def _check_svn_python_org(self, resp):
1010 # Just a simple check that everything went fine
1011 server_string = resp.getheader('server')
1012 self.assertIn('Apache', server_string)
1013
1014 def test_networked(self):
1015 # Default settings: no cert verification is done
1016 support.requires('network')
1017 with support.transient_internet('svn.python.org'):
1018 h = client.HTTPSConnection('svn.python.org', 443)
1019 h.request('GET', '/')
1020 resp = h.getresponse()
1021 self._check_svn_python_org(resp)
1022
1023 def test_networked_good_cert(self):
1024 # We feed a CA cert that validates the server's cert
1025 import ssl
1026 support.requires('network')
1027 with support.transient_internet('svn.python.org'):
1028 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1029 context.verify_mode = ssl.CERT_REQUIRED
1030 context.load_verify_locations(CACERT_svn_python_org)
1031 h = client.HTTPSConnection('svn.python.org', 443, context=context)
1032 h.request('GET', '/')
1033 resp = h.getresponse()
1034 self._check_svn_python_org(resp)
1035
1036 def test_networked_bad_cert(self):
1037 # We feed a "CA" cert that is unrelated to the server's cert
1038 import ssl
1039 support.requires('network')
1040 with support.transient_internet('svn.python.org'):
1041 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1042 context.verify_mode = ssl.CERT_REQUIRED
1043 context.load_verify_locations(CERT_localhost)
1044 h = client.HTTPSConnection('svn.python.org', 443, context=context)
1045 with self.assertRaises(ssl.SSLError):
1046 h.request('GET', '/')
1047
1048 def test_local_good_hostname(self):
1049 # The (valid) cert validates the HTTP hostname
1050 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001051 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001052 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1053 context.verify_mode = ssl.CERT_REQUIRED
1054 context.load_verify_locations(CERT_localhost)
1055 h = client.HTTPSConnection('localhost', server.port, context=context)
1056 h.request('GET', '/nonexistent')
1057 resp = h.getresponse()
1058 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -07001059 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001060
1061 def test_local_bad_hostname(self):
1062 # The (valid) cert doesn't validate the HTTP hostname
1063 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -07001064 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001065 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
1066 context.verify_mode = ssl.CERT_REQUIRED
1067 context.load_verify_locations(CERT_fakehostname)
1068 h = client.HTTPSConnection('localhost', server.port, context=context)
1069 with self.assertRaises(ssl.CertificateError):
1070 h.request('GET', '/')
1071 # Same with explicit check_hostname=True
1072 h = client.HTTPSConnection('localhost', server.port, context=context,
1073 check_hostname=True)
1074 with self.assertRaises(ssl.CertificateError):
1075 h.request('GET', '/')
1076 # With check_hostname=False, the mismatching is ignored
1077 h = client.HTTPSConnection('localhost', server.port, context=context,
1078 check_hostname=False)
1079 h.request('GET', '/nonexistent')
1080 resp = h.getresponse()
1081 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -07001082 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001083
Petri Lehtinene119c402011-10-26 21:29:15 +03001084 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
1085 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +02001086 def test_host_port(self):
1087 # Check invalid host_port
1088
1089 for hp in ("www.python.org:abc", "user:password@www.python.org"):
1090 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
1091
1092 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
1093 "fe80::207:e9ff:fe9b", 8000),
1094 ("www.python.org:443", "www.python.org", 443),
1095 ("www.python.org:", "www.python.org", 443),
1096 ("www.python.org", "www.python.org", 443),
1097 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
1098 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
1099 443)):
1100 c = client.HTTPSConnection(hp)
1101 self.assertEqual(h, c.host)
1102 self.assertEqual(p, c.port)
1103
Guido van Rossumd59da4b2007-05-22 18:11:13 +00001104
Jeremy Hylton236654b2009-03-27 20:24:34 +00001105class RequestBodyTest(TestCase):
1106 """Test cases where a request includes a message body."""
1107
1108 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001109 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +00001110 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +00001111 self.conn.sock = self.sock
1112
1113 def get_headers_and_fp(self):
1114 f = io.BytesIO(self.sock.data)
1115 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00001116 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +00001117 return message, f
1118
1119 def test_manual_content_length(self):
1120 # Set an incorrect content-length so that we can verify that
1121 # it will not be over-ridden by the library.
1122 self.conn.request("PUT", "/url", "body",
1123 {"Content-Length": "42"})
1124 message, f = self.get_headers_and_fp()
1125 self.assertEqual("42", message.get("content-length"))
1126 self.assertEqual(4, len(f.read()))
1127
1128 def test_ascii_body(self):
1129 self.conn.request("PUT", "/url", "body")
1130 message, f = self.get_headers_and_fp()
1131 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001132 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001133 self.assertEqual("4", message.get("content-length"))
1134 self.assertEqual(b'body', f.read())
1135
1136 def test_latin1_body(self):
1137 self.conn.request("PUT", "/url", "body\xc1")
1138 message, f = self.get_headers_and_fp()
1139 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001140 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001141 self.assertEqual("5", message.get("content-length"))
1142 self.assertEqual(b'body\xc1', f.read())
1143
1144 def test_bytes_body(self):
1145 self.conn.request("PUT", "/url", b"body\xc1")
1146 message, f = self.get_headers_and_fp()
1147 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001148 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001149 self.assertEqual("5", message.get("content-length"))
1150 self.assertEqual(b'body\xc1', f.read())
1151
1152 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001153 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001154 with open(support.TESTFN, "w") as f:
1155 f.write("body")
1156 with open(support.TESTFN) as f:
1157 self.conn.request("PUT", "/url", f)
1158 message, f = self.get_headers_and_fp()
1159 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001160 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001161 self.assertEqual("4", message.get("content-length"))
1162 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001163
1164 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001165 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001166 with open(support.TESTFN, "wb") as f:
1167 f.write(b"body\xc1")
1168 with open(support.TESTFN, "rb") as f:
1169 self.conn.request("PUT", "/url", f)
1170 message, f = self.get_headers_and_fp()
1171 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001172 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001173 self.assertEqual("5", message.get("content-length"))
1174 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001175
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001176
1177class HTTPResponseTest(TestCase):
1178
1179 def setUp(self):
1180 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1181 second-value\r\n\r\nText"
1182 sock = FakeSocket(body)
1183 self.resp = client.HTTPResponse(sock)
1184 self.resp.begin()
1185
1186 def test_getting_header(self):
1187 header = self.resp.getheader('My-Header')
1188 self.assertEqual(header, 'first-value, second-value')
1189
1190 header = self.resp.getheader('My-Header', 'some default')
1191 self.assertEqual(header, 'first-value, second-value')
1192
1193 def test_getting_nonexistent_header_with_string_default(self):
1194 header = self.resp.getheader('No-Such-Header', 'default-value')
1195 self.assertEqual(header, 'default-value')
1196
1197 def test_getting_nonexistent_header_with_iterable_default(self):
1198 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1199 self.assertEqual(header, 'default, values')
1200
1201 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1202 self.assertEqual(header, 'default, values')
1203
1204 def test_getting_nonexistent_header_without_default(self):
1205 header = self.resp.getheader('No-Such-Header')
1206 self.assertEqual(header, None)
1207
1208 def test_getting_header_defaultint(self):
1209 header = self.resp.getheader('No-Such-Header',default=42)
1210 self.assertEqual(header, 42)
1211
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001212class TunnelTests(TestCase):
1213
1214 def test_connect(self):
1215 response_text = (
1216 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1217 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1218 'Content-Length: 42\r\n\r\n'
1219 )
1220
1221 def create_connection(address, timeout=None, source_address=None):
1222 return FakeSocket(response_text, host=address[0],
1223 port=address[1])
1224
1225 conn = client.HTTPConnection('proxy.com')
1226 conn._create_connection = create_connection
1227
1228 # Once connected, we shouldn't be able to tunnel anymore
1229 conn.connect()
1230 self.assertRaises(RuntimeError, conn.set_tunnel,
1231 'destination.com')
1232
1233 # But if we close the connection, we're good
1234 conn.close()
1235 conn.set_tunnel('destination.com')
1236 conn.request('HEAD', '/', '')
1237
1238 self.assertEqual(conn.sock.host, 'proxy.com')
1239 self.assertEqual(conn.sock.port, 80)
1240 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1241 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1242
1243 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
1244 self.assertTrue(b'Host: proxy.com' not in conn.sock.data)
1245
1246 conn.close()
1247 conn.request('PUT', '/', '')
1248 self.assertEqual(conn.sock.host, 'proxy.com')
1249 self.assertEqual(conn.sock.port, 80)
1250 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1251 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1252
Jeremy Hylton2c178252004-08-07 16:28:14 +00001253def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001254 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001255 HTTPSTest, RequestBodyTest, SourceAddressTest,
Kristján Valur Jónsson8e5d0ca2014-03-19 10:07:26 +00001256 HTTPResponseTest, ExtendedReadTest,
Senthil Kumaran166214c2014-04-14 13:10:05 -04001257 ExtendedReadTestChunked, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001258
Thomas Wouters89f507f2006-12-13 04:49:30 +00001259if __name__ == '__main__':
1260 test_main()