blob: 425c7160510c010ec10015c3989c2bda75eadff9 [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
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000022
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000023class FakeSocket:
Jeremy Hylton8fff7922007-08-03 20:56:14 +000024 def __init__(self, text, fileclass=io.BytesIO):
25 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000026 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000027 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000028 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000029 self.data = b''
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000030
Jeremy Hylton2c178252004-08-07 16:28:14 +000031 def sendall(self, data):
Thomas Wouters89f507f2006-12-13 04:49:30 +000032 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000033
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000034 def makefile(self, mode, bufsize=None):
35 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000036 raise client.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000037 return self.fileclass(self.text)
38
Jeremy Hylton636950f2009-03-28 04:34:21 +000039class EPipeSocket(FakeSocket):
40
41 def __init__(self, text, pipe_trigger):
42 # When sendall() is called with pipe_trigger, raise EPIPE.
43 FakeSocket.__init__(self, text)
44 self.pipe_trigger = pipe_trigger
45
46 def sendall(self, data):
47 if self.pipe_trigger in data:
48 raise socket.error(errno.EPIPE, "gotcha")
49 self.data += data
50
51 def close(self):
52 pass
53
Jeremy Hylton8fff7922007-08-03 20:56:14 +000054class NoEOFStringIO(io.BytesIO):
Jeremy Hylton121d34a2003-07-08 12:36:58 +000055 """Like StringIO, but raises AssertionError on EOF.
56
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000057 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000058 more from the underlying file than it should.
59 """
60 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000061 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000062 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000063 raise AssertionError('caller tried to read past EOF')
64 return data
65
66 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000067 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000068 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000069 raise AssertionError('caller tried to read past EOF')
70 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000071
Jeremy Hylton2c178252004-08-07 16:28:14 +000072class HeaderTests(TestCase):
73 def test_auto_headers(self):
74 # Some headers are added automatically, but should not be added by
75 # .request() if they are explicitly set.
76
Jeremy Hylton2c178252004-08-07 16:28:14 +000077 class HeaderCountingBuffer(list):
78 def __init__(self):
79 self.count = {}
80 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000081 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000082 if len(kv) > 1:
83 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000084 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000085 self.count.setdefault(lcKey, 0)
86 self.count[lcKey] += 1
87 list.append(self, item)
88
89 for explicit_header in True, False:
90 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000091 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +000092 conn.sock = FakeSocket('blahblahblah')
93 conn._buffer = HeaderCountingBuffer()
94
95 body = 'spamspamspam'
96 headers = {}
97 if explicit_header:
98 headers[header] = str(len(body))
99 conn.request('POST', '/', body, headers)
100 self.assertEqual(conn._buffer.count[header.lower()], 1)
101
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000102 def test_putheader(self):
103 conn = client.HTTPConnection('example.com')
104 conn.sock = FakeSocket(None)
105 conn.putrequest('GET','/')
106 conn.putheader('Content-length', 42)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000107 self.assertTrue(b'Content-length: 42' in conn._buffer)
108
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000109 def test_ipv6host_header(self):
110 # Default host header on IPv6 transaction should wrapped by [] if
111 # its actual IPv6 address
112 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
113 b'Accept-Encoding: identity\r\n\r\n'
114 conn = client.HTTPConnection('[2001::]:81')
115 sock = FakeSocket('')
116 conn.sock = sock
117 conn.request('GET', '/foo')
118 self.assertTrue(sock.data.startswith(expected))
119
120 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
121 b'Accept-Encoding: identity\r\n\r\n'
122 conn = client.HTTPConnection('[2001:102A::]')
123 sock = FakeSocket('')
124 conn.sock = sock
125 conn.request('GET', '/foo')
126 self.assertTrue(sock.data.startswith(expected))
127
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000128
Thomas Wouters89f507f2006-12-13 04:49:30 +0000129class BasicTest(TestCase):
130 def test_status_lines(self):
131 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000132
Thomas Wouters89f507f2006-12-13 04:49:30 +0000133 body = "HTTP/1.1 200 Ok\r\n\r\nText"
134 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000135 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000136 resp.begin()
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000137 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000138 self.assertTrue(resp.isclosed())
Jeremy Hyltonba603192003-01-23 18:02:20 +0000139
Thomas Wouters89f507f2006-12-13 04:49:30 +0000140 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
141 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000142 resp = client.HTTPResponse(sock)
143 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000144
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000145 def test_bad_status_repr(self):
146 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000147 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000148
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000149 def test_partial_reads(self):
150 # if we have a lenght, the system knows when to close itself
151 # same behaviour than when we read the whole thing with read()
152 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
153 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000154 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000155 resp.begin()
156 self.assertEqual(resp.read(2), b'Te')
157 self.assertFalse(resp.isclosed())
158 self.assertEqual(resp.read(2), b'xt')
159 self.assertTrue(resp.isclosed())
160
Antoine Pitrou38d96432011-12-06 22:33:57 +0100161 def test_partial_readintos(self):
162 # if we have a lenght, the system knows when to close itself
163 # same behaviour than when we read the whole thing with read()
164 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
165 sock = FakeSocket(body)
166 resp = client.HTTPResponse(sock)
167 resp.begin()
168 b = bytearray(2)
169 n = resp.readinto(b)
170 self.assertEqual(n, 2)
171 self.assertEqual(bytes(b), b'Te')
172 self.assertFalse(resp.isclosed())
173 n = resp.readinto(b)
174 self.assertEqual(n, 2)
175 self.assertEqual(bytes(b), b'xt')
176 self.assertTrue(resp.isclosed())
177
Thomas Wouters89f507f2006-12-13 04:49:30 +0000178 def test_host_port(self):
179 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000180
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200181 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000182 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000183
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000184 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
185 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000186 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200187 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200189 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
190 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000191 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000192 self.assertEqual(h, c.host)
193 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000194
Thomas Wouters89f507f2006-12-13 04:49:30 +0000195 def test_response_headers(self):
196 # test response with multiple message headers with the same field name.
197 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000198 'Set-Cookie: Customer="WILE_E_COYOTE"; '
199 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000200 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
201 ' Path="/acme"\r\n'
202 '\r\n'
203 'No body\r\n')
204 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
205 ', '
206 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
207 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000208 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000209 r.begin()
210 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000211 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000212
Thomas Wouters89f507f2006-12-13 04:49:30 +0000213 def test_read_head(self):
214 # Test that the library doesn't attempt to read any data
215 # from a HEAD request. (Tickles SF bug #622042.)
216 sock = FakeSocket(
217 'HTTP/1.1 200 OK\r\n'
218 'Content-Length: 14432\r\n'
219 '\r\n',
220 NoEOFStringIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000221 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000222 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000223 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000224 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000225
Antoine Pitrou38d96432011-12-06 22:33:57 +0100226 def test_readinto_head(self):
227 # Test that the library doesn't attempt to read any data
228 # from a HEAD request. (Tickles SF bug #622042.)
229 sock = FakeSocket(
230 'HTTP/1.1 200 OK\r\n'
231 'Content-Length: 14432\r\n'
232 '\r\n',
233 NoEOFStringIO)
234 resp = client.HTTPResponse(sock, method="HEAD")
235 resp.begin()
236 b = bytearray(5)
237 if resp.readinto(b) != 0:
238 self.fail("Did not expect response from HEAD request")
239 self.assertEqual(bytes(b), b'\x00'*5)
240
Thomas Wouters89f507f2006-12-13 04:49:30 +0000241 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000242 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
243 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000244
Brett Cannon77b7de62010-10-29 23:31:11 +0000245 with open(__file__, 'rb') as body:
246 conn = client.HTTPConnection('example.com')
247 sock = FakeSocket(body)
248 conn.sock = sock
249 conn.request('GET', '/foo', body)
250 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
251 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000252
Antoine Pitrouead1d622009-09-29 18:44:53 +0000253 def test_send(self):
254 expected = b'this is a test this is only a test'
255 conn = client.HTTPConnection('example.com')
256 sock = FakeSocket(None)
257 conn.sock = sock
258 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000259 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000260 sock.data = b''
261 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000262 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000263 sock.data = b''
264 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000265 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000266
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000267 def test_send_iter(self):
268 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
269 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
270 b'\r\nonetwothree'
271
272 def body():
273 yield b"one"
274 yield b"two"
275 yield b"three"
276
277 conn = client.HTTPConnection('example.com')
278 sock = FakeSocket("")
279 conn.sock = sock
280 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000281 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000282
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800283 def test_send_type_error(self):
284 # See: Issue #12676
285 conn = client.HTTPConnection('example.com')
286 conn.sock = FakeSocket('')
287 with self.assertRaises(TypeError):
288 conn.request('POST', 'test', conn)
289
Christian Heimesa612dc02008-02-24 13:08:18 +0000290 def test_chunked(self):
291 chunked_start = (
292 'HTTP/1.1 200 OK\r\n'
293 'Transfer-Encoding: chunked\r\n\r\n'
294 'a\r\n'
295 'hello worl\r\n'
296 '1\r\n'
297 'd\r\n'
298 )
299 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000300 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000301 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000302 self.assertEqual(resp.read(), b'hello world')
Christian Heimesa612dc02008-02-24 13:08:18 +0000303 resp.close()
304
305 for x in ('', 'foo\r\n'):
306 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000307 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000308 resp.begin()
309 try:
310 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000311 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000312 self.assertEqual(i.partial, b'hello world')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000313 self.assertEqual(repr(i),'IncompleteRead(11 bytes read)')
314 self.assertEqual(str(i),'IncompleteRead(11 bytes read)')
Christian Heimesa612dc02008-02-24 13:08:18 +0000315 else:
316 self.fail('IncompleteRead expected')
317 finally:
318 resp.close()
319
Antoine Pitrou38d96432011-12-06 22:33:57 +0100320 def test_readinto_chunked(self):
321 chunked_start = (
322 'HTTP/1.1 200 OK\r\n'
323 'Transfer-Encoding: chunked\r\n\r\n'
324 'a\r\n'
325 'hello worl\r\n'
326 '1\r\n'
327 'd\r\n'
328 )
329 sock = FakeSocket(chunked_start + '0\r\n')
330 resp = client.HTTPResponse(sock, method="GET")
331 resp.begin()
332 b = bytearray(16)
333 n = resp.readinto(b)
334 self.assertEqual(b[:11], b'hello world')
335 self.assertEqual(n, 11)
336 resp.close()
337
338 for x in ('', 'foo\r\n'):
339 sock = FakeSocket(chunked_start + x)
340 resp = client.HTTPResponse(sock, method="GET")
341 resp.begin()
342 try:
343 b = bytearray(16)
344 n = resp.readinto(b)
345 except client.IncompleteRead as i:
346 self.assertEqual(i.partial, b'hello world')
347 self.assertEqual(repr(i),'IncompleteRead(11 bytes read)')
348 self.assertEqual(str(i),'IncompleteRead(11 bytes read)')
349 else:
350 self.fail('IncompleteRead expected')
351 finally:
352 resp.close()
353
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000354 def test_chunked_head(self):
355 chunked_start = (
356 'HTTP/1.1 200 OK\r\n'
357 'Transfer-Encoding: chunked\r\n\r\n'
358 'a\r\n'
359 'hello world\r\n'
360 '1\r\n'
361 'd\r\n'
362 )
363 sock = FakeSocket(chunked_start + '0\r\n')
364 resp = client.HTTPResponse(sock, method="HEAD")
365 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000366 self.assertEqual(resp.read(), b'')
367 self.assertEqual(resp.status, 200)
368 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000369 self.assertTrue(resp.isclosed())
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000370
Antoine Pitrou38d96432011-12-06 22:33:57 +0100371 def test_readinto_chunked_head(self):
372 chunked_start = (
373 'HTTP/1.1 200 OK\r\n'
374 'Transfer-Encoding: chunked\r\n\r\n'
375 'a\r\n'
376 'hello world\r\n'
377 '1\r\n'
378 'd\r\n'
379 )
380 sock = FakeSocket(chunked_start + '0\r\n')
381 resp = client.HTTPResponse(sock, method="HEAD")
382 resp.begin()
383 b = bytearray(5)
384 n = resp.readinto(b)
385 self.assertEqual(n, 0)
386 self.assertEqual(bytes(b), b'\x00'*5)
387 self.assertEqual(resp.status, 200)
388 self.assertEqual(resp.reason, 'OK')
389 self.assertTrue(resp.isclosed())
390
Christian Heimesa612dc02008-02-24 13:08:18 +0000391 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000392 sock = FakeSocket(
393 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000394 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000395 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000396 self.assertEqual(resp.read(), b'Hello\r\n')
Christian Heimesa612dc02008-02-24 13:08:18 +0000397 resp.close()
398
Benjamin Peterson6accb982009-03-02 22:50:25 +0000399 def test_incomplete_read(self):
400 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000401 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000402 resp.begin()
403 try:
404 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000405 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000406 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000407 self.assertEqual(repr(i),
408 "IncompleteRead(7 bytes read, 3 more expected)")
409 self.assertEqual(str(i),
410 "IncompleteRead(7 bytes read, 3 more expected)")
411 else:
412 self.fail('IncompleteRead expected')
413 finally:
414 resp.close()
415
Jeremy Hylton636950f2009-03-28 04:34:21 +0000416 def test_epipe(self):
417 sock = EPipeSocket(
418 "HTTP/1.0 401 Authorization Required\r\n"
419 "Content-type: text/html\r\n"
420 "WWW-Authenticate: Basic realm=\"example\"\r\n",
421 b"Content-Length")
422 conn = client.HTTPConnection("example.com")
423 conn.sock = sock
424 self.assertRaises(socket.error,
425 lambda: conn.request("PUT", "/url", "body"))
426 resp = conn.getresponse()
427 self.assertEqual(401, resp.status)
428 self.assertEqual("Basic realm=\"example\"",
429 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000430
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000431 # Test lines overflowing the max line size (_MAXLINE in http.client)
432
433 def test_overflowing_status_line(self):
434 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
435 resp = client.HTTPResponse(FakeSocket(body))
436 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
437
438 def test_overflowing_header_line(self):
439 body = (
440 'HTTP/1.1 200 OK\r\n'
441 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
442 )
443 resp = client.HTTPResponse(FakeSocket(body))
444 self.assertRaises(client.LineTooLong, resp.begin)
445
446 def test_overflowing_chunked_line(self):
447 body = (
448 'HTTP/1.1 200 OK\r\n'
449 'Transfer-Encoding: chunked\r\n\r\n'
450 + '0' * 65536 + 'a\r\n'
451 'hello world\r\n'
452 '0\r\n'
453 )
454 resp = client.HTTPResponse(FakeSocket(body))
455 resp.begin()
456 self.assertRaises(client.LineTooLong, resp.read)
457
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000458class OfflineTest(TestCase):
459 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000460 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000461
Gregory P. Smithb4066372010-01-03 03:28:29 +0000462
463class SourceAddressTest(TestCase):
464 def setUp(self):
465 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
466 self.port = support.bind_port(self.serv)
467 self.source_port = support.find_unused_port()
468 self.serv.listen(5)
469 self.conn = None
470
471 def tearDown(self):
472 if self.conn:
473 self.conn.close()
474 self.conn = None
475 self.serv.close()
476 self.serv = None
477
478 def testHTTPConnectionSourceAddress(self):
479 self.conn = client.HTTPConnection(HOST, self.port,
480 source_address=('', self.source_port))
481 self.conn.connect()
482 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
483
484 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
485 'http.client.HTTPSConnection not defined')
486 def testHTTPSConnectionSourceAddress(self):
487 self.conn = client.HTTPSConnection(HOST, self.port,
488 source_address=('', self.source_port))
489 # We don't test anything here other the constructor not barfing as
490 # this code doesn't deal with setting up an active running SSL server
491 # for an ssl_wrapped connect() to actually return from.
492
493
Guido van Rossumd8faa362007-04-27 19:54:29 +0000494class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000495 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000496
497 def setUp(self):
498 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000499 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000500 self.serv.listen(5)
501
502 def tearDown(self):
503 self.serv.close()
504 self.serv = None
505
506 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000507 # This will prove that the timeout gets through HTTPConnection
508 # and into the socket.
509
Georg Brandlf78e02b2008-06-10 17:40:04 +0000510 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000511 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000512 socket.setdefaulttimeout(30)
513 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000514 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000515 httpConn.connect()
516 finally:
517 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000518 self.assertEqual(httpConn.sock.gettimeout(), 30)
519 httpConn.close()
520
Georg Brandlf78e02b2008-06-10 17:40:04 +0000521 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000522 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000523 socket.setdefaulttimeout(30)
524 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000525 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000526 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000527 httpConn.connect()
528 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000529 socket.setdefaulttimeout(None)
530 self.assertEqual(httpConn.sock.gettimeout(), None)
531 httpConn.close()
532
533 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000534 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000535 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000536 self.assertEqual(httpConn.sock.gettimeout(), 30)
537 httpConn.close()
538
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000539
540class HTTPSTest(TestCase):
541
542 def setUp(self):
543 if not hasattr(client, 'HTTPSConnection'):
544 self.skipTest('ssl support required')
545
546 def make_server(self, certfile):
547 from test.ssl_servers import make_https_server
548 return make_https_server(self, certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000549
550 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000551 # simple test to check it's storing the timeout
552 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
553 self.assertEqual(h.timeout, 30)
554
555 def _check_svn_python_org(self, resp):
556 # Just a simple check that everything went fine
557 server_string = resp.getheader('server')
558 self.assertIn('Apache', server_string)
559
560 def test_networked(self):
561 # Default settings: no cert verification is done
562 support.requires('network')
563 with support.transient_internet('svn.python.org'):
564 h = client.HTTPSConnection('svn.python.org', 443)
565 h.request('GET', '/')
566 resp = h.getresponse()
567 self._check_svn_python_org(resp)
568
569 def test_networked_good_cert(self):
570 # We feed a CA cert that validates the server's cert
571 import ssl
572 support.requires('network')
573 with support.transient_internet('svn.python.org'):
574 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
575 context.verify_mode = ssl.CERT_REQUIRED
576 context.load_verify_locations(CACERT_svn_python_org)
577 h = client.HTTPSConnection('svn.python.org', 443, context=context)
578 h.request('GET', '/')
579 resp = h.getresponse()
580 self._check_svn_python_org(resp)
581
582 def test_networked_bad_cert(self):
583 # We feed a "CA" cert that is unrelated to the server's cert
584 import ssl
585 support.requires('network')
586 with support.transient_internet('svn.python.org'):
587 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
588 context.verify_mode = ssl.CERT_REQUIRED
589 context.load_verify_locations(CERT_localhost)
590 h = client.HTTPSConnection('svn.python.org', 443, context=context)
591 with self.assertRaises(ssl.SSLError):
592 h.request('GET', '/')
593
594 def test_local_good_hostname(self):
595 # The (valid) cert validates the HTTP hostname
596 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700597 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000598 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
599 context.verify_mode = ssl.CERT_REQUIRED
600 context.load_verify_locations(CERT_localhost)
601 h = client.HTTPSConnection('localhost', server.port, context=context)
602 h.request('GET', '/nonexistent')
603 resp = h.getresponse()
604 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700605 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000606
607 def test_local_bad_hostname(self):
608 # The (valid) cert doesn't validate the HTTP hostname
609 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700610 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000611 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
612 context.verify_mode = ssl.CERT_REQUIRED
613 context.load_verify_locations(CERT_fakehostname)
614 h = client.HTTPSConnection('localhost', server.port, context=context)
615 with self.assertRaises(ssl.CertificateError):
616 h.request('GET', '/')
617 # Same with explicit check_hostname=True
618 h = client.HTTPSConnection('localhost', server.port, context=context,
619 check_hostname=True)
620 with self.assertRaises(ssl.CertificateError):
621 h.request('GET', '/')
622 # With check_hostname=False, the mismatching is ignored
623 h = client.HTTPSConnection('localhost', server.port, context=context,
624 check_hostname=False)
625 h.request('GET', '/nonexistent')
626 resp = h.getresponse()
627 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700628 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000629
Petri Lehtinene119c402011-10-26 21:29:15 +0300630 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
631 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200632 def test_host_port(self):
633 # Check invalid host_port
634
635 for hp in ("www.python.org:abc", "user:password@www.python.org"):
636 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
637
638 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
639 "fe80::207:e9ff:fe9b", 8000),
640 ("www.python.org:443", "www.python.org", 443),
641 ("www.python.org:", "www.python.org", 443),
642 ("www.python.org", "www.python.org", 443),
643 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
644 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
645 443)):
646 c = client.HTTPSConnection(hp)
647 self.assertEqual(h, c.host)
648 self.assertEqual(p, c.port)
649
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000650
Jeremy Hylton236654b2009-03-27 20:24:34 +0000651class RequestBodyTest(TestCase):
652 """Test cases where a request includes a message body."""
653
654 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000655 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000656 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000657 self.conn.sock = self.sock
658
659 def get_headers_and_fp(self):
660 f = io.BytesIO(self.sock.data)
661 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000662 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000663 return message, f
664
665 def test_manual_content_length(self):
666 # Set an incorrect content-length so that we can verify that
667 # it will not be over-ridden by the library.
668 self.conn.request("PUT", "/url", "body",
669 {"Content-Length": "42"})
670 message, f = self.get_headers_and_fp()
671 self.assertEqual("42", message.get("content-length"))
672 self.assertEqual(4, len(f.read()))
673
674 def test_ascii_body(self):
675 self.conn.request("PUT", "/url", "body")
676 message, f = self.get_headers_and_fp()
677 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000678 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000679 self.assertEqual("4", message.get("content-length"))
680 self.assertEqual(b'body', f.read())
681
682 def test_latin1_body(self):
683 self.conn.request("PUT", "/url", "body\xc1")
684 message, f = self.get_headers_and_fp()
685 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000686 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000687 self.assertEqual("5", message.get("content-length"))
688 self.assertEqual(b'body\xc1', f.read())
689
690 def test_bytes_body(self):
691 self.conn.request("PUT", "/url", b"body\xc1")
692 message, f = self.get_headers_and_fp()
693 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000694 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000695 self.assertEqual("5", message.get("content-length"))
696 self.assertEqual(b'body\xc1', f.read())
697
698 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200699 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000700 with open(support.TESTFN, "w") as f:
701 f.write("body")
702 with open(support.TESTFN) as f:
703 self.conn.request("PUT", "/url", f)
704 message, f = self.get_headers_and_fp()
705 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000706 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000707 self.assertEqual("4", message.get("content-length"))
708 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000709
710 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200711 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000712 with open(support.TESTFN, "wb") as f:
713 f.write(b"body\xc1")
714 with open(support.TESTFN, "rb") as f:
715 self.conn.request("PUT", "/url", f)
716 message, f = self.get_headers_and_fp()
717 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000718 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000719 self.assertEqual("5", message.get("content-length"))
720 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000721
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000722
723class HTTPResponseTest(TestCase):
724
725 def setUp(self):
726 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
727 second-value\r\n\r\nText"
728 sock = FakeSocket(body)
729 self.resp = client.HTTPResponse(sock)
730 self.resp.begin()
731
732 def test_getting_header(self):
733 header = self.resp.getheader('My-Header')
734 self.assertEqual(header, 'first-value, second-value')
735
736 header = self.resp.getheader('My-Header', 'some default')
737 self.assertEqual(header, 'first-value, second-value')
738
739 def test_getting_nonexistent_header_with_string_default(self):
740 header = self.resp.getheader('No-Such-Header', 'default-value')
741 self.assertEqual(header, 'default-value')
742
743 def test_getting_nonexistent_header_with_iterable_default(self):
744 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
745 self.assertEqual(header, 'default, values')
746
747 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
748 self.assertEqual(header, 'default, values')
749
750 def test_getting_nonexistent_header_without_default(self):
751 header = self.resp.getheader('No-Such-Header')
752 self.assertEqual(header, None)
753
754 def test_getting_header_defaultint(self):
755 header = self.resp.getheader('No-Such-Header',default=42)
756 self.assertEqual(header, 42)
757
Jeremy Hylton2c178252004-08-07 16:28:14 +0000758def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000759 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000760 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000761 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000762
Thomas Wouters89f507f2006-12-13 04:49:30 +0000763if __name__ == '__main__':
764 test_main()