blob: 1456de322783553293976c095a63cf6d715f3425 [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
Serhiy Storchakab491e052014-12-01 13:07:45 +020031 self.file_closed = False
Senthil Kumaran9da047b2014-04-14 13:07:56 -040032 self.host = host
33 self.port = port
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000034
Jeremy Hylton2c178252004-08-07 16:28:14 +000035 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010036 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000037 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000038
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000039 def makefile(self, mode, bufsize=None):
40 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000041 raise client.UnimplementedFileMode()
Serhiy Storchakab491e052014-12-01 13:07:45 +020042 # keep the file around so we can check how much was read from it
43 self.file = self.fileclass(self.text)
44 self.file.close = self.file_close #nerf close ()
45 return self.file
46
47 def file_close(self):
48 self.file_closed = True
Jeremy Hylton121d34a2003-07-08 12:36:58 +000049
Senthil Kumaran9da047b2014-04-14 13:07:56 -040050 def close(self):
51 pass
52
Jeremy Hylton636950f2009-03-28 04:34:21 +000053class EPipeSocket(FakeSocket):
54
55 def __init__(self, text, pipe_trigger):
56 # When sendall() is called with pipe_trigger, raise EPIPE.
57 FakeSocket.__init__(self, text)
58 self.pipe_trigger = pipe_trigger
59
60 def sendall(self, data):
61 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020062 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000063 self.data += data
64
65 def close(self):
66 pass
67
Serhiy Storchaka50254c52013-08-29 11:35:43 +030068class NoEOFBytesIO(io.BytesIO):
69 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000070
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000071 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000072 more from the underlying file than it should.
73 """
74 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000075 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000076 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000077 raise AssertionError('caller tried to read past EOF')
78 return data
79
80 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000081 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000082 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000083 raise AssertionError('caller tried to read past EOF')
84 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000085
Jeremy Hylton2c178252004-08-07 16:28:14 +000086class HeaderTests(TestCase):
87 def test_auto_headers(self):
88 # Some headers are added automatically, but should not be added by
89 # .request() if they are explicitly set.
90
Jeremy Hylton2c178252004-08-07 16:28:14 +000091 class HeaderCountingBuffer(list):
92 def __init__(self):
93 self.count = {}
94 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000095 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000096 if len(kv) > 1:
97 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000098 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000099 self.count.setdefault(lcKey, 0)
100 self.count[lcKey] += 1
101 list.append(self, item)
102
103 for explicit_header in True, False:
104 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000105 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +0000106 conn.sock = FakeSocket('blahblahblah')
107 conn._buffer = HeaderCountingBuffer()
108
109 body = 'spamspamspam'
110 headers = {}
111 if explicit_header:
112 headers[header] = str(len(body))
113 conn.request('POST', '/', body, headers)
114 self.assertEqual(conn._buffer.count[header.lower()], 1)
115
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800116 def test_content_length_0(self):
117
118 class ContentLengthChecker(list):
119 def __init__(self):
120 list.__init__(self)
121 self.content_length = None
122 def append(self, item):
123 kv = item.split(b':', 1)
124 if len(kv) > 1 and kv[0].lower() == b'content-length':
125 self.content_length = kv[1].strip()
126 list.append(self, item)
127
128 # POST with empty body
129 conn = client.HTTPConnection('example.com')
130 conn.sock = FakeSocket(None)
131 conn._buffer = ContentLengthChecker()
132 conn.request('POST', '/', '')
133 self.assertEqual(conn._buffer.content_length, b'0',
134 'Header Content-Length not set')
135
136 # PUT request with empty body
137 conn = client.HTTPConnection('example.com')
138 conn.sock = FakeSocket(None)
139 conn._buffer = ContentLengthChecker()
140 conn.request('PUT', '/', '')
141 self.assertEqual(conn._buffer.content_length, b'0',
142 'Header Content-Length not set')
143
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000144 def test_putheader(self):
145 conn = client.HTTPConnection('example.com')
146 conn.sock = FakeSocket(None)
147 conn.putrequest('GET','/')
148 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200149 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000150
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000151 def test_ipv6host_header(self):
152 # Default host header on IPv6 transaction should wrapped by [] if
153 # its actual IPv6 address
154 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
155 b'Accept-Encoding: identity\r\n\r\n'
156 conn = client.HTTPConnection('[2001::]:81')
157 sock = FakeSocket('')
158 conn.sock = sock
159 conn.request('GET', '/foo')
160 self.assertTrue(sock.data.startswith(expected))
161
162 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
163 b'Accept-Encoding: identity\r\n\r\n'
164 conn = client.HTTPConnection('[2001:102A::]')
165 sock = FakeSocket('')
166 conn.sock = sock
167 conn.request('GET', '/foo')
168 self.assertTrue(sock.data.startswith(expected))
169
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000170
Thomas Wouters89f507f2006-12-13 04:49:30 +0000171class BasicTest(TestCase):
172 def test_status_lines(self):
173 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000174
Thomas Wouters89f507f2006-12-13 04:49:30 +0000175 body = "HTTP/1.1 200 Ok\r\n\r\nText"
176 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000177 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000178 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200179 self.assertEqual(resp.read(0), b'') # Issue #20007
180 self.assertFalse(resp.isclosed())
181 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000182 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000183 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200184 self.assertFalse(resp.closed)
185 resp.close()
186 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000187
Thomas Wouters89f507f2006-12-13 04:49:30 +0000188 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
189 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000190 resp = client.HTTPResponse(sock)
191 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000192
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000193 def test_bad_status_repr(self):
194 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000195 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000196
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000197 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100198 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000199 # same behaviour than when we read the whole thing with read()
200 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
201 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000202 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000203 resp.begin()
204 self.assertEqual(resp.read(2), b'Te')
205 self.assertFalse(resp.isclosed())
206 self.assertEqual(resp.read(2), b'xt')
207 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200208 self.assertFalse(resp.closed)
209 resp.close()
210 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000211
Antoine Pitrou38d96432011-12-06 22:33:57 +0100212 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100213 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100214 # same behaviour than when we read the whole thing with read()
215 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
216 sock = FakeSocket(body)
217 resp = client.HTTPResponse(sock)
218 resp.begin()
219 b = bytearray(2)
220 n = resp.readinto(b)
221 self.assertEqual(n, 2)
222 self.assertEqual(bytes(b), b'Te')
223 self.assertFalse(resp.isclosed())
224 n = resp.readinto(b)
225 self.assertEqual(n, 2)
226 self.assertEqual(bytes(b), b'xt')
227 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200228 self.assertFalse(resp.closed)
229 resp.close()
230 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100231
Antoine Pitrou084daa22012-12-15 19:11:54 +0100232 def test_partial_reads_no_content_length(self):
233 # when no length is present, the socket should be gracefully closed when
234 # all data was read
235 body = "HTTP/1.1 200 Ok\r\n\r\nText"
236 sock = FakeSocket(body)
237 resp = client.HTTPResponse(sock)
238 resp.begin()
239 self.assertEqual(resp.read(2), b'Te')
240 self.assertFalse(resp.isclosed())
241 self.assertEqual(resp.read(2), b'xt')
242 self.assertEqual(resp.read(1), b'')
243 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200244 self.assertFalse(resp.closed)
245 resp.close()
246 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100247
Antoine Pitroud20e7742012-12-15 19:22:30 +0100248 def test_partial_readintos_no_content_length(self):
249 # when no length is present, the socket should be gracefully closed when
250 # all data was read
251 body = "HTTP/1.1 200 Ok\r\n\r\nText"
252 sock = FakeSocket(body)
253 resp = client.HTTPResponse(sock)
254 resp.begin()
255 b = bytearray(2)
256 n = resp.readinto(b)
257 self.assertEqual(n, 2)
258 self.assertEqual(bytes(b), b'Te')
259 self.assertFalse(resp.isclosed())
260 n = resp.readinto(b)
261 self.assertEqual(n, 2)
262 self.assertEqual(bytes(b), b'xt')
263 n = resp.readinto(b)
264 self.assertEqual(n, 0)
265 self.assertTrue(resp.isclosed())
266
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100267 def test_partial_reads_incomplete_body(self):
268 # if the server shuts down the connection before the whole
269 # content-length is delivered, the socket is gracefully closed
270 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
271 sock = FakeSocket(body)
272 resp = client.HTTPResponse(sock)
273 resp.begin()
274 self.assertEqual(resp.read(2), b'Te')
275 self.assertFalse(resp.isclosed())
276 self.assertEqual(resp.read(2), b'xt')
277 self.assertEqual(resp.read(1), b'')
278 self.assertTrue(resp.isclosed())
279
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100280 def test_partial_readintos_incomplete_body(self):
281 # if the server shuts down the connection before the whole
282 # content-length is delivered, the socket is gracefully closed
283 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
284 sock = FakeSocket(body)
285 resp = client.HTTPResponse(sock)
286 resp.begin()
287 b = bytearray(2)
288 n = resp.readinto(b)
289 self.assertEqual(n, 2)
290 self.assertEqual(bytes(b), b'Te')
291 self.assertFalse(resp.isclosed())
292 n = resp.readinto(b)
293 self.assertEqual(n, 2)
294 self.assertEqual(bytes(b), b'xt')
295 n = resp.readinto(b)
296 self.assertEqual(n, 0)
297 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200298 self.assertFalse(resp.closed)
299 resp.close()
300 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100301
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 def test_host_port(self):
303 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000304
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200305 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000306 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000308 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
309 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200311 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200313 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
314 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000315 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000316 self.assertEqual(h, c.host)
317 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000318
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319 def test_response_headers(self):
320 # test response with multiple message headers with the same field name.
321 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000322 'Set-Cookie: Customer="WILE_E_COYOTE"; '
323 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000324 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
325 ' Path="/acme"\r\n'
326 '\r\n'
327 'No body\r\n')
328 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
329 ', '
330 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
331 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000332 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 r.begin()
334 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000335 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000336
Thomas Wouters89f507f2006-12-13 04:49:30 +0000337 def test_read_head(self):
338 # Test that the library doesn't attempt to read any data
339 # from a HEAD request. (Tickles SF bug #622042.)
340 sock = FakeSocket(
341 'HTTP/1.1 200 OK\r\n'
342 'Content-Length: 14432\r\n'
343 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300344 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000345 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000346 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000347 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000348 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000349
Antoine Pitrou38d96432011-12-06 22:33:57 +0100350 def test_readinto_head(self):
351 # Test that the library doesn't attempt to read any data
352 # from a HEAD request. (Tickles SF bug #622042.)
353 sock = FakeSocket(
354 'HTTP/1.1 200 OK\r\n'
355 'Content-Length: 14432\r\n'
356 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300357 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100358 resp = client.HTTPResponse(sock, method="HEAD")
359 resp.begin()
360 b = bytearray(5)
361 if resp.readinto(b) != 0:
362 self.fail("Did not expect response from HEAD request")
363 self.assertEqual(bytes(b), b'\x00'*5)
364
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100365 def test_too_many_headers(self):
366 headers = '\r\n'.join('Header%d: foo' % i
367 for i in range(client._MAXHEADERS + 1)) + '\r\n'
368 text = ('HTTP/1.1 200 OK\r\n' + headers)
369 s = FakeSocket(text)
370 r = client.HTTPResponse(s)
371 self.assertRaisesRegex(client.HTTPException,
372 r"got more than \d+ headers", r.begin)
373
Thomas Wouters89f507f2006-12-13 04:49:30 +0000374 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000375 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
376 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000377
Brett Cannon77b7de62010-10-29 23:31:11 +0000378 with open(__file__, 'rb') as body:
379 conn = client.HTTPConnection('example.com')
380 sock = FakeSocket(body)
381 conn.sock = sock
382 conn.request('GET', '/foo', body)
383 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
384 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000385
Antoine Pitrouead1d622009-09-29 18:44:53 +0000386 def test_send(self):
387 expected = b'this is a test this is only a test'
388 conn = client.HTTPConnection('example.com')
389 sock = FakeSocket(None)
390 conn.sock = sock
391 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000392 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000393 sock.data = b''
394 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000395 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000396 sock.data = b''
397 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000398 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000399
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300400 def test_send_updating_file(self):
401 def data():
402 yield 'data'
403 yield None
404 yield 'data_two'
405
406 class UpdatingFile():
407 mode = 'r'
408 d = data()
409 def read(self, blocksize=-1):
410 return self.d.__next__()
411
412 expected = b'data'
413
414 conn = client.HTTPConnection('example.com')
415 sock = FakeSocket("")
416 conn.sock = sock
417 conn.send(UpdatingFile())
418 self.assertEqual(sock.data, expected)
419
420
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000421 def test_send_iter(self):
422 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
423 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
424 b'\r\nonetwothree'
425
426 def body():
427 yield b"one"
428 yield b"two"
429 yield b"three"
430
431 conn = client.HTTPConnection('example.com')
432 sock = FakeSocket("")
433 conn.sock = sock
434 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000435 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000436
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800437 def test_send_type_error(self):
438 # See: Issue #12676
439 conn = client.HTTPConnection('example.com')
440 conn.sock = FakeSocket('')
441 with self.assertRaises(TypeError):
442 conn.request('POST', 'test', conn)
443
Christian Heimesa612dc02008-02-24 13:08:18 +0000444 def test_chunked(self):
445 chunked_start = (
446 'HTTP/1.1 200 OK\r\n'
447 'Transfer-Encoding: chunked\r\n\r\n'
448 'a\r\n'
449 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100450 '3\r\n'
451 'd! \r\n'
452 '8\r\n'
453 'and now \r\n'
454 '22\r\n'
455 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000456 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100457 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000458 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000459 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000460 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100461 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000462 resp.close()
463
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100464 # Various read sizes
465 for n in range(1, 12):
466 sock = FakeSocket(chunked_start + '0\r\n')
467 resp = client.HTTPResponse(sock, method="GET")
468 resp.begin()
469 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
470 resp.close()
471
Christian Heimesa612dc02008-02-24 13:08:18 +0000472 for x in ('', 'foo\r\n'):
473 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000474 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000475 resp.begin()
476 try:
477 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000478 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100479 self.assertEqual(i.partial, expected)
480 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
481 self.assertEqual(repr(i), expected_message)
482 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000483 else:
484 self.fail('IncompleteRead expected')
485 finally:
486 resp.close()
487
Antoine Pitrou38d96432011-12-06 22:33:57 +0100488 def test_readinto_chunked(self):
489 chunked_start = (
490 'HTTP/1.1 200 OK\r\n'
491 'Transfer-Encoding: chunked\r\n\r\n'
492 'a\r\n'
493 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100494 '3\r\n'
495 'd! \r\n'
496 '8\r\n'
497 'and now \r\n'
498 '22\r\n'
499 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100500 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100501 expected = b'hello world! and now for something completely different'
502 nexpected = len(expected)
503 b = bytearray(128)
504
Antoine Pitrou38d96432011-12-06 22:33:57 +0100505 sock = FakeSocket(chunked_start + '0\r\n')
506 resp = client.HTTPResponse(sock, method="GET")
507 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100508 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100509 self.assertEqual(b[:nexpected], expected)
510 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100511 resp.close()
512
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100513 # Various read sizes
514 for n in range(1, 12):
515 sock = FakeSocket(chunked_start + '0\r\n')
516 resp = client.HTTPResponse(sock, method="GET")
517 resp.begin()
518 m = memoryview(b)
519 i = resp.readinto(m[0:n])
520 i += resp.readinto(m[i:n + i])
521 i += resp.readinto(m[i:])
522 self.assertEqual(b[:nexpected], expected)
523 self.assertEqual(i, nexpected)
524 resp.close()
525
Antoine Pitrou38d96432011-12-06 22:33:57 +0100526 for x in ('', 'foo\r\n'):
527 sock = FakeSocket(chunked_start + x)
528 resp = client.HTTPResponse(sock, method="GET")
529 resp.begin()
530 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100531 n = resp.readinto(b)
532 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100533 self.assertEqual(i.partial, expected)
534 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
535 self.assertEqual(repr(i), expected_message)
536 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100537 else:
538 self.fail('IncompleteRead expected')
539 finally:
540 resp.close()
541
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000542 def test_chunked_head(self):
543 chunked_start = (
544 'HTTP/1.1 200 OK\r\n'
545 'Transfer-Encoding: chunked\r\n\r\n'
546 'a\r\n'
547 'hello world\r\n'
548 '1\r\n'
549 'd\r\n'
550 )
551 sock = FakeSocket(chunked_start + '0\r\n')
552 resp = client.HTTPResponse(sock, method="HEAD")
553 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000554 self.assertEqual(resp.read(), b'')
555 self.assertEqual(resp.status, 200)
556 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000557 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200558 self.assertFalse(resp.closed)
559 resp.close()
560 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000561
Antoine Pitrou38d96432011-12-06 22:33:57 +0100562 def test_readinto_chunked_head(self):
563 chunked_start = (
564 'HTTP/1.1 200 OK\r\n'
565 'Transfer-Encoding: chunked\r\n\r\n'
566 'a\r\n'
567 'hello world\r\n'
568 '1\r\n'
569 'd\r\n'
570 )
571 sock = FakeSocket(chunked_start + '0\r\n')
572 resp = client.HTTPResponse(sock, method="HEAD")
573 resp.begin()
574 b = bytearray(5)
575 n = resp.readinto(b)
576 self.assertEqual(n, 0)
577 self.assertEqual(bytes(b), b'\x00'*5)
578 self.assertEqual(resp.status, 200)
579 self.assertEqual(resp.reason, 'OK')
580 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200581 self.assertFalse(resp.closed)
582 resp.close()
583 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100584
Christian Heimesa612dc02008-02-24 13:08:18 +0000585 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000586 sock = FakeSocket(
587 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000588 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000589 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000590 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100591 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000592
Benjamin Peterson6accb982009-03-02 22:50:25 +0000593 def test_incomplete_read(self):
594 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000595 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000596 resp.begin()
597 try:
598 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000599 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000600 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000601 self.assertEqual(repr(i),
602 "IncompleteRead(7 bytes read, 3 more expected)")
603 self.assertEqual(str(i),
604 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100605 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000606 else:
607 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000608
Jeremy Hylton636950f2009-03-28 04:34:21 +0000609 def test_epipe(self):
610 sock = EPipeSocket(
611 "HTTP/1.0 401 Authorization Required\r\n"
612 "Content-type: text/html\r\n"
613 "WWW-Authenticate: Basic realm=\"example\"\r\n",
614 b"Content-Length")
615 conn = client.HTTPConnection("example.com")
616 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200617 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000618 lambda: conn.request("PUT", "/url", "body"))
619 resp = conn.getresponse()
620 self.assertEqual(401, resp.status)
621 self.assertEqual("Basic realm=\"example\"",
622 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000623
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000624 # Test lines overflowing the max line size (_MAXLINE in http.client)
625
626 def test_overflowing_status_line(self):
627 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
628 resp = client.HTTPResponse(FakeSocket(body))
629 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
630
631 def test_overflowing_header_line(self):
632 body = (
633 'HTTP/1.1 200 OK\r\n'
634 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
635 )
636 resp = client.HTTPResponse(FakeSocket(body))
637 self.assertRaises(client.LineTooLong, resp.begin)
638
639 def test_overflowing_chunked_line(self):
640 body = (
641 'HTTP/1.1 200 OK\r\n'
642 'Transfer-Encoding: chunked\r\n\r\n'
643 + '0' * 65536 + 'a\r\n'
644 'hello world\r\n'
645 '0\r\n'
646 )
647 resp = client.HTTPResponse(FakeSocket(body))
648 resp.begin()
649 self.assertRaises(client.LineTooLong, resp.read)
650
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800651 def test_early_eof(self):
652 # Test httpresponse with no \r\n termination,
653 body = "HTTP/1.1 200 Ok"
654 sock = FakeSocket(body)
655 resp = client.HTTPResponse(sock)
656 resp.begin()
657 self.assertEqual(resp.read(), b'')
658 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200659 self.assertFalse(resp.closed)
660 resp.close()
661 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800662
Antoine Pitrou90e47742013-01-02 22:10:47 +0100663 def test_delayed_ack_opt(self):
664 # Test that Nagle/delayed_ack optimistaion works correctly.
665
666 # For small payloads, it should coalesce the body with
667 # headers, resulting in a single sendall() call
668 conn = client.HTTPConnection('example.com')
669 sock = FakeSocket(None)
670 conn.sock = sock
671 body = b'x' * (conn.mss - 1)
672 conn.request('POST', '/', body)
673 self.assertEqual(sock.sendall_calls, 1)
674
675 # For large payloads, it should send the headers and
676 # then the body, resulting in more than one sendall()
677 # call
678 conn = client.HTTPConnection('example.com')
679 sock = FakeSocket(None)
680 conn.sock = sock
681 body = b'x' * conn.mss
682 conn.request('POST', '/', body)
683 self.assertGreater(sock.sendall_calls, 1)
684
Serhiy Storchakab491e052014-12-01 13:07:45 +0200685 def test_error_leak(self):
686 # Test that the socket is not leaked if getresponse() fails
687 conn = client.HTTPConnection('example.com')
688 response = None
689 class Response(client.HTTPResponse):
690 def __init__(self, *pos, **kw):
691 nonlocal response
692 response = self # Avoid garbage collector closing the socket
693 client.HTTPResponse.__init__(self, *pos, **kw)
694 conn.response_class = Response
695 conn.sock = FakeSocket('') # Emulate server dropping connection
696 conn.request('GET', '/')
697 self.assertRaises(client.BadStatusLine, conn.getresponse)
698 self.assertTrue(response.closed)
699 self.assertTrue(conn.sock.file_closed)
700
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000701class OfflineTest(TestCase):
702 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000703 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000704
Gregory P. Smithb4066372010-01-03 03:28:29 +0000705
706class SourceAddressTest(TestCase):
707 def setUp(self):
708 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
709 self.port = support.bind_port(self.serv)
710 self.source_port = support.find_unused_port()
711 self.serv.listen(5)
712 self.conn = None
713
714 def tearDown(self):
715 if self.conn:
716 self.conn.close()
717 self.conn = None
718 self.serv.close()
719 self.serv = None
720
721 def testHTTPConnectionSourceAddress(self):
722 self.conn = client.HTTPConnection(HOST, self.port,
723 source_address=('', self.source_port))
724 self.conn.connect()
725 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
726
727 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
728 'http.client.HTTPSConnection not defined')
729 def testHTTPSConnectionSourceAddress(self):
730 self.conn = client.HTTPSConnection(HOST, self.port,
731 source_address=('', self.source_port))
732 # We don't test anything here other the constructor not barfing as
733 # this code doesn't deal with setting up an active running SSL server
734 # for an ssl_wrapped connect() to actually return from.
735
736
Guido van Rossumd8faa362007-04-27 19:54:29 +0000737class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000738 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000739
740 def setUp(self):
741 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000742 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000743 self.serv.listen(5)
744
745 def tearDown(self):
746 self.serv.close()
747 self.serv = None
748
749 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000750 # This will prove that the timeout gets through HTTPConnection
751 # and into the socket.
752
Georg Brandlf78e02b2008-06-10 17:40:04 +0000753 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200754 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000755 socket.setdefaulttimeout(30)
756 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000757 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000758 httpConn.connect()
759 finally:
760 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000761 self.assertEqual(httpConn.sock.gettimeout(), 30)
762 httpConn.close()
763
Georg Brandlf78e02b2008-06-10 17:40:04 +0000764 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200765 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000766 socket.setdefaulttimeout(30)
767 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000768 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000769 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000770 httpConn.connect()
771 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000772 socket.setdefaulttimeout(None)
773 self.assertEqual(httpConn.sock.gettimeout(), None)
774 httpConn.close()
775
776 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000777 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000778 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000779 self.assertEqual(httpConn.sock.gettimeout(), 30)
780 httpConn.close()
781
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000782
783class HTTPSTest(TestCase):
784
785 def setUp(self):
786 if not hasattr(client, 'HTTPSConnection'):
787 self.skipTest('ssl support required')
788
789 def make_server(self, certfile):
790 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100791 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000792
793 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000794 # simple test to check it's storing the timeout
795 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
796 self.assertEqual(h.timeout, 30)
797
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000798 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500799 # Default settings: requires a valid cert from a trusted CA
800 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000801 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500802 with support.transient_internet('self-signed.pythontest.net'):
803 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
804 with self.assertRaises(ssl.SSLError) as exc_info:
805 h.request('GET', '/')
806 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
807
808 def test_networked_noverification(self):
809 # Switch off cert verification
810 import ssl
811 support.requires('network')
812 with support.transient_internet('self-signed.pythontest.net'):
813 context = ssl._create_unverified_context()
814 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
815 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000816 h.request('GET', '/')
817 resp = h.getresponse()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500818 self.assertIn('nginx', resp.getheader('server'))
819
Benjamin Peterson2615e9e2014-11-25 15:16:55 -0600820 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500821 def test_networked_trusted_by_default_cert(self):
822 # Default settings: requires a valid cert from a trusted CA
823 support.requires('network')
824 with support.transient_internet('www.python.org'):
825 h = client.HTTPSConnection('www.python.org', 443)
826 h.request('GET', '/')
827 resp = h.getresponse()
828 content_type = resp.getheader('content-type')
829 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000830
831 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +0100832 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000833 import ssl
834 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +0100835 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000836 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
837 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +0100838 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
839 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000840 h.request('GET', '/')
841 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +0100842 server_string = resp.getheader('server')
843 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000844
845 def test_networked_bad_cert(self):
846 # We feed a "CA" cert that is unrelated to the server's cert
847 import ssl
848 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500849 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000850 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
851 context.verify_mode = ssl.CERT_REQUIRED
852 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500853 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
854 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000855 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500856 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
857
858 def test_local_unknown_cert(self):
859 # The custom cert isn't known to the default trust bundle
860 import ssl
861 server = self.make_server(CERT_localhost)
862 h = client.HTTPSConnection('localhost', server.port)
863 with self.assertRaises(ssl.SSLError) as exc_info:
864 h.request('GET', '/')
865 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000866
867 def test_local_good_hostname(self):
868 # The (valid) cert validates the HTTP hostname
869 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700870 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000871 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
872 context.verify_mode = ssl.CERT_REQUIRED
873 context.load_verify_locations(CERT_localhost)
874 h = client.HTTPSConnection('localhost', server.port, context=context)
875 h.request('GET', '/nonexistent')
876 resp = h.getresponse()
877 self.assertEqual(resp.status, 404)
878
879 def test_local_bad_hostname(self):
880 # The (valid) cert doesn't validate the HTTP hostname
881 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700882 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000883 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
884 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -0500885 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000886 context.load_verify_locations(CERT_fakehostname)
887 h = client.HTTPSConnection('localhost', server.port, context=context)
888 with self.assertRaises(ssl.CertificateError):
889 h.request('GET', '/')
890 # Same with explicit check_hostname=True
891 h = client.HTTPSConnection('localhost', server.port, context=context,
892 check_hostname=True)
893 with self.assertRaises(ssl.CertificateError):
894 h.request('GET', '/')
895 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -0500896 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000897 h = client.HTTPSConnection('localhost', server.port, context=context,
898 check_hostname=False)
899 h.request('GET', '/nonexistent')
900 resp = h.getresponse()
901 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -0500902 # The context's check_hostname setting is used if one isn't passed to
903 # HTTPSConnection.
904 context.check_hostname = False
905 h = client.HTTPSConnection('localhost', server.port, context=context)
906 h.request('GET', '/nonexistent')
907 self.assertEqual(h.getresponse().status, 404)
908 # Passing check_hostname to HTTPSConnection should override the
909 # context's setting.
910 h = client.HTTPSConnection('localhost', server.port, context=context,
911 check_hostname=True)
912 with self.assertRaises(ssl.CertificateError):
913 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000914
Petri Lehtinene119c402011-10-26 21:29:15 +0300915 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
916 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200917 def test_host_port(self):
918 # Check invalid host_port
919
920 for hp in ("www.python.org:abc", "user:password@www.python.org"):
921 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
922
923 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
924 "fe80::207:e9ff:fe9b", 8000),
925 ("www.python.org:443", "www.python.org", 443),
926 ("www.python.org:", "www.python.org", 443),
927 ("www.python.org", "www.python.org", 443),
928 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
929 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
930 443)):
931 c = client.HTTPSConnection(hp)
932 self.assertEqual(h, c.host)
933 self.assertEqual(p, c.port)
934
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000935
Jeremy Hylton236654b2009-03-27 20:24:34 +0000936class RequestBodyTest(TestCase):
937 """Test cases where a request includes a message body."""
938
939 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000940 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000941 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000942 self.conn.sock = self.sock
943
944 def get_headers_and_fp(self):
945 f = io.BytesIO(self.sock.data)
946 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000947 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000948 return message, f
949
950 def test_manual_content_length(self):
951 # Set an incorrect content-length so that we can verify that
952 # it will not be over-ridden by the library.
953 self.conn.request("PUT", "/url", "body",
954 {"Content-Length": "42"})
955 message, f = self.get_headers_and_fp()
956 self.assertEqual("42", message.get("content-length"))
957 self.assertEqual(4, len(f.read()))
958
959 def test_ascii_body(self):
960 self.conn.request("PUT", "/url", "body")
961 message, f = self.get_headers_and_fp()
962 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000963 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000964 self.assertEqual("4", message.get("content-length"))
965 self.assertEqual(b'body', f.read())
966
967 def test_latin1_body(self):
968 self.conn.request("PUT", "/url", "body\xc1")
969 message, f = self.get_headers_and_fp()
970 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000971 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000972 self.assertEqual("5", message.get("content-length"))
973 self.assertEqual(b'body\xc1', f.read())
974
975 def test_bytes_body(self):
976 self.conn.request("PUT", "/url", b"body\xc1")
977 message, f = self.get_headers_and_fp()
978 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000979 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000980 self.assertEqual("5", message.get("content-length"))
981 self.assertEqual(b'body\xc1', f.read())
982
983 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200984 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000985 with open(support.TESTFN, "w") as f:
986 f.write("body")
987 with open(support.TESTFN) as f:
988 self.conn.request("PUT", "/url", f)
989 message, f = self.get_headers_and_fp()
990 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000991 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000992 self.assertEqual("4", message.get("content-length"))
993 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000994
995 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200996 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000997 with open(support.TESTFN, "wb") as f:
998 f.write(b"body\xc1")
999 with open(support.TESTFN, "rb") as f:
1000 self.conn.request("PUT", "/url", f)
1001 message, f = self.get_headers_and_fp()
1002 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001003 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001004 self.assertEqual("5", message.get("content-length"))
1005 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001006
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001007
1008class HTTPResponseTest(TestCase):
1009
1010 def setUp(self):
1011 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1012 second-value\r\n\r\nText"
1013 sock = FakeSocket(body)
1014 self.resp = client.HTTPResponse(sock)
1015 self.resp.begin()
1016
1017 def test_getting_header(self):
1018 header = self.resp.getheader('My-Header')
1019 self.assertEqual(header, 'first-value, second-value')
1020
1021 header = self.resp.getheader('My-Header', 'some default')
1022 self.assertEqual(header, 'first-value, second-value')
1023
1024 def test_getting_nonexistent_header_with_string_default(self):
1025 header = self.resp.getheader('No-Such-Header', 'default-value')
1026 self.assertEqual(header, 'default-value')
1027
1028 def test_getting_nonexistent_header_with_iterable_default(self):
1029 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1030 self.assertEqual(header, 'default, values')
1031
1032 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1033 self.assertEqual(header, 'default, values')
1034
1035 def test_getting_nonexistent_header_without_default(self):
1036 header = self.resp.getheader('No-Such-Header')
1037 self.assertEqual(header, None)
1038
1039 def test_getting_header_defaultint(self):
1040 header = self.resp.getheader('No-Such-Header',default=42)
1041 self.assertEqual(header, 42)
1042
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001043class TunnelTests(TestCase):
1044
1045 def test_connect(self):
1046 response_text = (
1047 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1048 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1049 'Content-Length: 42\r\n\r\n'
1050 )
1051
1052 def create_connection(address, timeout=None, source_address=None):
1053 return FakeSocket(response_text, host=address[0],
1054 port=address[1])
1055
1056 conn = client.HTTPConnection('proxy.com')
1057 conn._create_connection = create_connection
1058
1059 # Once connected, we shouldn't be able to tunnel anymore
1060 conn.connect()
1061 self.assertRaises(RuntimeError, conn.set_tunnel,
1062 'destination.com')
1063
1064 # But if we close the connection, we're good
1065 conn.close()
1066 conn.set_tunnel('destination.com')
1067 conn.request('HEAD', '/', '')
1068
1069 self.assertEqual(conn.sock.host, 'proxy.com')
1070 self.assertEqual(conn.sock.port, 80)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001071 self.assertIn(b'CONNECT destination.com', conn.sock.data)
1072 # issue22095
1073 self.assertNotIn(b'Host: destination.com:None', conn.sock.data)
1074 self.assertIn(b'Host: destination.com', conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001075
1076 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001077 self.assertNotIn(b'Host: proxy.com', conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001078
1079 conn.close()
1080 conn.request('PUT', '/', '')
1081 self.assertEqual(conn.sock.host, 'proxy.com')
1082 self.assertEqual(conn.sock.port, 80)
1083 self.assertTrue(b'CONNECT destination.com' in conn.sock.data)
1084 self.assertTrue(b'Host: destination.com' in conn.sock.data)
1085
Benjamin Peterson9566de12014-12-13 16:13:24 -05001086@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001087def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001088 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001089 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001090 HTTPResponseTest, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001091
Thomas Wouters89f507f2006-12-13 04:49:30 +00001092if __name__ == '__main__':
1093 test_main()