blob: d259fb28533ac6bfee1bb0ce48a853485444a685 [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')
Georg Brandlfbaf9312014-11-05 20:37:40 +010018# Self-signed cert file for self-signed.pythontest.net
19CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000020
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:
Senthil Kumaran9da047b2014-04-14 13:07:56 -040024 def __init__(self, text, fileclass=io.BytesIO, host=None, port=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000025 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''
Antoine Pitrou90e47742013-01-02 22:10:47 +010030 self.sendall_calls = 0
Senthil Kumaran9da047b2014-04-14 13:07:56 -040031 self.host = host
32 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000033
Jeremy Hylton2c178252004-08-07 16:28:14 +000034 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010035 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000036 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000037
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000038 def makefile(self, mode, bufsize=None):
39 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000040 raise client.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000041 return self.fileclass(self.text)
42
Senthil Kumaran9da047b2014-04-14 13:07:56 -040043 def close(self):
44 pass
45
Jeremy Hylton636950f2009-03-28 04:34:21 +000046class EPipeSocket(FakeSocket):
47
48 def __init__(self, text, pipe_trigger):
49 # When sendall() is called with pipe_trigger, raise EPIPE.
50 FakeSocket.__init__(self, text)
51 self.pipe_trigger = pipe_trigger
52
53 def sendall(self, data):
54 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020055 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000056 self.data += data
57
58 def close(self):
59 pass
60
Serhiy Storchaka50254c52013-08-29 11:35:43 +030061class NoEOFBytesIO(io.BytesIO):
62 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000063
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000064 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000065 more from the underlying file than it should.
66 """
67 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000068 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000069 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000070 raise AssertionError('caller tried to read past EOF')
71 return data
72
73 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000074 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000075 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000076 raise AssertionError('caller tried to read past EOF')
77 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000078
Jeremy Hylton2c178252004-08-07 16:28:14 +000079class HeaderTests(TestCase):
80 def test_auto_headers(self):
81 # Some headers are added automatically, but should not be added by
82 # .request() if they are explicitly set.
83
Jeremy Hylton2c178252004-08-07 16:28:14 +000084 class HeaderCountingBuffer(list):
85 def __init__(self):
86 self.count = {}
87 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000088 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000089 if len(kv) > 1:
90 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000091 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000092 self.count.setdefault(lcKey, 0)
93 self.count[lcKey] += 1
94 list.append(self, item)
95
96 for explicit_header in True, False:
97 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000098 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +000099 conn.sock = FakeSocket('blahblahblah')
100 conn._buffer = HeaderCountingBuffer()
101
102 body = 'spamspamspam'
103 headers = {}
104 if explicit_header:
105 headers[header] = str(len(body))
106 conn.request('POST', '/', body, headers)
107 self.assertEqual(conn._buffer.count[header.lower()], 1)
108
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800109 def test_content_length_0(self):
110
111 class ContentLengthChecker(list):
112 def __init__(self):
113 list.__init__(self)
114 self.content_length = None
115 def append(self, item):
116 kv = item.split(b':', 1)
117 if len(kv) > 1 and kv[0].lower() == b'content-length':
118 self.content_length = kv[1].strip()
119 list.append(self, item)
120
121 # POST with empty body
122 conn = client.HTTPConnection('example.com')
123 conn.sock = FakeSocket(None)
124 conn._buffer = ContentLengthChecker()
125 conn.request('POST', '/', '')
126 self.assertEqual(conn._buffer.content_length, b'0',
127 'Header Content-Length not set')
128
129 # PUT request with empty body
130 conn = client.HTTPConnection('example.com')
131 conn.sock = FakeSocket(None)
132 conn._buffer = ContentLengthChecker()
133 conn.request('PUT', '/', '')
134 self.assertEqual(conn._buffer.content_length, b'0',
135 'Header Content-Length not set')
136
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000137 def test_putheader(self):
138 conn = client.HTTPConnection('example.com')
139 conn.sock = FakeSocket(None)
140 conn.putrequest('GET','/')
141 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200142 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000143
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000144 def test_ipv6host_header(self):
145 # Default host header on IPv6 transaction should wrapped by [] if
146 # its actual IPv6 address
147 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
148 b'Accept-Encoding: identity\r\n\r\n'
149 conn = client.HTTPConnection('[2001::]:81')
150 sock = FakeSocket('')
151 conn.sock = sock
152 conn.request('GET', '/foo')
153 self.assertTrue(sock.data.startswith(expected))
154
155 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
156 b'Accept-Encoding: identity\r\n\r\n'
157 conn = client.HTTPConnection('[2001:102A::]')
158 sock = FakeSocket('')
159 conn.sock = sock
160 conn.request('GET', '/foo')
161 self.assertTrue(sock.data.startswith(expected))
162
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000163
Thomas Wouters89f507f2006-12-13 04:49:30 +0000164class BasicTest(TestCase):
165 def test_status_lines(self):
166 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000167
Thomas Wouters89f507f2006-12-13 04:49:30 +0000168 body = "HTTP/1.1 200 Ok\r\n\r\nText"
169 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000170 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000171 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200172 self.assertEqual(resp.read(0), b'') # Issue #20007
173 self.assertFalse(resp.isclosed())
174 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000175 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000176 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200177 self.assertFalse(resp.closed)
178 resp.close()
179 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000180
Thomas Wouters89f507f2006-12-13 04:49:30 +0000181 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
182 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000183 resp = client.HTTPResponse(sock)
184 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000185
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000186 def test_bad_status_repr(self):
187 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000188 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000189
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000190 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100191 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000192 # same behaviour than when we read the whole thing with read()
193 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
194 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000195 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000196 resp.begin()
197 self.assertEqual(resp.read(2), b'Te')
198 self.assertFalse(resp.isclosed())
199 self.assertEqual(resp.read(2), b'xt')
200 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200201 self.assertFalse(resp.closed)
202 resp.close()
203 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000204
Antoine Pitrou38d96432011-12-06 22:33:57 +0100205 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100206 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100207 # same behaviour than when we read the whole thing with read()
208 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
209 sock = FakeSocket(body)
210 resp = client.HTTPResponse(sock)
211 resp.begin()
212 b = bytearray(2)
213 n = resp.readinto(b)
214 self.assertEqual(n, 2)
215 self.assertEqual(bytes(b), b'Te')
216 self.assertFalse(resp.isclosed())
217 n = resp.readinto(b)
218 self.assertEqual(n, 2)
219 self.assertEqual(bytes(b), b'xt')
220 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200221 self.assertFalse(resp.closed)
222 resp.close()
223 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100224
Antoine Pitrou084daa22012-12-15 19:11:54 +0100225 def test_partial_reads_no_content_length(self):
226 # when no length is present, the socket should be gracefully closed when
227 # all data was read
228 body = "HTTP/1.1 200 Ok\r\n\r\nText"
229 sock = FakeSocket(body)
230 resp = client.HTTPResponse(sock)
231 resp.begin()
232 self.assertEqual(resp.read(2), b'Te')
233 self.assertFalse(resp.isclosed())
234 self.assertEqual(resp.read(2), b'xt')
235 self.assertEqual(resp.read(1), b'')
236 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200237 self.assertFalse(resp.closed)
238 resp.close()
239 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100240
Antoine Pitroud20e7742012-12-15 19:22:30 +0100241 def test_partial_readintos_no_content_length(self):
242 # when no length is present, the socket should be gracefully closed when
243 # all data was read
244 body = "HTTP/1.1 200 Ok\r\n\r\nText"
245 sock = FakeSocket(body)
246 resp = client.HTTPResponse(sock)
247 resp.begin()
248 b = bytearray(2)
249 n = resp.readinto(b)
250 self.assertEqual(n, 2)
251 self.assertEqual(bytes(b), b'Te')
252 self.assertFalse(resp.isclosed())
253 n = resp.readinto(b)
254 self.assertEqual(n, 2)
255 self.assertEqual(bytes(b), b'xt')
256 n = resp.readinto(b)
257 self.assertEqual(n, 0)
258 self.assertTrue(resp.isclosed())
259
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100260 def test_partial_reads_incomplete_body(self):
261 # if the server shuts down the connection before the whole
262 # content-length is delivered, the socket is gracefully closed
263 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
264 sock = FakeSocket(body)
265 resp = client.HTTPResponse(sock)
266 resp.begin()
267 self.assertEqual(resp.read(2), b'Te')
268 self.assertFalse(resp.isclosed())
269 self.assertEqual(resp.read(2), b'xt')
270 self.assertEqual(resp.read(1), b'')
271 self.assertTrue(resp.isclosed())
272
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100273 def test_partial_readintos_incomplete_body(self):
274 # if the server shuts down the connection before the whole
275 # content-length is delivered, the socket is gracefully closed
276 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
277 sock = FakeSocket(body)
278 resp = client.HTTPResponse(sock)
279 resp.begin()
280 b = bytearray(2)
281 n = resp.readinto(b)
282 self.assertEqual(n, 2)
283 self.assertEqual(bytes(b), b'Te')
284 self.assertFalse(resp.isclosed())
285 n = resp.readinto(b)
286 self.assertEqual(n, 2)
287 self.assertEqual(bytes(b), b'xt')
288 n = resp.readinto(b)
289 self.assertEqual(n, 0)
290 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200291 self.assertFalse(resp.closed)
292 resp.close()
293 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100294
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295 def test_host_port(self):
296 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000297
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200298 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000299 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000300
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000301 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
302 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000303 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200304 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200306 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
307 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000308 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000309 self.assertEqual(h, c.host)
310 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000311
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 def test_response_headers(self):
313 # test response with multiple message headers with the same field name.
314 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000315 'Set-Cookie: Customer="WILE_E_COYOTE"; '
316 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
318 ' Path="/acme"\r\n'
319 '\r\n'
320 'No body\r\n')
321 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
322 ', '
323 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
324 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000325 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000326 r.begin()
327 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000328 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000329
Thomas Wouters89f507f2006-12-13 04:49:30 +0000330 def test_read_head(self):
331 # Test that the library doesn't attempt to read any data
332 # from a HEAD request. (Tickles SF bug #622042.)
333 sock = FakeSocket(
334 'HTTP/1.1 200 OK\r\n'
335 'Content-Length: 14432\r\n'
336 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300337 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000338 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000339 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000340 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000341 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000342
Antoine Pitrou38d96432011-12-06 22:33:57 +0100343 def test_readinto_head(self):
344 # Test that the library doesn't attempt to read any data
345 # from a HEAD request. (Tickles SF bug #622042.)
346 sock = FakeSocket(
347 'HTTP/1.1 200 OK\r\n'
348 'Content-Length: 14432\r\n'
349 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300350 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100351 resp = client.HTTPResponse(sock, method="HEAD")
352 resp.begin()
353 b = bytearray(5)
354 if resp.readinto(b) != 0:
355 self.fail("Did not expect response from HEAD request")
356 self.assertEqual(bytes(b), b'\x00'*5)
357
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100358 def test_too_many_headers(self):
359 headers = '\r\n'.join('Header%d: foo' % i
360 for i in range(client._MAXHEADERS + 1)) + '\r\n'
361 text = ('HTTP/1.1 200 OK\r\n' + headers)
362 s = FakeSocket(text)
363 r = client.HTTPResponse(s)
364 self.assertRaisesRegex(client.HTTPException,
365 r"got more than \d+ headers", r.begin)
366
Thomas Wouters89f507f2006-12-13 04:49:30 +0000367 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000368 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
369 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000370
Brett Cannon77b7de62010-10-29 23:31:11 +0000371 with open(__file__, 'rb') as body:
372 conn = client.HTTPConnection('example.com')
373 sock = FakeSocket(body)
374 conn.sock = sock
375 conn.request('GET', '/foo', body)
376 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
377 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000378
Antoine Pitrouead1d622009-09-29 18:44:53 +0000379 def test_send(self):
380 expected = b'this is a test this is only a test'
381 conn = client.HTTPConnection('example.com')
382 sock = FakeSocket(None)
383 conn.sock = sock
384 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000385 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000386 sock.data = b''
387 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000388 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000389 sock.data = b''
390 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000391 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000392
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300393 def test_send_updating_file(self):
394 def data():
395 yield 'data'
396 yield None
397 yield 'data_two'
398
399 class UpdatingFile():
400 mode = 'r'
401 d = data()
402 def read(self, blocksize=-1):
403 return self.d.__next__()
404
405 expected = b'data'
406
407 conn = client.HTTPConnection('example.com')
408 sock = FakeSocket("")
409 conn.sock = sock
410 conn.send(UpdatingFile())
411 self.assertEqual(sock.data, expected)
412
413
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000414 def test_send_iter(self):
415 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
416 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
417 b'\r\nonetwothree'
418
419 def body():
420 yield b"one"
421 yield b"two"
422 yield b"three"
423
424 conn = client.HTTPConnection('example.com')
425 sock = FakeSocket("")
426 conn.sock = sock
427 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000428 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000429
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800430 def test_send_type_error(self):
431 # See: Issue #12676
432 conn = client.HTTPConnection('example.com')
433 conn.sock = FakeSocket('')
434 with self.assertRaises(TypeError):
435 conn.request('POST', 'test', conn)
436
Christian Heimesa612dc02008-02-24 13:08:18 +0000437 def test_chunked(self):
438 chunked_start = (
439 'HTTP/1.1 200 OK\r\n'
440 'Transfer-Encoding: chunked\r\n\r\n'
441 'a\r\n'
442 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100443 '3\r\n'
444 'd! \r\n'
445 '8\r\n'
446 'and now \r\n'
447 '22\r\n'
448 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000449 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100450 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000451 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000452 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000453 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100454 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000455 resp.close()
456
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100457 # Various read sizes
458 for n in range(1, 12):
459 sock = FakeSocket(chunked_start + '0\r\n')
460 resp = client.HTTPResponse(sock, method="GET")
461 resp.begin()
462 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
463 resp.close()
464
Christian Heimesa612dc02008-02-24 13:08:18 +0000465 for x in ('', 'foo\r\n'):
466 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000467 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000468 resp.begin()
469 try:
470 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000471 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100472 self.assertEqual(i.partial, expected)
473 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
474 self.assertEqual(repr(i), expected_message)
475 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000476 else:
477 self.fail('IncompleteRead expected')
478 finally:
479 resp.close()
480
Antoine Pitrou38d96432011-12-06 22:33:57 +0100481 def test_readinto_chunked(self):
482 chunked_start = (
483 'HTTP/1.1 200 OK\r\n'
484 'Transfer-Encoding: chunked\r\n\r\n'
485 'a\r\n'
486 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100487 '3\r\n'
488 'd! \r\n'
489 '8\r\n'
490 'and now \r\n'
491 '22\r\n'
492 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100493 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100494 expected = b'hello world! and now for something completely different'
495 nexpected = len(expected)
496 b = bytearray(128)
497
Antoine Pitrou38d96432011-12-06 22:33:57 +0100498 sock = FakeSocket(chunked_start + '0\r\n')
499 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):
508 sock = FakeSocket(chunked_start + '0\r\n')
509 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 )
544 sock = FakeSocket(chunked_start + '0\r\n')
545 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 )
564 sock = FakeSocket(chunked_start + '0\r\n')
565 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'
639 )
640 resp = client.HTTPResponse(FakeSocket(body))
641 resp.begin()
642 self.assertRaises(client.LineTooLong, resp.read)
643
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800644 def test_early_eof(self):
645 # Test httpresponse with no \r\n termination,
646 body = "HTTP/1.1 200 Ok"
647 sock = FakeSocket(body)
648 resp = client.HTTPResponse(sock)
649 resp.begin()
650 self.assertEqual(resp.read(), b'')
651 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200652 self.assertFalse(resp.closed)
653 resp.close()
654 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800655
Antoine Pitrou90e47742013-01-02 22:10:47 +0100656 def test_delayed_ack_opt(self):
657 # Test that Nagle/delayed_ack optimistaion works correctly.
658
659 # For small payloads, it should coalesce the body with
660 # headers, resulting in a single sendall() call
661 conn = client.HTTPConnection('example.com')
662 sock = FakeSocket(None)
663 conn.sock = sock
664 body = b'x' * (conn.mss - 1)
665 conn.request('POST', '/', body)
666 self.assertEqual(sock.sendall_calls, 1)
667
668 # For large payloads, it should send the headers and
669 # then the body, resulting in more than one sendall()
670 # call
671 conn = client.HTTPConnection('example.com')
672 sock = FakeSocket(None)
673 conn.sock = sock
674 body = b'x' * conn.mss
675 conn.request('POST', '/', body)
676 self.assertGreater(sock.sendall_calls, 1)
677
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000678class OfflineTest(TestCase):
679 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000680 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000681
Gregory P. Smithb4066372010-01-03 03:28:29 +0000682
683class SourceAddressTest(TestCase):
684 def setUp(self):
685 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
686 self.port = support.bind_port(self.serv)
687 self.source_port = support.find_unused_port()
688 self.serv.listen(5)
689 self.conn = None
690
691 def tearDown(self):
692 if self.conn:
693 self.conn.close()
694 self.conn = None
695 self.serv.close()
696 self.serv = None
697
698 def testHTTPConnectionSourceAddress(self):
699 self.conn = client.HTTPConnection(HOST, self.port,
700 source_address=('', self.source_port))
701 self.conn.connect()
702 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
703
704 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
705 'http.client.HTTPSConnection not defined')
706 def testHTTPSConnectionSourceAddress(self):
707 self.conn = client.HTTPSConnection(HOST, self.port,
708 source_address=('', self.source_port))
709 # We don't test anything here other the constructor not barfing as
710 # this code doesn't deal with setting up an active running SSL server
711 # for an ssl_wrapped connect() to actually return from.
712
713
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000715 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000716
717 def setUp(self):
718 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000719 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000720 self.serv.listen(5)
721
722 def tearDown(self):
723 self.serv.close()
724 self.serv = None
725
726 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000727 # This will prove that the timeout gets through HTTPConnection
728 # and into the socket.
729
Georg Brandlf78e02b2008-06-10 17:40:04 +0000730 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200731 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000732 socket.setdefaulttimeout(30)
733 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000734 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000735 httpConn.connect()
736 finally:
737 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738 self.assertEqual(httpConn.sock.gettimeout(), 30)
739 httpConn.close()
740
Georg Brandlf78e02b2008-06-10 17:40:04 +0000741 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200742 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 socket.setdefaulttimeout(30)
744 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000745 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000746 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747 httpConn.connect()
748 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000749 socket.setdefaulttimeout(None)
750 self.assertEqual(httpConn.sock.gettimeout(), None)
751 httpConn.close()
752
753 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000754 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000755 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000756 self.assertEqual(httpConn.sock.gettimeout(), 30)
757 httpConn.close()
758
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000759
760class HTTPSTest(TestCase):
761
762 def setUp(self):
763 if not hasattr(client, 'HTTPSConnection'):
764 self.skipTest('ssl support required')
765
766 def make_server(self, certfile):
767 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100768 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000769
770 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000771 # simple test to check it's storing the timeout
772 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
773 self.assertEqual(h.timeout, 30)
774
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000775 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500776 # Default settings: requires a valid cert from a trusted CA
777 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000778 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500779 with support.transient_internet('self-signed.pythontest.net'):
780 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
781 with self.assertRaises(ssl.SSLError) as exc_info:
782 h.request('GET', '/')
783 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
784
785 def test_networked_noverification(self):
786 # Switch off cert verification
787 import ssl
788 support.requires('network')
789 with support.transient_internet('self-signed.pythontest.net'):
790 context = ssl._create_unverified_context()
791 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
792 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000793 h.request('GET', '/')
794 resp = h.getresponse()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500795 self.assertIn('nginx', resp.getheader('server'))
796
797 def test_networked_trusted_by_default_cert(self):
798 # Default settings: requires a valid cert from a trusted CA
799 support.requires('network')
800 with support.transient_internet('www.python.org'):
801 h = client.HTTPSConnection('www.python.org', 443)
802 h.request('GET', '/')
803 resp = h.getresponse()
804 content_type = resp.getheader('content-type')
805 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000806
807 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +0100808 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000809 import ssl
810 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +0100811 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000812 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
813 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +0100814 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
815 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000816 h.request('GET', '/')
817 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +0100818 server_string = resp.getheader('server')
819 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000820
821 def test_networked_bad_cert(self):
822 # We feed a "CA" cert that is unrelated to the server's cert
823 import ssl
824 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500825 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000826 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
827 context.verify_mode = ssl.CERT_REQUIRED
828 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500829 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
830 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000831 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500832 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
833
834 def test_local_unknown_cert(self):
835 # The custom cert isn't known to the default trust bundle
836 import ssl
837 server = self.make_server(CERT_localhost)
838 h = client.HTTPSConnection('localhost', server.port)
839 with self.assertRaises(ssl.SSLError) as exc_info:
840 h.request('GET', '/')
841 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000842
843 def test_local_good_hostname(self):
844 # The (valid) cert validates the HTTP hostname
845 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700846 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000847 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
848 context.verify_mode = ssl.CERT_REQUIRED
849 context.load_verify_locations(CERT_localhost)
850 h = client.HTTPSConnection('localhost', server.port, context=context)
851 h.request('GET', '/nonexistent')
852 resp = h.getresponse()
853 self.assertEqual(resp.status, 404)
854
855 def test_local_bad_hostname(self):
856 # The (valid) cert doesn't validate the HTTP hostname
857 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700858 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000859 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
860 context.verify_mode = ssl.CERT_REQUIRED
861 context.load_verify_locations(CERT_fakehostname)
862 h = client.HTTPSConnection('localhost', server.port, context=context)
863 with self.assertRaises(ssl.CertificateError):
864 h.request('GET', '/')
865 # Same with explicit check_hostname=True
866 h = client.HTTPSConnection('localhost', server.port, context=context,
867 check_hostname=True)
868 with self.assertRaises(ssl.CertificateError):
869 h.request('GET', '/')
870 # With check_hostname=False, the mismatching is ignored
871 h = client.HTTPSConnection('localhost', server.port, context=context,
872 check_hostname=False)
873 h.request('GET', '/nonexistent')
874 resp = h.getresponse()
875 self.assertEqual(resp.status, 404)
876
Petri Lehtinene119c402011-10-26 21:29:15 +0300877 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
878 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200879 def test_host_port(self):
880 # Check invalid host_port
881
882 for hp in ("www.python.org:abc", "user:password@www.python.org"):
883 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
884
885 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
886 "fe80::207:e9ff:fe9b", 8000),
887 ("www.python.org:443", "www.python.org", 443),
888 ("www.python.org:", "www.python.org", 443),
889 ("www.python.org", "www.python.org", 443),
890 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
891 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
892 443)):
893 c = client.HTTPSConnection(hp)
894 self.assertEqual(h, c.host)
895 self.assertEqual(p, c.port)
896
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000897
Jeremy Hylton236654b2009-03-27 20:24:34 +0000898class RequestBodyTest(TestCase):
899 """Test cases where a request includes a message body."""
900
901 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000902 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000903 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000904 self.conn.sock = self.sock
905
906 def get_headers_and_fp(self):
907 f = io.BytesIO(self.sock.data)
908 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000909 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000910 return message, f
911
912 def test_manual_content_length(self):
913 # Set an incorrect content-length so that we can verify that
914 # it will not be over-ridden by the library.
915 self.conn.request("PUT", "/url", "body",
916 {"Content-Length": "42"})
917 message, f = self.get_headers_and_fp()
918 self.assertEqual("42", message.get("content-length"))
919 self.assertEqual(4, len(f.read()))
920
921 def test_ascii_body(self):
922 self.conn.request("PUT", "/url", "body")
923 message, f = self.get_headers_and_fp()
924 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000925 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000926 self.assertEqual("4", message.get("content-length"))
927 self.assertEqual(b'body', f.read())
928
929 def test_latin1_body(self):
930 self.conn.request("PUT", "/url", "body\xc1")
931 message, f = self.get_headers_and_fp()
932 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000933 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000934 self.assertEqual("5", message.get("content-length"))
935 self.assertEqual(b'body\xc1', f.read())
936
937 def test_bytes_body(self):
938 self.conn.request("PUT", "/url", b"body\xc1")
939 message, f = self.get_headers_and_fp()
940 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000941 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000942 self.assertEqual("5", message.get("content-length"))
943 self.assertEqual(b'body\xc1', f.read())
944
945 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200946 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000947 with open(support.TESTFN, "w") as f:
948 f.write("body")
949 with open(support.TESTFN) as f:
950 self.conn.request("PUT", "/url", f)
951 message, f = self.get_headers_and_fp()
952 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000953 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000954 self.assertEqual("4", message.get("content-length"))
955 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000956
957 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200958 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000959 with open(support.TESTFN, "wb") as f:
960 f.write(b"body\xc1")
961 with open(support.TESTFN, "rb") as f:
962 self.conn.request("PUT", "/url", f)
963 message, f = self.get_headers_and_fp()
964 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000965 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000966 self.assertEqual("5", message.get("content-length"))
967 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000968
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000969
970class HTTPResponseTest(TestCase):
971
972 def setUp(self):
973 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
974 second-value\r\n\r\nText"
975 sock = FakeSocket(body)
976 self.resp = client.HTTPResponse(sock)
977 self.resp.begin()
978
979 def test_getting_header(self):
980 header = self.resp.getheader('My-Header')
981 self.assertEqual(header, 'first-value, second-value')
982
983 header = self.resp.getheader('My-Header', 'some default')
984 self.assertEqual(header, 'first-value, second-value')
985
986 def test_getting_nonexistent_header_with_string_default(self):
987 header = self.resp.getheader('No-Such-Header', 'default-value')
988 self.assertEqual(header, 'default-value')
989
990 def test_getting_nonexistent_header_with_iterable_default(self):
991 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
992 self.assertEqual(header, 'default, values')
993
994 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
995 self.assertEqual(header, 'default, values')
996
997 def test_getting_nonexistent_header_without_default(self):
998 header = self.resp.getheader('No-Such-Header')
999 self.assertEqual(header, None)
1000
1001 def test_getting_header_defaultint(self):
1002 header = self.resp.getheader('No-Such-Header',default=42)
1003 self.assertEqual(header, 42)
1004
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001005class TunnelTests(TestCase):
1006
1007 def test_connect(self):
1008 response_text = (
1009 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1010 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1011 'Content-Length: 42\r\n\r\n'
1012 )
1013
1014 def create_connection(address, timeout=None, source_address=None):
1015 return FakeSocket(response_text, host=address[0],
1016 port=address[1])
1017
1018 conn = client.HTTPConnection('proxy.com')
1019 conn._create_connection = create_connection
1020
1021 # Once connected, we shouldn't be able to tunnel anymore
1022 conn.connect()
1023 self.assertRaises(RuntimeError, conn.set_tunnel,
1024 'destination.com')
1025
1026 # But if we close the connection, we're good
1027 conn.close()
1028 conn.set_tunnel('destination.com')
1029 conn.request('HEAD', '/', '')
1030
1031 self.assertEqual(conn.sock.host, 'proxy.com')
1032 self.assertEqual(conn.sock.port, 80)
1033 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1034 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1035
1036 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
1037 self.assertTrue(b'Host: proxy.com' not in conn.sock.data)
1038
1039 conn.close()
1040 conn.request('PUT', '/', '')
1041 self.assertEqual(conn.sock.host, 'proxy.com')
1042 self.assertEqual(conn.sock.port, 80)
1043 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1044 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1045
Jeremy Hylton2c178252004-08-07 16:28:14 +00001046def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001047 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001048 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001049 HTTPResponseTest, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001050
Thomas Wouters89f507f2006-12-13 04:49:30 +00001051if __name__ == '__main__':
1052 test_main()