blob: 2ded60edba7966a7baed23c8ced1de543de9d07a [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:
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
775 def _check_svn_python_org(self, resp):
776 # Just a simple check that everything went fine
777 server_string = resp.getheader('server')
778 self.assertIn('Apache', server_string)
779
780 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500781 # Default settings: requires a valid cert from a trusted CA
782 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000783 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500784 with support.transient_internet('self-signed.pythontest.net'):
785 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
786 with self.assertRaises(ssl.SSLError) as exc_info:
787 h.request('GET', '/')
788 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
789
790 def test_networked_noverification(self):
791 # Switch off cert verification
792 import ssl
793 support.requires('network')
794 with support.transient_internet('self-signed.pythontest.net'):
795 context = ssl._create_unverified_context()
796 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
797 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000798 h.request('GET', '/')
799 resp = h.getresponse()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500800 self.assertIn('nginx', resp.getheader('server'))
801
802 def test_networked_trusted_by_default_cert(self):
803 # Default settings: requires a valid cert from a trusted CA
804 support.requires('network')
805 with support.transient_internet('www.python.org'):
806 h = client.HTTPSConnection('www.python.org', 443)
807 h.request('GET', '/')
808 resp = h.getresponse()
809 content_type = resp.getheader('content-type')
810 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000811
812 def test_networked_good_cert(self):
813 # We feed a CA cert that validates the server's cert
814 import ssl
815 support.requires('network')
816 with support.transient_internet('svn.python.org'):
817 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
818 context.verify_mode = ssl.CERT_REQUIRED
819 context.load_verify_locations(CACERT_svn_python_org)
820 h = client.HTTPSConnection('svn.python.org', 443, context=context)
821 h.request('GET', '/')
822 resp = h.getresponse()
823 self._check_svn_python_org(resp)
824
825 def test_networked_bad_cert(self):
826 # We feed a "CA" cert that is unrelated to the server's cert
827 import ssl
828 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500829 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000830 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
831 context.verify_mode = ssl.CERT_REQUIRED
832 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500833 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
834 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000835 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500836 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
837
838 def test_local_unknown_cert(self):
839 # The custom cert isn't known to the default trust bundle
840 import ssl
841 server = self.make_server(CERT_localhost)
842 h = client.HTTPSConnection('localhost', server.port)
843 with self.assertRaises(ssl.SSLError) as exc_info:
844 h.request('GET', '/')
845 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000846
847 def test_local_good_hostname(self):
848 # The (valid) cert validates the HTTP hostname
849 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700850 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000851 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
852 context.verify_mode = ssl.CERT_REQUIRED
853 context.load_verify_locations(CERT_localhost)
854 h = client.HTTPSConnection('localhost', server.port, context=context)
855 h.request('GET', '/nonexistent')
856 resp = h.getresponse()
857 self.assertEqual(resp.status, 404)
858
859 def test_local_bad_hostname(self):
860 # The (valid) cert doesn't validate the HTTP hostname
861 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700862 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000863 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
864 context.verify_mode = ssl.CERT_REQUIRED
865 context.load_verify_locations(CERT_fakehostname)
866 h = client.HTTPSConnection('localhost', server.port, context=context)
867 with self.assertRaises(ssl.CertificateError):
868 h.request('GET', '/')
869 # Same with explicit check_hostname=True
870 h = client.HTTPSConnection('localhost', server.port, context=context,
871 check_hostname=True)
872 with self.assertRaises(ssl.CertificateError):
873 h.request('GET', '/')
874 # With check_hostname=False, the mismatching is ignored
875 h = client.HTTPSConnection('localhost', server.port, context=context,
876 check_hostname=False)
877 h.request('GET', '/nonexistent')
878 resp = h.getresponse()
879 self.assertEqual(resp.status, 404)
880
Petri Lehtinene119c402011-10-26 21:29:15 +0300881 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
882 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200883 def test_host_port(self):
884 # Check invalid host_port
885
886 for hp in ("www.python.org:abc", "user:password@www.python.org"):
887 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
888
889 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
890 "fe80::207:e9ff:fe9b", 8000),
891 ("www.python.org:443", "www.python.org", 443),
892 ("www.python.org:", "www.python.org", 443),
893 ("www.python.org", "www.python.org", 443),
894 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
895 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
896 443)):
897 c = client.HTTPSConnection(hp)
898 self.assertEqual(h, c.host)
899 self.assertEqual(p, c.port)
900
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000901
Jeremy Hylton236654b2009-03-27 20:24:34 +0000902class RequestBodyTest(TestCase):
903 """Test cases where a request includes a message body."""
904
905 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000906 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000907 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000908 self.conn.sock = self.sock
909
910 def get_headers_and_fp(self):
911 f = io.BytesIO(self.sock.data)
912 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000913 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000914 return message, f
915
916 def test_manual_content_length(self):
917 # Set an incorrect content-length so that we can verify that
918 # it will not be over-ridden by the library.
919 self.conn.request("PUT", "/url", "body",
920 {"Content-Length": "42"})
921 message, f = self.get_headers_and_fp()
922 self.assertEqual("42", message.get("content-length"))
923 self.assertEqual(4, len(f.read()))
924
925 def test_ascii_body(self):
926 self.conn.request("PUT", "/url", "body")
927 message, f = self.get_headers_and_fp()
928 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000929 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000930 self.assertEqual("4", message.get("content-length"))
931 self.assertEqual(b'body', f.read())
932
933 def test_latin1_body(self):
934 self.conn.request("PUT", "/url", "body\xc1")
935 message, f = self.get_headers_and_fp()
936 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000937 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000938 self.assertEqual("5", message.get("content-length"))
939 self.assertEqual(b'body\xc1', f.read())
940
941 def test_bytes_body(self):
942 self.conn.request("PUT", "/url", b"body\xc1")
943 message, f = self.get_headers_and_fp()
944 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000945 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000946 self.assertEqual("5", message.get("content-length"))
947 self.assertEqual(b'body\xc1', f.read())
948
949 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200950 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000951 with open(support.TESTFN, "w") as f:
952 f.write("body")
953 with open(support.TESTFN) as f:
954 self.conn.request("PUT", "/url", f)
955 message, f = self.get_headers_and_fp()
956 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000957 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000958 self.assertEqual("4", message.get("content-length"))
959 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000960
961 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200962 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000963 with open(support.TESTFN, "wb") as f:
964 f.write(b"body\xc1")
965 with open(support.TESTFN, "rb") as f:
966 self.conn.request("PUT", "/url", f)
967 message, f = self.get_headers_and_fp()
968 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000969 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000970 self.assertEqual("5", message.get("content-length"))
971 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000972
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000973
974class HTTPResponseTest(TestCase):
975
976 def setUp(self):
977 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
978 second-value\r\n\r\nText"
979 sock = FakeSocket(body)
980 self.resp = client.HTTPResponse(sock)
981 self.resp.begin()
982
983 def test_getting_header(self):
984 header = self.resp.getheader('My-Header')
985 self.assertEqual(header, 'first-value, second-value')
986
987 header = self.resp.getheader('My-Header', 'some default')
988 self.assertEqual(header, 'first-value, second-value')
989
990 def test_getting_nonexistent_header_with_string_default(self):
991 header = self.resp.getheader('No-Such-Header', 'default-value')
992 self.assertEqual(header, 'default-value')
993
994 def test_getting_nonexistent_header_with_iterable_default(self):
995 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
996 self.assertEqual(header, 'default, values')
997
998 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
999 self.assertEqual(header, 'default, values')
1000
1001 def test_getting_nonexistent_header_without_default(self):
1002 header = self.resp.getheader('No-Such-Header')
1003 self.assertEqual(header, None)
1004
1005 def test_getting_header_defaultint(self):
1006 header = self.resp.getheader('No-Such-Header',default=42)
1007 self.assertEqual(header, 42)
1008
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001009class TunnelTests(TestCase):
1010
1011 def test_connect(self):
1012 response_text = (
1013 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1014 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1015 'Content-Length: 42\r\n\r\n'
1016 )
1017
1018 def create_connection(address, timeout=None, source_address=None):
1019 return FakeSocket(response_text, host=address[0],
1020 port=address[1])
1021
1022 conn = client.HTTPConnection('proxy.com')
1023 conn._create_connection = create_connection
1024
1025 # Once connected, we shouldn't be able to tunnel anymore
1026 conn.connect()
1027 self.assertRaises(RuntimeError, conn.set_tunnel,
1028 'destination.com')
1029
1030 # But if we close the connection, we're good
1031 conn.close()
1032 conn.set_tunnel('destination.com')
1033 conn.request('HEAD', '/', '')
1034
1035 self.assertEqual(conn.sock.host, 'proxy.com')
1036 self.assertEqual(conn.sock.port, 80)
1037 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1038 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1039
1040 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
1041 self.assertTrue(b'Host: proxy.com' not in conn.sock.data)
1042
1043 conn.close()
1044 conn.request('PUT', '/', '')
1045 self.assertEqual(conn.sock.host, 'proxy.com')
1046 self.assertEqual(conn.sock.port, 80)
1047 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1048 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1049
Jeremy Hylton2c178252004-08-07 16:28:14 +00001050def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001051 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001052 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001053 HTTPResponseTest, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001054
Thomas Wouters89f507f2006-12-13 04:49:30 +00001055if __name__ == '__main__':
1056 test_main()