blob: 2a0b3e39da5b1f02349e886e0205d5aa205eeda2 [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'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100296 '3\r\n'
297 'd! \r\n'
298 '8\r\n'
299 'and now \r\n'
300 '22\r\n'
301 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000302 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100303 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000304 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000305 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000306 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100307 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000308 resp.close()
309
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100310 # Various read sizes
311 for n in range(1, 12):
312 sock = FakeSocket(chunked_start + '0\r\n')
313 resp = client.HTTPResponse(sock, method="GET")
314 resp.begin()
315 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
316 resp.close()
317
Christian Heimesa612dc02008-02-24 13:08:18 +0000318 for x in ('', 'foo\r\n'):
319 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000320 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000321 resp.begin()
322 try:
323 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000324 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100325 self.assertEqual(i.partial, expected)
326 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
327 self.assertEqual(repr(i), expected_message)
328 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000329 else:
330 self.fail('IncompleteRead expected')
331 finally:
332 resp.close()
333
Antoine Pitrou38d96432011-12-06 22:33:57 +0100334 def test_readinto_chunked(self):
335 chunked_start = (
336 'HTTP/1.1 200 OK\r\n'
337 'Transfer-Encoding: chunked\r\n\r\n'
338 'a\r\n'
339 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100340 '3\r\n'
341 'd! \r\n'
342 '8\r\n'
343 'and now \r\n'
344 '22\r\n'
345 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100346 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100347 expected = b'hello world! and now for something completely different'
348 nexpected = len(expected)
349 b = bytearray(128)
350
Antoine Pitrou38d96432011-12-06 22:33:57 +0100351 sock = FakeSocket(chunked_start + '0\r\n')
352 resp = client.HTTPResponse(sock, method="GET")
353 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100354 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100355 self.assertEqual(b[:nexpected], expected)
356 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100357 resp.close()
358
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100359 # Various read sizes
360 for n in range(1, 12):
361 sock = FakeSocket(chunked_start + '0\r\n')
362 resp = client.HTTPResponse(sock, method="GET")
363 resp.begin()
364 m = memoryview(b)
365 i = resp.readinto(m[0:n])
366 i += resp.readinto(m[i:n + i])
367 i += resp.readinto(m[i:])
368 self.assertEqual(b[:nexpected], expected)
369 self.assertEqual(i, nexpected)
370 resp.close()
371
Antoine Pitrou38d96432011-12-06 22:33:57 +0100372 for x in ('', 'foo\r\n'):
373 sock = FakeSocket(chunked_start + x)
374 resp = client.HTTPResponse(sock, method="GET")
375 resp.begin()
376 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100377 n = resp.readinto(b)
378 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100379 self.assertEqual(i.partial, expected)
380 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
381 self.assertEqual(repr(i), expected_message)
382 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100383 else:
384 self.fail('IncompleteRead expected')
385 finally:
386 resp.close()
387
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000388 def test_chunked_head(self):
389 chunked_start = (
390 'HTTP/1.1 200 OK\r\n'
391 'Transfer-Encoding: chunked\r\n\r\n'
392 'a\r\n'
393 'hello world\r\n'
394 '1\r\n'
395 'd\r\n'
396 )
397 sock = FakeSocket(chunked_start + '0\r\n')
398 resp = client.HTTPResponse(sock, method="HEAD")
399 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000400 self.assertEqual(resp.read(), b'')
401 self.assertEqual(resp.status, 200)
402 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000403 self.assertTrue(resp.isclosed())
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000404
Antoine Pitrou38d96432011-12-06 22:33:57 +0100405 def test_readinto_chunked_head(self):
406 chunked_start = (
407 'HTTP/1.1 200 OK\r\n'
408 'Transfer-Encoding: chunked\r\n\r\n'
409 'a\r\n'
410 'hello world\r\n'
411 '1\r\n'
412 'd\r\n'
413 )
414 sock = FakeSocket(chunked_start + '0\r\n')
415 resp = client.HTTPResponse(sock, method="HEAD")
416 resp.begin()
417 b = bytearray(5)
418 n = resp.readinto(b)
419 self.assertEqual(n, 0)
420 self.assertEqual(bytes(b), b'\x00'*5)
421 self.assertEqual(resp.status, 200)
422 self.assertEqual(resp.reason, 'OK')
423 self.assertTrue(resp.isclosed())
424
Christian Heimesa612dc02008-02-24 13:08:18 +0000425 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000426 sock = FakeSocket(
427 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000428 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000429 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000430 self.assertEqual(resp.read(), b'Hello\r\n')
Christian Heimesa612dc02008-02-24 13:08:18 +0000431 resp.close()
432
Benjamin Peterson6accb982009-03-02 22:50:25 +0000433 def test_incomplete_read(self):
434 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000435 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000436 resp.begin()
437 try:
438 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000439 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000440 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000441 self.assertEqual(repr(i),
442 "IncompleteRead(7 bytes read, 3 more expected)")
443 self.assertEqual(str(i),
444 "IncompleteRead(7 bytes read, 3 more expected)")
445 else:
446 self.fail('IncompleteRead expected')
447 finally:
448 resp.close()
449
Jeremy Hylton636950f2009-03-28 04:34:21 +0000450 def test_epipe(self):
451 sock = EPipeSocket(
452 "HTTP/1.0 401 Authorization Required\r\n"
453 "Content-type: text/html\r\n"
454 "WWW-Authenticate: Basic realm=\"example\"\r\n",
455 b"Content-Length")
456 conn = client.HTTPConnection("example.com")
457 conn.sock = sock
458 self.assertRaises(socket.error,
459 lambda: conn.request("PUT", "/url", "body"))
460 resp = conn.getresponse()
461 self.assertEqual(401, resp.status)
462 self.assertEqual("Basic realm=\"example\"",
463 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000464
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000465 # Test lines overflowing the max line size (_MAXLINE in http.client)
466
467 def test_overflowing_status_line(self):
468 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
469 resp = client.HTTPResponse(FakeSocket(body))
470 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
471
472 def test_overflowing_header_line(self):
473 body = (
474 'HTTP/1.1 200 OK\r\n'
475 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
476 )
477 resp = client.HTTPResponse(FakeSocket(body))
478 self.assertRaises(client.LineTooLong, resp.begin)
479
480 def test_overflowing_chunked_line(self):
481 body = (
482 'HTTP/1.1 200 OK\r\n'
483 'Transfer-Encoding: chunked\r\n\r\n'
484 + '0' * 65536 + 'a\r\n'
485 'hello world\r\n'
486 '0\r\n'
487 )
488 resp = client.HTTPResponse(FakeSocket(body))
489 resp.begin()
490 self.assertRaises(client.LineTooLong, resp.read)
491
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000492class OfflineTest(TestCase):
493 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000494 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000495
Gregory P. Smithb4066372010-01-03 03:28:29 +0000496
497class SourceAddressTest(TestCase):
498 def setUp(self):
499 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
500 self.port = support.bind_port(self.serv)
501 self.source_port = support.find_unused_port()
502 self.serv.listen(5)
503 self.conn = None
504
505 def tearDown(self):
506 if self.conn:
507 self.conn.close()
508 self.conn = None
509 self.serv.close()
510 self.serv = None
511
512 def testHTTPConnectionSourceAddress(self):
513 self.conn = client.HTTPConnection(HOST, self.port,
514 source_address=('', self.source_port))
515 self.conn.connect()
516 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
517
518 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
519 'http.client.HTTPSConnection not defined')
520 def testHTTPSConnectionSourceAddress(self):
521 self.conn = client.HTTPSConnection(HOST, self.port,
522 source_address=('', self.source_port))
523 # We don't test anything here other the constructor not barfing as
524 # this code doesn't deal with setting up an active running SSL server
525 # for an ssl_wrapped connect() to actually return from.
526
527
Guido van Rossumd8faa362007-04-27 19:54:29 +0000528class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000529 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000530
531 def setUp(self):
532 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000533 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000534 self.serv.listen(5)
535
536 def tearDown(self):
537 self.serv.close()
538 self.serv = None
539
540 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000541 # This will prove that the timeout gets through HTTPConnection
542 # and into the socket.
543
Georg Brandlf78e02b2008-06-10 17:40:04 +0000544 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000545 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000546 socket.setdefaulttimeout(30)
547 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000548 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000549 httpConn.connect()
550 finally:
551 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000552 self.assertEqual(httpConn.sock.gettimeout(), 30)
553 httpConn.close()
554
Georg Brandlf78e02b2008-06-10 17:40:04 +0000555 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000556 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000557 socket.setdefaulttimeout(30)
558 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000559 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000560 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000561 httpConn.connect()
562 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000563 socket.setdefaulttimeout(None)
564 self.assertEqual(httpConn.sock.gettimeout(), None)
565 httpConn.close()
566
567 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000568 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000569 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000570 self.assertEqual(httpConn.sock.gettimeout(), 30)
571 httpConn.close()
572
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000573
574class HTTPSTest(TestCase):
575
576 def setUp(self):
577 if not hasattr(client, 'HTTPSConnection'):
578 self.skipTest('ssl support required')
579
580 def make_server(self, certfile):
581 from test.ssl_servers import make_https_server
582 return make_https_server(self, certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000583
584 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000585 # simple test to check it's storing the timeout
586 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
587 self.assertEqual(h.timeout, 30)
588
589 def _check_svn_python_org(self, resp):
590 # Just a simple check that everything went fine
591 server_string = resp.getheader('server')
592 self.assertIn('Apache', server_string)
593
594 def test_networked(self):
595 # Default settings: no cert verification is done
596 support.requires('network')
597 with support.transient_internet('svn.python.org'):
598 h = client.HTTPSConnection('svn.python.org', 443)
599 h.request('GET', '/')
600 resp = h.getresponse()
601 self._check_svn_python_org(resp)
602
603 def test_networked_good_cert(self):
604 # We feed a CA cert that validates the server's cert
605 import ssl
606 support.requires('network')
607 with support.transient_internet('svn.python.org'):
608 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
609 context.verify_mode = ssl.CERT_REQUIRED
610 context.load_verify_locations(CACERT_svn_python_org)
611 h = client.HTTPSConnection('svn.python.org', 443, context=context)
612 h.request('GET', '/')
613 resp = h.getresponse()
614 self._check_svn_python_org(resp)
615
616 def test_networked_bad_cert(self):
617 # We feed a "CA" cert that is unrelated to the server's cert
618 import ssl
619 support.requires('network')
620 with support.transient_internet('svn.python.org'):
621 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
622 context.verify_mode = ssl.CERT_REQUIRED
623 context.load_verify_locations(CERT_localhost)
624 h = client.HTTPSConnection('svn.python.org', 443, context=context)
625 with self.assertRaises(ssl.SSLError):
626 h.request('GET', '/')
627
628 def test_local_good_hostname(self):
629 # The (valid) cert validates the HTTP hostname
630 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700631 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000632 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
633 context.verify_mode = ssl.CERT_REQUIRED
634 context.load_verify_locations(CERT_localhost)
635 h = client.HTTPSConnection('localhost', server.port, context=context)
636 h.request('GET', '/nonexistent')
637 resp = h.getresponse()
638 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700639 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000640
641 def test_local_bad_hostname(self):
642 # The (valid) cert doesn't validate the HTTP hostname
643 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700644 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000645 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
646 context.verify_mode = ssl.CERT_REQUIRED
647 context.load_verify_locations(CERT_fakehostname)
648 h = client.HTTPSConnection('localhost', server.port, context=context)
649 with self.assertRaises(ssl.CertificateError):
650 h.request('GET', '/')
651 # Same with explicit check_hostname=True
652 h = client.HTTPSConnection('localhost', server.port, context=context,
653 check_hostname=True)
654 with self.assertRaises(ssl.CertificateError):
655 h.request('GET', '/')
656 # With check_hostname=False, the mismatching is ignored
657 h = client.HTTPSConnection('localhost', server.port, context=context,
658 check_hostname=False)
659 h.request('GET', '/nonexistent')
660 resp = h.getresponse()
661 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700662 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000663
Petri Lehtinene119c402011-10-26 21:29:15 +0300664 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
665 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200666 def test_host_port(self):
667 # Check invalid host_port
668
669 for hp in ("www.python.org:abc", "user:password@www.python.org"):
670 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
671
672 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
673 "fe80::207:e9ff:fe9b", 8000),
674 ("www.python.org:443", "www.python.org", 443),
675 ("www.python.org:", "www.python.org", 443),
676 ("www.python.org", "www.python.org", 443),
677 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
678 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
679 443)):
680 c = client.HTTPSConnection(hp)
681 self.assertEqual(h, c.host)
682 self.assertEqual(p, c.port)
683
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000684
Jeremy Hylton236654b2009-03-27 20:24:34 +0000685class RequestBodyTest(TestCase):
686 """Test cases where a request includes a message body."""
687
688 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000689 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000690 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000691 self.conn.sock = self.sock
692
693 def get_headers_and_fp(self):
694 f = io.BytesIO(self.sock.data)
695 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000696 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000697 return message, f
698
699 def test_manual_content_length(self):
700 # Set an incorrect content-length so that we can verify that
701 # it will not be over-ridden by the library.
702 self.conn.request("PUT", "/url", "body",
703 {"Content-Length": "42"})
704 message, f = self.get_headers_and_fp()
705 self.assertEqual("42", message.get("content-length"))
706 self.assertEqual(4, len(f.read()))
707
708 def test_ascii_body(self):
709 self.conn.request("PUT", "/url", "body")
710 message, f = self.get_headers_and_fp()
711 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000712 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000713 self.assertEqual("4", message.get("content-length"))
714 self.assertEqual(b'body', f.read())
715
716 def test_latin1_body(self):
717 self.conn.request("PUT", "/url", "body\xc1")
718 message, f = self.get_headers_and_fp()
719 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000720 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000721 self.assertEqual("5", message.get("content-length"))
722 self.assertEqual(b'body\xc1', f.read())
723
724 def test_bytes_body(self):
725 self.conn.request("PUT", "/url", b"body\xc1")
726 message, f = self.get_headers_and_fp()
727 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000728 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000729 self.assertEqual("5", message.get("content-length"))
730 self.assertEqual(b'body\xc1', f.read())
731
732 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200733 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000734 with open(support.TESTFN, "w") as f:
735 f.write("body")
736 with open(support.TESTFN) as f:
737 self.conn.request("PUT", "/url", f)
738 message, f = self.get_headers_and_fp()
739 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000740 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000741 self.assertEqual("4", message.get("content-length"))
742 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000743
744 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200745 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000746 with open(support.TESTFN, "wb") as f:
747 f.write(b"body\xc1")
748 with open(support.TESTFN, "rb") as f:
749 self.conn.request("PUT", "/url", f)
750 message, f = self.get_headers_and_fp()
751 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000752 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000753 self.assertEqual("5", message.get("content-length"))
754 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000755
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000756
757class HTTPResponseTest(TestCase):
758
759 def setUp(self):
760 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
761 second-value\r\n\r\nText"
762 sock = FakeSocket(body)
763 self.resp = client.HTTPResponse(sock)
764 self.resp.begin()
765
766 def test_getting_header(self):
767 header = self.resp.getheader('My-Header')
768 self.assertEqual(header, 'first-value, second-value')
769
770 header = self.resp.getheader('My-Header', 'some default')
771 self.assertEqual(header, 'first-value, second-value')
772
773 def test_getting_nonexistent_header_with_string_default(self):
774 header = self.resp.getheader('No-Such-Header', 'default-value')
775 self.assertEqual(header, 'default-value')
776
777 def test_getting_nonexistent_header_with_iterable_default(self):
778 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
779 self.assertEqual(header, 'default, values')
780
781 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
782 self.assertEqual(header, 'default, values')
783
784 def test_getting_nonexistent_header_without_default(self):
785 header = self.resp.getheader('No-Such-Header')
786 self.assertEqual(header, None)
787
788 def test_getting_header_defaultint(self):
789 header = self.resp.getheader('No-Such-Header',default=42)
790 self.assertEqual(header, 42)
791
Jeremy Hylton2c178252004-08-07 16:28:14 +0000792def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000793 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000794 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000795 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000796
Thomas Wouters89f507f2006-12-13 04:49:30 +0000797if __name__ == '__main__':
798 test_main()