blob: 3fc34665da4047b9e46b5d50762e2cdc8c41e144 [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
Benjamin Peterson155ceaa2015-01-25 23:30:30 -0500170 def test_malformed_headers_coped_with(self):
171 # Issue 19996
172 body = "HTTP/1.1 200 OK\r\nFirst: val\r\n: nval\r\nSecond: val\r\n\r\n"
173 sock = FakeSocket(body)
174 resp = client.HTTPResponse(sock)
175 resp.begin()
176
177 self.assertEqual(resp.getheader('First'), 'val')
178 self.assertEqual(resp.getheader('Second'), 'val')
179
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000180
Thomas Wouters89f507f2006-12-13 04:49:30 +0000181class BasicTest(TestCase):
182 def test_status_lines(self):
183 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000184
Thomas Wouters89f507f2006-12-13 04:49:30 +0000185 body = "HTTP/1.1 200 Ok\r\n\r\nText"
186 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000187 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000188 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200189 self.assertEqual(resp.read(0), b'') # Issue #20007
190 self.assertFalse(resp.isclosed())
191 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000192 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000193 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200194 self.assertFalse(resp.closed)
195 resp.close()
196 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000197
Thomas Wouters89f507f2006-12-13 04:49:30 +0000198 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
199 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000200 resp = client.HTTPResponse(sock)
201 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000202
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000203 def test_bad_status_repr(self):
204 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000205 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000206
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000207 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100208 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000209 # same behaviour than when we read the whole thing with read()
210 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
211 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000212 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000213 resp.begin()
214 self.assertEqual(resp.read(2), b'Te')
215 self.assertFalse(resp.isclosed())
216 self.assertEqual(resp.read(2), b'xt')
217 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200218 self.assertFalse(resp.closed)
219 resp.close()
220 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000221
Antoine Pitrou38d96432011-12-06 22:33:57 +0100222 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100223 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100224 # same behaviour than when we read the whole thing with read()
225 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
226 sock = FakeSocket(body)
227 resp = client.HTTPResponse(sock)
228 resp.begin()
229 b = bytearray(2)
230 n = resp.readinto(b)
231 self.assertEqual(n, 2)
232 self.assertEqual(bytes(b), b'Te')
233 self.assertFalse(resp.isclosed())
234 n = resp.readinto(b)
235 self.assertEqual(n, 2)
236 self.assertEqual(bytes(b), b'xt')
237 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200238 self.assertFalse(resp.closed)
239 resp.close()
240 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100241
Antoine Pitrou084daa22012-12-15 19:11:54 +0100242 def test_partial_reads_no_content_length(self):
243 # when no length is present, the socket should be gracefully closed when
244 # all data was read
245 body = "HTTP/1.1 200 Ok\r\n\r\nText"
246 sock = FakeSocket(body)
247 resp = client.HTTPResponse(sock)
248 resp.begin()
249 self.assertEqual(resp.read(2), b'Te')
250 self.assertFalse(resp.isclosed())
251 self.assertEqual(resp.read(2), b'xt')
252 self.assertEqual(resp.read(1), b'')
253 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200254 self.assertFalse(resp.closed)
255 resp.close()
256 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100257
Antoine Pitroud20e7742012-12-15 19:22:30 +0100258 def test_partial_readintos_no_content_length(self):
259 # when no length is present, the socket should be gracefully closed when
260 # all data was read
261 body = "HTTP/1.1 200 Ok\r\n\r\nText"
262 sock = FakeSocket(body)
263 resp = client.HTTPResponse(sock)
264 resp.begin()
265 b = bytearray(2)
266 n = resp.readinto(b)
267 self.assertEqual(n, 2)
268 self.assertEqual(bytes(b), b'Te')
269 self.assertFalse(resp.isclosed())
270 n = resp.readinto(b)
271 self.assertEqual(n, 2)
272 self.assertEqual(bytes(b), b'xt')
273 n = resp.readinto(b)
274 self.assertEqual(n, 0)
275 self.assertTrue(resp.isclosed())
276
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100277 def test_partial_reads_incomplete_body(self):
278 # if the server shuts down the connection before the whole
279 # content-length is delivered, the socket is gracefully closed
280 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
281 sock = FakeSocket(body)
282 resp = client.HTTPResponse(sock)
283 resp.begin()
284 self.assertEqual(resp.read(2), b'Te')
285 self.assertFalse(resp.isclosed())
286 self.assertEqual(resp.read(2), b'xt')
287 self.assertEqual(resp.read(1), b'')
288 self.assertTrue(resp.isclosed())
289
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100290 def test_partial_readintos_incomplete_body(self):
291 # if the server shuts down the connection before the whole
292 # content-length is delivered, the socket is gracefully closed
293 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
294 sock = FakeSocket(body)
295 resp = client.HTTPResponse(sock)
296 resp.begin()
297 b = bytearray(2)
298 n = resp.readinto(b)
299 self.assertEqual(n, 2)
300 self.assertEqual(bytes(b), b'Te')
301 self.assertFalse(resp.isclosed())
302 n = resp.readinto(b)
303 self.assertEqual(n, 2)
304 self.assertEqual(bytes(b), b'xt')
305 n = resp.readinto(b)
306 self.assertEqual(n, 0)
307 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200308 self.assertFalse(resp.closed)
309 resp.close()
310 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100311
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 def test_host_port(self):
313 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000314
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200315 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000316 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000317
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000318 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
319 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000320 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200321 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200323 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
324 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000325 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000326 self.assertEqual(h, c.host)
327 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000328
Thomas Wouters89f507f2006-12-13 04:49:30 +0000329 def test_response_headers(self):
330 # test response with multiple message headers with the same field name.
331 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000332 'Set-Cookie: Customer="WILE_E_COYOTE"; '
333 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000334 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
335 ' Path="/acme"\r\n'
336 '\r\n'
337 'No body\r\n')
338 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
339 ', '
340 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
341 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000342 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000343 r.begin()
344 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000345 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000346
Thomas Wouters89f507f2006-12-13 04:49:30 +0000347 def test_read_head(self):
348 # Test that the library doesn't attempt to read any data
349 # from a HEAD request. (Tickles SF bug #622042.)
350 sock = FakeSocket(
351 'HTTP/1.1 200 OK\r\n'
352 'Content-Length: 14432\r\n'
353 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300354 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000355 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000356 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000357 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000358 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000359
Antoine Pitrou38d96432011-12-06 22:33:57 +0100360 def test_readinto_head(self):
361 # Test that the library doesn't attempt to read any data
362 # from a HEAD request. (Tickles SF bug #622042.)
363 sock = FakeSocket(
364 'HTTP/1.1 200 OK\r\n'
365 'Content-Length: 14432\r\n'
366 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300367 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100368 resp = client.HTTPResponse(sock, method="HEAD")
369 resp.begin()
370 b = bytearray(5)
371 if resp.readinto(b) != 0:
372 self.fail("Did not expect response from HEAD request")
373 self.assertEqual(bytes(b), b'\x00'*5)
374
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100375 def test_too_many_headers(self):
376 headers = '\r\n'.join('Header%d: foo' % i
377 for i in range(client._MAXHEADERS + 1)) + '\r\n'
378 text = ('HTTP/1.1 200 OK\r\n' + headers)
379 s = FakeSocket(text)
380 r = client.HTTPResponse(s)
381 self.assertRaisesRegex(client.HTTPException,
382 r"got more than \d+ headers", r.begin)
383
Thomas Wouters89f507f2006-12-13 04:49:30 +0000384 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000385 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
386 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000387
Brett Cannon77b7de62010-10-29 23:31:11 +0000388 with open(__file__, 'rb') as body:
389 conn = client.HTTPConnection('example.com')
390 sock = FakeSocket(body)
391 conn.sock = sock
392 conn.request('GET', '/foo', body)
393 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
394 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000395
Antoine Pitrouead1d622009-09-29 18:44:53 +0000396 def test_send(self):
397 expected = b'this is a test this is only a test'
398 conn = client.HTTPConnection('example.com')
399 sock = FakeSocket(None)
400 conn.sock = sock
401 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000402 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000403 sock.data = b''
404 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000405 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000406 sock.data = b''
407 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000408 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000409
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300410 def test_send_updating_file(self):
411 def data():
412 yield 'data'
413 yield None
414 yield 'data_two'
415
416 class UpdatingFile():
417 mode = 'r'
418 d = data()
419 def read(self, blocksize=-1):
420 return self.d.__next__()
421
422 expected = b'data'
423
424 conn = client.HTTPConnection('example.com')
425 sock = FakeSocket("")
426 conn.sock = sock
427 conn.send(UpdatingFile())
428 self.assertEqual(sock.data, expected)
429
430
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000431 def test_send_iter(self):
432 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
433 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
434 b'\r\nonetwothree'
435
436 def body():
437 yield b"one"
438 yield b"two"
439 yield b"three"
440
441 conn = client.HTTPConnection('example.com')
442 sock = FakeSocket("")
443 conn.sock = sock
444 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000445 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000446
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800447 def test_send_type_error(self):
448 # See: Issue #12676
449 conn = client.HTTPConnection('example.com')
450 conn.sock = FakeSocket('')
451 with self.assertRaises(TypeError):
452 conn.request('POST', 'test', conn)
453
Christian Heimesa612dc02008-02-24 13:08:18 +0000454 def test_chunked(self):
455 chunked_start = (
456 'HTTP/1.1 200 OK\r\n'
457 'Transfer-Encoding: chunked\r\n\r\n'
458 'a\r\n'
459 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100460 '3\r\n'
461 'd! \r\n'
462 '8\r\n'
463 'and now \r\n'
464 '22\r\n'
465 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000466 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100467 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000468 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000469 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000470 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100471 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000472 resp.close()
473
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100474 # Various read sizes
475 for n in range(1, 12):
476 sock = FakeSocket(chunked_start + '0\r\n')
477 resp = client.HTTPResponse(sock, method="GET")
478 resp.begin()
479 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
480 resp.close()
481
Christian Heimesa612dc02008-02-24 13:08:18 +0000482 for x in ('', 'foo\r\n'):
483 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000484 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000485 resp.begin()
486 try:
487 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000488 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100489 self.assertEqual(i.partial, expected)
490 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
491 self.assertEqual(repr(i), expected_message)
492 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000493 else:
494 self.fail('IncompleteRead expected')
495 finally:
496 resp.close()
497
Antoine Pitrou38d96432011-12-06 22:33:57 +0100498 def test_readinto_chunked(self):
499 chunked_start = (
500 'HTTP/1.1 200 OK\r\n'
501 'Transfer-Encoding: chunked\r\n\r\n'
502 'a\r\n'
503 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100504 '3\r\n'
505 'd! \r\n'
506 '8\r\n'
507 'and now \r\n'
508 '22\r\n'
509 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100510 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100511 expected = b'hello world! and now for something completely different'
512 nexpected = len(expected)
513 b = bytearray(128)
514
Antoine Pitrou38d96432011-12-06 22:33:57 +0100515 sock = FakeSocket(chunked_start + '0\r\n')
516 resp = client.HTTPResponse(sock, method="GET")
517 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100518 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100519 self.assertEqual(b[:nexpected], expected)
520 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100521 resp.close()
522
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100523 # Various read sizes
524 for n in range(1, 12):
525 sock = FakeSocket(chunked_start + '0\r\n')
526 resp = client.HTTPResponse(sock, method="GET")
527 resp.begin()
528 m = memoryview(b)
529 i = resp.readinto(m[0:n])
530 i += resp.readinto(m[i:n + i])
531 i += resp.readinto(m[i:])
532 self.assertEqual(b[:nexpected], expected)
533 self.assertEqual(i, nexpected)
534 resp.close()
535
Antoine Pitrou38d96432011-12-06 22:33:57 +0100536 for x in ('', 'foo\r\n'):
537 sock = FakeSocket(chunked_start + x)
538 resp = client.HTTPResponse(sock, method="GET")
539 resp.begin()
540 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100541 n = resp.readinto(b)
542 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100543 self.assertEqual(i.partial, expected)
544 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
545 self.assertEqual(repr(i), expected_message)
546 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100547 else:
548 self.fail('IncompleteRead expected')
549 finally:
550 resp.close()
551
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000552 def test_chunked_head(self):
553 chunked_start = (
554 'HTTP/1.1 200 OK\r\n'
555 'Transfer-Encoding: chunked\r\n\r\n'
556 'a\r\n'
557 'hello world\r\n'
558 '1\r\n'
559 'd\r\n'
560 )
561 sock = FakeSocket(chunked_start + '0\r\n')
562 resp = client.HTTPResponse(sock, method="HEAD")
563 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000564 self.assertEqual(resp.read(), b'')
565 self.assertEqual(resp.status, 200)
566 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000567 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200568 self.assertFalse(resp.closed)
569 resp.close()
570 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000571
Antoine Pitrou38d96432011-12-06 22:33:57 +0100572 def test_readinto_chunked_head(self):
573 chunked_start = (
574 'HTTP/1.1 200 OK\r\n'
575 'Transfer-Encoding: chunked\r\n\r\n'
576 'a\r\n'
577 'hello world\r\n'
578 '1\r\n'
579 'd\r\n'
580 )
581 sock = FakeSocket(chunked_start + '0\r\n')
582 resp = client.HTTPResponse(sock, method="HEAD")
583 resp.begin()
584 b = bytearray(5)
585 n = resp.readinto(b)
586 self.assertEqual(n, 0)
587 self.assertEqual(bytes(b), b'\x00'*5)
588 self.assertEqual(resp.status, 200)
589 self.assertEqual(resp.reason, 'OK')
590 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200591 self.assertFalse(resp.closed)
592 resp.close()
593 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100594
Christian Heimesa612dc02008-02-24 13:08:18 +0000595 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000596 sock = FakeSocket(
597 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000598 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000599 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000600 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100601 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000602
Benjamin Peterson6accb982009-03-02 22:50:25 +0000603 def test_incomplete_read(self):
604 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000605 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000606 resp.begin()
607 try:
608 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000609 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000610 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000611 self.assertEqual(repr(i),
612 "IncompleteRead(7 bytes read, 3 more expected)")
613 self.assertEqual(str(i),
614 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100615 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000616 else:
617 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000618
Jeremy Hylton636950f2009-03-28 04:34:21 +0000619 def test_epipe(self):
620 sock = EPipeSocket(
621 "HTTP/1.0 401 Authorization Required\r\n"
622 "Content-type: text/html\r\n"
623 "WWW-Authenticate: Basic realm=\"example\"\r\n",
624 b"Content-Length")
625 conn = client.HTTPConnection("example.com")
626 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200627 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000628 lambda: conn.request("PUT", "/url", "body"))
629 resp = conn.getresponse()
630 self.assertEqual(401, resp.status)
631 self.assertEqual("Basic realm=\"example\"",
632 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000633
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000634 # Test lines overflowing the max line size (_MAXLINE in http.client)
635
636 def test_overflowing_status_line(self):
637 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
638 resp = client.HTTPResponse(FakeSocket(body))
639 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
640
641 def test_overflowing_header_line(self):
642 body = (
643 'HTTP/1.1 200 OK\r\n'
644 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
645 )
646 resp = client.HTTPResponse(FakeSocket(body))
647 self.assertRaises(client.LineTooLong, resp.begin)
648
649 def test_overflowing_chunked_line(self):
650 body = (
651 'HTTP/1.1 200 OK\r\n'
652 'Transfer-Encoding: chunked\r\n\r\n'
653 + '0' * 65536 + 'a\r\n'
654 'hello world\r\n'
655 '0\r\n'
656 )
657 resp = client.HTTPResponse(FakeSocket(body))
658 resp.begin()
659 self.assertRaises(client.LineTooLong, resp.read)
660
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800661 def test_early_eof(self):
662 # Test httpresponse with no \r\n termination,
663 body = "HTTP/1.1 200 Ok"
664 sock = FakeSocket(body)
665 resp = client.HTTPResponse(sock)
666 resp.begin()
667 self.assertEqual(resp.read(), b'')
668 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200669 self.assertFalse(resp.closed)
670 resp.close()
671 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800672
Antoine Pitrou90e47742013-01-02 22:10:47 +0100673 def test_delayed_ack_opt(self):
674 # Test that Nagle/delayed_ack optimistaion works correctly.
675
676 # For small payloads, it should coalesce the body with
677 # headers, resulting in a single sendall() call
678 conn = client.HTTPConnection('example.com')
679 sock = FakeSocket(None)
680 conn.sock = sock
681 body = b'x' * (conn.mss - 1)
682 conn.request('POST', '/', body)
683 self.assertEqual(sock.sendall_calls, 1)
684
685 # For large payloads, it should send the headers and
686 # then the body, resulting in more than one sendall()
687 # call
688 conn = client.HTTPConnection('example.com')
689 sock = FakeSocket(None)
690 conn.sock = sock
691 body = b'x' * conn.mss
692 conn.request('POST', '/', body)
693 self.assertGreater(sock.sendall_calls, 1)
694
Serhiy Storchakab491e052014-12-01 13:07:45 +0200695 def test_error_leak(self):
696 # Test that the socket is not leaked if getresponse() fails
697 conn = client.HTTPConnection('example.com')
698 response = None
699 class Response(client.HTTPResponse):
700 def __init__(self, *pos, **kw):
701 nonlocal response
702 response = self # Avoid garbage collector closing the socket
703 client.HTTPResponse.__init__(self, *pos, **kw)
704 conn.response_class = Response
705 conn.sock = FakeSocket('') # Emulate server dropping connection
706 conn.request('GET', '/')
707 self.assertRaises(client.BadStatusLine, conn.getresponse)
708 self.assertTrue(response.closed)
709 self.assertTrue(conn.sock.file_closed)
710
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000711class OfflineTest(TestCase):
712 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000713 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000714
Gregory P. Smithb4066372010-01-03 03:28:29 +0000715
716class SourceAddressTest(TestCase):
717 def setUp(self):
718 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
719 self.port = support.bind_port(self.serv)
720 self.source_port = support.find_unused_port()
721 self.serv.listen(5)
722 self.conn = None
723
724 def tearDown(self):
725 if self.conn:
726 self.conn.close()
727 self.conn = None
728 self.serv.close()
729 self.serv = None
730
731 def testHTTPConnectionSourceAddress(self):
732 self.conn = client.HTTPConnection(HOST, self.port,
733 source_address=('', self.source_port))
734 self.conn.connect()
735 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
736
737 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
738 'http.client.HTTPSConnection not defined')
739 def testHTTPSConnectionSourceAddress(self):
740 self.conn = client.HTTPSConnection(HOST, self.port,
741 source_address=('', self.source_port))
742 # We don't test anything here other the constructor not barfing as
743 # this code doesn't deal with setting up an active running SSL server
744 # for an ssl_wrapped connect() to actually return from.
745
746
Guido van Rossumd8faa362007-04-27 19:54:29 +0000747class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000748 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000749
750 def setUp(self):
751 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000752 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000753 self.serv.listen(5)
754
755 def tearDown(self):
756 self.serv.close()
757 self.serv = None
758
759 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000760 # This will prove that the timeout gets through HTTPConnection
761 # and into the socket.
762
Georg Brandlf78e02b2008-06-10 17:40:04 +0000763 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200764 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000765 socket.setdefaulttimeout(30)
766 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000767 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000768 httpConn.connect()
769 finally:
770 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000771 self.assertEqual(httpConn.sock.gettimeout(), 30)
772 httpConn.close()
773
Georg Brandlf78e02b2008-06-10 17:40:04 +0000774 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200775 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000776 socket.setdefaulttimeout(30)
777 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000778 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000779 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000780 httpConn.connect()
781 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000782 socket.setdefaulttimeout(None)
783 self.assertEqual(httpConn.sock.gettimeout(), None)
784 httpConn.close()
785
786 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000787 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000788 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000789 self.assertEqual(httpConn.sock.gettimeout(), 30)
790 httpConn.close()
791
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000792
793class HTTPSTest(TestCase):
794
795 def setUp(self):
796 if not hasattr(client, 'HTTPSConnection'):
797 self.skipTest('ssl support required')
798
799 def make_server(self, certfile):
800 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100801 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000802
803 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000804 # simple test to check it's storing the timeout
805 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
806 self.assertEqual(h.timeout, 30)
807
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000808 def test_networked(self):
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500809 # Default settings: requires a valid cert from a trusted CA
810 import ssl
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000811 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500812 with support.transient_internet('self-signed.pythontest.net'):
813 h = client.HTTPSConnection('self-signed.pythontest.net', 443)
814 with self.assertRaises(ssl.SSLError) as exc_info:
815 h.request('GET', '/')
816 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
817
818 def test_networked_noverification(self):
819 # Switch off cert verification
820 import ssl
821 support.requires('network')
822 with support.transient_internet('self-signed.pythontest.net'):
823 context = ssl._create_unverified_context()
824 h = client.HTTPSConnection('self-signed.pythontest.net', 443,
825 context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000826 h.request('GET', '/')
827 resp = h.getresponse()
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500828 self.assertIn('nginx', resp.getheader('server'))
829
Benjamin Peterson2615e9e2014-11-25 15:16:55 -0600830 @support.system_must_validate_cert
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500831 def test_networked_trusted_by_default_cert(self):
832 # Default settings: requires a valid cert from a trusted CA
833 support.requires('network')
834 with support.transient_internet('www.python.org'):
835 h = client.HTTPSConnection('www.python.org', 443)
836 h.request('GET', '/')
837 resp = h.getresponse()
838 content_type = resp.getheader('content-type')
839 self.assertIn('text/html', content_type)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000840
841 def test_networked_good_cert(self):
Georg Brandlfbaf9312014-11-05 20:37:40 +0100842 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000843 import ssl
844 support.requires('network')
Georg Brandlfbaf9312014-11-05 20:37:40 +0100845 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000846 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
847 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandlfbaf9312014-11-05 20:37:40 +0100848 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
849 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000850 h.request('GET', '/')
851 resp = h.getresponse()
Georg Brandlfbaf9312014-11-05 20:37:40 +0100852 server_string = resp.getheader('server')
853 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000854
855 def test_networked_bad_cert(self):
856 # We feed a "CA" cert that is unrelated to the server's cert
857 import ssl
858 support.requires('network')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500859 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000860 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
861 context.verify_mode = ssl.CERT_REQUIRED
862 context.load_verify_locations(CERT_localhost)
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500863 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
864 with self.assertRaises(ssl.SSLError) as exc_info:
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000865 h.request('GET', '/')
Benjamin Peterson4ffb0752014-11-03 14:29:33 -0500866 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
867
868 def test_local_unknown_cert(self):
869 # The custom cert isn't known to the default trust bundle
870 import ssl
871 server = self.make_server(CERT_localhost)
872 h = client.HTTPSConnection('localhost', server.port)
873 with self.assertRaises(ssl.SSLError) as exc_info:
874 h.request('GET', '/')
875 self.assertEqual(exc_info.exception.reason, 'CERTIFICATE_VERIFY_FAILED')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000876
877 def test_local_good_hostname(self):
878 # The (valid) cert validates the HTTP hostname
879 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700880 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000881 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
882 context.verify_mode = ssl.CERT_REQUIRED
883 context.load_verify_locations(CERT_localhost)
884 h = client.HTTPSConnection('localhost', server.port, context=context)
885 h.request('GET', '/nonexistent')
886 resp = h.getresponse()
887 self.assertEqual(resp.status, 404)
888
889 def test_local_bad_hostname(self):
890 # The (valid) cert doesn't validate the HTTP hostname
891 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700892 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000893 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
894 context.verify_mode = ssl.CERT_REQUIRED
Benjamin Petersona090f012014-12-07 13:18:25 -0500895 context.check_hostname = True
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000896 context.load_verify_locations(CERT_fakehostname)
897 h = client.HTTPSConnection('localhost', server.port, context=context)
898 with self.assertRaises(ssl.CertificateError):
899 h.request('GET', '/')
900 # Same with explicit check_hostname=True
901 h = client.HTTPSConnection('localhost', server.port, context=context,
902 check_hostname=True)
903 with self.assertRaises(ssl.CertificateError):
904 h.request('GET', '/')
905 # With check_hostname=False, the mismatching is ignored
Benjamin Petersona090f012014-12-07 13:18:25 -0500906 context.check_hostname = False
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000907 h = client.HTTPSConnection('localhost', server.port, context=context,
908 check_hostname=False)
909 h.request('GET', '/nonexistent')
910 resp = h.getresponse()
911 self.assertEqual(resp.status, 404)
Benjamin Petersona090f012014-12-07 13:18:25 -0500912 # The context's check_hostname setting is used if one isn't passed to
913 # HTTPSConnection.
914 context.check_hostname = False
915 h = client.HTTPSConnection('localhost', server.port, context=context)
916 h.request('GET', '/nonexistent')
917 self.assertEqual(h.getresponse().status, 404)
918 # Passing check_hostname to HTTPSConnection should override the
919 # context's setting.
920 h = client.HTTPSConnection('localhost', server.port, context=context,
921 check_hostname=True)
922 with self.assertRaises(ssl.CertificateError):
923 h.request('GET', '/')
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000924
Petri Lehtinene119c402011-10-26 21:29:15 +0300925 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
926 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200927 def test_host_port(self):
928 # Check invalid host_port
929
930 for hp in ("www.python.org:abc", "user:password@www.python.org"):
931 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
932
933 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
934 "fe80::207:e9ff:fe9b", 8000),
935 ("www.python.org:443", "www.python.org", 443),
936 ("www.python.org:", "www.python.org", 443),
937 ("www.python.org", "www.python.org", 443),
938 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
939 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
940 443)):
941 c = client.HTTPSConnection(hp)
942 self.assertEqual(h, c.host)
943 self.assertEqual(p, c.port)
944
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000945
Jeremy Hylton236654b2009-03-27 20:24:34 +0000946class RequestBodyTest(TestCase):
947 """Test cases where a request includes a message body."""
948
949 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000950 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000951 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000952 self.conn.sock = self.sock
953
954 def get_headers_and_fp(self):
955 f = io.BytesIO(self.sock.data)
956 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000957 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000958 return message, f
959
960 def test_manual_content_length(self):
961 # Set an incorrect content-length so that we can verify that
962 # it will not be over-ridden by the library.
963 self.conn.request("PUT", "/url", "body",
964 {"Content-Length": "42"})
965 message, f = self.get_headers_and_fp()
966 self.assertEqual("42", message.get("content-length"))
967 self.assertEqual(4, len(f.read()))
968
969 def test_ascii_body(self):
970 self.conn.request("PUT", "/url", "body")
971 message, f = self.get_headers_and_fp()
972 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000973 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000974 self.assertEqual("4", message.get("content-length"))
975 self.assertEqual(b'body', f.read())
976
977 def test_latin1_body(self):
978 self.conn.request("PUT", "/url", "body\xc1")
979 message, f = self.get_headers_and_fp()
980 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000981 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000982 self.assertEqual("5", message.get("content-length"))
983 self.assertEqual(b'body\xc1', f.read())
984
985 def test_bytes_body(self):
986 self.conn.request("PUT", "/url", b"body\xc1")
987 message, f = self.get_headers_and_fp()
988 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000989 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000990 self.assertEqual("5", message.get("content-length"))
991 self.assertEqual(b'body\xc1', f.read())
992
993 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200994 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000995 with open(support.TESTFN, "w") as f:
996 f.write("body")
997 with open(support.TESTFN) as f:
998 self.conn.request("PUT", "/url", f)
999 message, f = self.get_headers_and_fp()
1000 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001001 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001002 self.assertEqual("4", message.get("content-length"))
1003 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001004
1005 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +02001006 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +00001007 with open(support.TESTFN, "wb") as f:
1008 f.write(b"body\xc1")
1009 with open(support.TESTFN, "rb") as f:
1010 self.conn.request("PUT", "/url", f)
1011 message, f = self.get_headers_and_fp()
1012 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +00001013 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +00001014 self.assertEqual("5", message.get("content-length"))
1015 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +00001016
Senthil Kumaran9f8dc442010-08-02 11:04:58 +00001017
1018class HTTPResponseTest(TestCase):
1019
1020 def setUp(self):
1021 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
1022 second-value\r\n\r\nText"
1023 sock = FakeSocket(body)
1024 self.resp = client.HTTPResponse(sock)
1025 self.resp.begin()
1026
1027 def test_getting_header(self):
1028 header = self.resp.getheader('My-Header')
1029 self.assertEqual(header, 'first-value, second-value')
1030
1031 header = self.resp.getheader('My-Header', 'some default')
1032 self.assertEqual(header, 'first-value, second-value')
1033
1034 def test_getting_nonexistent_header_with_string_default(self):
1035 header = self.resp.getheader('No-Such-Header', 'default-value')
1036 self.assertEqual(header, 'default-value')
1037
1038 def test_getting_nonexistent_header_with_iterable_default(self):
1039 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
1040 self.assertEqual(header, 'default, values')
1041
1042 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
1043 self.assertEqual(header, 'default, values')
1044
1045 def test_getting_nonexistent_header_without_default(self):
1046 header = self.resp.getheader('No-Such-Header')
1047 self.assertEqual(header, None)
1048
1049 def test_getting_header_defaultint(self):
1050 header = self.resp.getheader('No-Such-Header',default=42)
1051 self.assertEqual(header, 42)
1052
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001053class TunnelTests(TestCase):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001054 def setUp(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001055 response_text = (
1056 'HTTP/1.0 200 OK\r\n\r\n' # Reply to CONNECT
1057 'HTTP/1.1 200 OK\r\n' # Reply to HEAD
1058 'Content-Length: 42\r\n\r\n'
1059 )
1060
1061 def create_connection(address, timeout=None, source_address=None):
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001062 return FakeSocket(response_text, host=address[0], port=address[1])
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001063
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001064 self.host = 'proxy.com'
1065 self.conn = client.HTTPConnection(self.host)
1066 self.conn._create_connection = create_connection
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001067
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001068 def tearDown(self):
1069 self.conn.close()
1070
1071 def test_set_tunnel_host_port_headers(self):
1072 tunnel_host = 'destination.com'
1073 tunnel_port = 8888
1074 tunnel_headers = {'User-Agent': 'Mozilla/5.0 (compatible, MSIE 11)'}
1075 self.conn.set_tunnel(tunnel_host, port=tunnel_port,
1076 headers=tunnel_headers)
1077 self.conn.request('HEAD', '/', '')
1078 self.assertEqual(self.conn.sock.host, self.host)
1079 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1080 self.assertEqual(self.conn._tunnel_host, tunnel_host)
1081 self.assertEqual(self.conn._tunnel_port, tunnel_port)
1082 self.assertEqual(self.conn._tunnel_headers, tunnel_headers)
1083
1084 def test_disallow_set_tunnel_after_connect(self):
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001085 # Once connected, we shouldn't be able to tunnel anymore
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001086 self.conn.connect()
1087 self.assertRaises(RuntimeError, self.conn.set_tunnel,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001088 'destination.com')
1089
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001090 def test_connect_with_tunnel(self):
1091 self.conn.set_tunnel('destination.com')
1092 self.conn.request('HEAD', '/', '')
1093 self.assertEqual(self.conn.sock.host, self.host)
1094 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1095 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
Serhiy Storchaka4ac7ed92014-12-12 09:29:15 +02001096 # issue22095
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001097 self.assertNotIn(b'Host: destination.com:None', self.conn.sock.data)
1098 self.assertIn(b'Host: destination.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001099
1100 # This test should be removed when CONNECT gets the HTTP/1.1 blessing
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001101 self.assertNotIn(b'Host: proxy.com', self.conn.sock.data)
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001102
Senthil Kumarane6cc7012015-01-24 19:24:59 -08001103 def test_connect_put_request(self):
1104 self.conn.set_tunnel('destination.com')
1105 self.conn.request('PUT', '/', '')
1106 self.assertEqual(self.conn.sock.host, self.host)
1107 self.assertEqual(self.conn.sock.port, client.HTTP_PORT)
1108 self.assertIn(b'CONNECT destination.com', self.conn.sock.data)
1109 self.assertIn(b'Host: destination.com', self.conn.sock.data)
1110
1111
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001112
Benjamin Peterson9566de12014-12-13 16:13:24 -05001113@support.reap_threads
Jeremy Hylton2c178252004-08-07 16:28:14 +00001114def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001115 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +00001116 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9da047b2014-04-14 13:07:56 -04001117 HTTPResponseTest, TunnelTests)
Jeremy Hylton2c178252004-08-07 16:28:14 +00001118
Thomas Wouters89f507f2006-12-13 04:49:30 +00001119if __name__ == '__main__':
1120 test_main()