blob: 30b6c0cfcbbe28b1ff432a8f1a04bd9cdf714eb9 [file] [log] [blame]
Jeremy Hylton636950f2009-03-28 04:34:21 +00001import errno
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002from http import client
Jeremy Hylton8fff7922007-08-03 20:56:14 +00003import io
Antoine Pitrou803e6d62010-10-13 10:36:15 +00004import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00005import array
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import socket
Jeremy Hylton121d34a2003-07-08 12:36:58 +00007
Gregory P. Smithb4066372010-01-03 03:28:29 +00008import unittest
9TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000010
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000012
Antoine Pitrou803e6d62010-10-13 10:36:15 +000013here = os.path.dirname(__file__)
14# Self-signed cert file for 'localhost'
15CERT_localhost = os.path.join(here, 'keycert.pem')
16# Self-signed cert file for 'fakehostname'
17CERT_fakehostname = os.path.join(here, 'keycert2.pem')
18# Root cert file (CA) for svn.python.org's cert
19CACERT_svn_python_org = os.path.join(here, 'https_svn_python_org_root.pem')
20
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000022
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000023class FakeSocket:
Jeremy Hylton8fff7922007-08-03 20:56:14 +000024 def __init__(self, text, fileclass=io.BytesIO):
25 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000026 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000027 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000028 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000029 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010030 self.sendall_calls = 0
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000031
Jeremy Hylton2c178252004-08-07 16:28:14 +000032 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010033 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000035
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000036 def makefile(self, mode, bufsize=None):
37 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000038 raise client.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000039 return self.fileclass(self.text)
40
Jeremy Hylton636950f2009-03-28 04:34:21 +000041class EPipeSocket(FakeSocket):
42
43 def __init__(self, text, pipe_trigger):
44 # When sendall() is called with pipe_trigger, raise EPIPE.
45 FakeSocket.__init__(self, text)
46 self.pipe_trigger = pipe_trigger
47
48 def sendall(self, data):
49 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020050 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000051 self.data += data
52
53 def close(self):
54 pass
55
Serhiy Storchaka50254c52013-08-29 11:35:43 +030056class NoEOFBytesIO(io.BytesIO):
57 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000058
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000059 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000060 more from the underlying file than it should.
61 """
62 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000063 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000064 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000065 raise AssertionError('caller tried to read past EOF')
66 return data
67
68 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000069 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000070 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000071 raise AssertionError('caller tried to read past EOF')
72 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000073
Jeremy Hylton2c178252004-08-07 16:28:14 +000074class HeaderTests(TestCase):
75 def test_auto_headers(self):
76 # Some headers are added automatically, but should not be added by
77 # .request() if they are explicitly set.
78
Jeremy Hylton2c178252004-08-07 16:28:14 +000079 class HeaderCountingBuffer(list):
80 def __init__(self):
81 self.count = {}
82 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000083 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000084 if len(kv) > 1:
85 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000086 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000087 self.count.setdefault(lcKey, 0)
88 self.count[lcKey] += 1
89 list.append(self, item)
90
91 for explicit_header in True, False:
92 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000093 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +000094 conn.sock = FakeSocket('blahblahblah')
95 conn._buffer = HeaderCountingBuffer()
96
97 body = 'spamspamspam'
98 headers = {}
99 if explicit_header:
100 headers[header] = str(len(body))
101 conn.request('POST', '/', body, headers)
102 self.assertEqual(conn._buffer.count[header.lower()], 1)
103
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800104 def test_content_length_0(self):
105
106 class ContentLengthChecker(list):
107 def __init__(self):
108 list.__init__(self)
109 self.content_length = None
110 def append(self, item):
111 kv = item.split(b':', 1)
112 if len(kv) > 1 and kv[0].lower() == b'content-length':
113 self.content_length = kv[1].strip()
114 list.append(self, item)
115
116 # POST with empty body
117 conn = client.HTTPConnection('example.com')
118 conn.sock = FakeSocket(None)
119 conn._buffer = ContentLengthChecker()
120 conn.request('POST', '/', '')
121 self.assertEqual(conn._buffer.content_length, b'0',
122 'Header Content-Length not set')
123
124 # PUT request with empty body
125 conn = client.HTTPConnection('example.com')
126 conn.sock = FakeSocket(None)
127 conn._buffer = ContentLengthChecker()
128 conn.request('PUT', '/', '')
129 self.assertEqual(conn._buffer.content_length, b'0',
130 'Header Content-Length not set')
131
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000132 def test_putheader(self):
133 conn = client.HTTPConnection('example.com')
134 conn.sock = FakeSocket(None)
135 conn.putrequest('GET','/')
136 conn.putheader('Content-length', 42)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200137 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000138
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000139 def test_ipv6host_header(self):
140 # Default host header on IPv6 transaction should wrapped by [] if
141 # its actual IPv6 address
142 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
143 b'Accept-Encoding: identity\r\n\r\n'
144 conn = client.HTTPConnection('[2001::]:81')
145 sock = FakeSocket('')
146 conn.sock = sock
147 conn.request('GET', '/foo')
148 self.assertTrue(sock.data.startswith(expected))
149
150 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
151 b'Accept-Encoding: identity\r\n\r\n'
152 conn = client.HTTPConnection('[2001:102A::]')
153 sock = FakeSocket('')
154 conn.sock = sock
155 conn.request('GET', '/foo')
156 self.assertTrue(sock.data.startswith(expected))
157
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000158
Thomas Wouters89f507f2006-12-13 04:49:30 +0000159class BasicTest(TestCase):
160 def test_status_lines(self):
161 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000162
Thomas Wouters89f507f2006-12-13 04:49:30 +0000163 body = "HTTP/1.1 200 Ok\r\n\r\nText"
164 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000165 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000166 resp.begin()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200167 self.assertEqual(resp.read(0), b'') # Issue #20007
168 self.assertFalse(resp.isclosed())
169 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000170 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000171 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200172 self.assertFalse(resp.closed)
173 resp.close()
174 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000175
Thomas Wouters89f507f2006-12-13 04:49:30 +0000176 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
177 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000178 resp = client.HTTPResponse(sock)
179 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000180
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000181 def test_bad_status_repr(self):
182 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000183 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000184
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000185 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100186 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000187 # same behaviour than when we read the whole thing with read()
188 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
189 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000190 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000191 resp.begin()
192 self.assertEqual(resp.read(2), b'Te')
193 self.assertFalse(resp.isclosed())
194 self.assertEqual(resp.read(2), b'xt')
195 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200196 self.assertFalse(resp.closed)
197 resp.close()
198 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000199
Antoine Pitrou38d96432011-12-06 22:33:57 +0100200 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100201 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100202 # same behaviour than when we read the whole thing with read()
203 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
204 sock = FakeSocket(body)
205 resp = client.HTTPResponse(sock)
206 resp.begin()
207 b = bytearray(2)
208 n = resp.readinto(b)
209 self.assertEqual(n, 2)
210 self.assertEqual(bytes(b), b'Te')
211 self.assertFalse(resp.isclosed())
212 n = resp.readinto(b)
213 self.assertEqual(n, 2)
214 self.assertEqual(bytes(b), b'xt')
215 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200216 self.assertFalse(resp.closed)
217 resp.close()
218 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100219
Antoine Pitrou084daa22012-12-15 19:11:54 +0100220 def test_partial_reads_no_content_length(self):
221 # when no length is present, the socket should be gracefully closed when
222 # all data was read
223 body = "HTTP/1.1 200 Ok\r\n\r\nText"
224 sock = FakeSocket(body)
225 resp = client.HTTPResponse(sock)
226 resp.begin()
227 self.assertEqual(resp.read(2), b'Te')
228 self.assertFalse(resp.isclosed())
229 self.assertEqual(resp.read(2), b'xt')
230 self.assertEqual(resp.read(1), b'')
231 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200232 self.assertFalse(resp.closed)
233 resp.close()
234 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100235
Antoine Pitroud20e7742012-12-15 19:22:30 +0100236 def test_partial_readintos_no_content_length(self):
237 # when no length is present, the socket should be gracefully closed when
238 # all data was read
239 body = "HTTP/1.1 200 Ok\r\n\r\nText"
240 sock = FakeSocket(body)
241 resp = client.HTTPResponse(sock)
242 resp.begin()
243 b = bytearray(2)
244 n = resp.readinto(b)
245 self.assertEqual(n, 2)
246 self.assertEqual(bytes(b), b'Te')
247 self.assertFalse(resp.isclosed())
248 n = resp.readinto(b)
249 self.assertEqual(n, 2)
250 self.assertEqual(bytes(b), b'xt')
251 n = resp.readinto(b)
252 self.assertEqual(n, 0)
253 self.assertTrue(resp.isclosed())
254
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100255 def test_partial_reads_incomplete_body(self):
256 # if the server shuts down the connection before the whole
257 # content-length is delivered, the socket is gracefully closed
258 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
259 sock = FakeSocket(body)
260 resp = client.HTTPResponse(sock)
261 resp.begin()
262 self.assertEqual(resp.read(2), b'Te')
263 self.assertFalse(resp.isclosed())
264 self.assertEqual(resp.read(2), b'xt')
265 self.assertEqual(resp.read(1), b'')
266 self.assertTrue(resp.isclosed())
267
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100268 def test_partial_readintos_incomplete_body(self):
269 # if the server shuts down the connection before the whole
270 # content-length is delivered, the socket is gracefully closed
271 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
272 sock = FakeSocket(body)
273 resp = client.HTTPResponse(sock)
274 resp.begin()
275 b = bytearray(2)
276 n = resp.readinto(b)
277 self.assertEqual(n, 2)
278 self.assertEqual(bytes(b), b'Te')
279 self.assertFalse(resp.isclosed())
280 n = resp.readinto(b)
281 self.assertEqual(n, 2)
282 self.assertEqual(bytes(b), b'xt')
283 n = resp.readinto(b)
284 self.assertEqual(n, 0)
285 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200286 self.assertFalse(resp.closed)
287 resp.close()
288 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100289
Thomas Wouters89f507f2006-12-13 04:49:30 +0000290 def test_host_port(self):
291 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000292
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200293 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000294 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000296 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
297 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000298 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200299 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000300 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200301 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
302 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000303 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000304 self.assertEqual(h, c.host)
305 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 def test_response_headers(self):
308 # test response with multiple message headers with the same field name.
309 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000310 'Set-Cookie: Customer="WILE_E_COYOTE"; '
311 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000312 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
313 ' Path="/acme"\r\n'
314 '\r\n'
315 'No body\r\n')
316 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
317 ', '
318 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
319 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000320 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 r.begin()
322 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000323 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000324
Thomas Wouters89f507f2006-12-13 04:49:30 +0000325 def test_read_head(self):
326 # Test that the library doesn't attempt to read any data
327 # from a HEAD request. (Tickles SF bug #622042.)
328 sock = FakeSocket(
329 'HTTP/1.1 200 OK\r\n'
330 'Content-Length: 14432\r\n'
331 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300332 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000333 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000334 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000335 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000336 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000337
Antoine Pitrou38d96432011-12-06 22:33:57 +0100338 def test_readinto_head(self):
339 # Test that the library doesn't attempt to read any data
340 # from a HEAD request. (Tickles SF bug #622042.)
341 sock = FakeSocket(
342 'HTTP/1.1 200 OK\r\n'
343 'Content-Length: 14432\r\n'
344 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300345 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100346 resp = client.HTTPResponse(sock, method="HEAD")
347 resp.begin()
348 b = bytearray(5)
349 if resp.readinto(b) != 0:
350 self.fail("Did not expect response from HEAD request")
351 self.assertEqual(bytes(b), b'\x00'*5)
352
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100353 def test_too_many_headers(self):
354 headers = '\r\n'.join('Header%d: foo' % i
355 for i in range(client._MAXHEADERS + 1)) + '\r\n'
356 text = ('HTTP/1.1 200 OK\r\n' + headers)
357 s = FakeSocket(text)
358 r = client.HTTPResponse(s)
359 self.assertRaisesRegex(client.HTTPException,
360 r"got more than \d+ headers", r.begin)
361
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000363 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
364 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000365
Brett Cannon77b7de62010-10-29 23:31:11 +0000366 with open(__file__, 'rb') as body:
367 conn = client.HTTPConnection('example.com')
368 sock = FakeSocket(body)
369 conn.sock = sock
370 conn.request('GET', '/foo', body)
371 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
372 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000373
Antoine Pitrouead1d622009-09-29 18:44:53 +0000374 def test_send(self):
375 expected = b'this is a test this is only a test'
376 conn = client.HTTPConnection('example.com')
377 sock = FakeSocket(None)
378 conn.sock = sock
379 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000380 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000381 sock.data = b''
382 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000383 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000384 sock.data = b''
385 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000386 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000387
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300388 def test_send_updating_file(self):
389 def data():
390 yield 'data'
391 yield None
392 yield 'data_two'
393
394 class UpdatingFile():
395 mode = 'r'
396 d = data()
397 def read(self, blocksize=-1):
398 return self.d.__next__()
399
400 expected = b'data'
401
402 conn = client.HTTPConnection('example.com')
403 sock = FakeSocket("")
404 conn.sock = sock
405 conn.send(UpdatingFile())
406 self.assertEqual(sock.data, expected)
407
408
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000409 def test_send_iter(self):
410 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
411 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
412 b'\r\nonetwothree'
413
414 def body():
415 yield b"one"
416 yield b"two"
417 yield b"three"
418
419 conn = client.HTTPConnection('example.com')
420 sock = FakeSocket("")
421 conn.sock = sock
422 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000423 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000424
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800425 def test_send_type_error(self):
426 # See: Issue #12676
427 conn = client.HTTPConnection('example.com')
428 conn.sock = FakeSocket('')
429 with self.assertRaises(TypeError):
430 conn.request('POST', 'test', conn)
431
Christian Heimesa612dc02008-02-24 13:08:18 +0000432 def test_chunked(self):
433 chunked_start = (
434 'HTTP/1.1 200 OK\r\n'
435 'Transfer-Encoding: chunked\r\n\r\n'
436 'a\r\n'
437 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100438 '3\r\n'
439 'd! \r\n'
440 '8\r\n'
441 'and now \r\n'
442 '22\r\n'
443 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000444 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100445 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000446 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000447 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000448 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100449 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000450 resp.close()
451
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100452 # Various read sizes
453 for n in range(1, 12):
454 sock = FakeSocket(chunked_start + '0\r\n')
455 resp = client.HTTPResponse(sock, method="GET")
456 resp.begin()
457 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
458 resp.close()
459
Christian Heimesa612dc02008-02-24 13:08:18 +0000460 for x in ('', 'foo\r\n'):
461 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000462 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000463 resp.begin()
464 try:
465 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000466 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100467 self.assertEqual(i.partial, expected)
468 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
469 self.assertEqual(repr(i), expected_message)
470 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000471 else:
472 self.fail('IncompleteRead expected')
473 finally:
474 resp.close()
475
Antoine Pitrou38d96432011-12-06 22:33:57 +0100476 def test_readinto_chunked(self):
477 chunked_start = (
478 'HTTP/1.1 200 OK\r\n'
479 'Transfer-Encoding: chunked\r\n\r\n'
480 'a\r\n'
481 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100482 '3\r\n'
483 'd! \r\n'
484 '8\r\n'
485 'and now \r\n'
486 '22\r\n'
487 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100488 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100489 expected = b'hello world! and now for something completely different'
490 nexpected = len(expected)
491 b = bytearray(128)
492
Antoine Pitrou38d96432011-12-06 22:33:57 +0100493 sock = FakeSocket(chunked_start + '0\r\n')
494 resp = client.HTTPResponse(sock, method="GET")
495 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100496 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100497 self.assertEqual(b[:nexpected], expected)
498 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100499 resp.close()
500
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100501 # Various read sizes
502 for n in range(1, 12):
503 sock = FakeSocket(chunked_start + '0\r\n')
504 resp = client.HTTPResponse(sock, method="GET")
505 resp.begin()
506 m = memoryview(b)
507 i = resp.readinto(m[0:n])
508 i += resp.readinto(m[i:n + i])
509 i += resp.readinto(m[i:])
510 self.assertEqual(b[:nexpected], expected)
511 self.assertEqual(i, nexpected)
512 resp.close()
513
Antoine Pitrou38d96432011-12-06 22:33:57 +0100514 for x in ('', 'foo\r\n'):
515 sock = FakeSocket(chunked_start + x)
516 resp = client.HTTPResponse(sock, method="GET")
517 resp.begin()
518 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100519 n = resp.readinto(b)
520 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100521 self.assertEqual(i.partial, expected)
522 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
523 self.assertEqual(repr(i), expected_message)
524 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100525 else:
526 self.fail('IncompleteRead expected')
527 finally:
528 resp.close()
529
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000530 def test_chunked_head(self):
531 chunked_start = (
532 'HTTP/1.1 200 OK\r\n'
533 'Transfer-Encoding: chunked\r\n\r\n'
534 'a\r\n'
535 'hello world\r\n'
536 '1\r\n'
537 'd\r\n'
538 )
539 sock = FakeSocket(chunked_start + '0\r\n')
540 resp = client.HTTPResponse(sock, method="HEAD")
541 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000542 self.assertEqual(resp.read(), b'')
543 self.assertEqual(resp.status, 200)
544 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000545 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200546 self.assertFalse(resp.closed)
547 resp.close()
548 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000549
Antoine Pitrou38d96432011-12-06 22:33:57 +0100550 def test_readinto_chunked_head(self):
551 chunked_start = (
552 'HTTP/1.1 200 OK\r\n'
553 'Transfer-Encoding: chunked\r\n\r\n'
554 'a\r\n'
555 'hello world\r\n'
556 '1\r\n'
557 'd\r\n'
558 )
559 sock = FakeSocket(chunked_start + '0\r\n')
560 resp = client.HTTPResponse(sock, method="HEAD")
561 resp.begin()
562 b = bytearray(5)
563 n = resp.readinto(b)
564 self.assertEqual(n, 0)
565 self.assertEqual(bytes(b), b'\x00'*5)
566 self.assertEqual(resp.status, 200)
567 self.assertEqual(resp.reason, 'OK')
568 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200569 self.assertFalse(resp.closed)
570 resp.close()
571 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100572
Christian Heimesa612dc02008-02-24 13:08:18 +0000573 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000574 sock = FakeSocket(
575 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000576 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000577 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000578 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100579 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000580
Benjamin Peterson6accb982009-03-02 22:50:25 +0000581 def test_incomplete_read(self):
582 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000583 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000584 resp.begin()
585 try:
586 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000587 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000588 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000589 self.assertEqual(repr(i),
590 "IncompleteRead(7 bytes read, 3 more expected)")
591 self.assertEqual(str(i),
592 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100593 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000594 else:
595 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000596
Jeremy Hylton636950f2009-03-28 04:34:21 +0000597 def test_epipe(self):
598 sock = EPipeSocket(
599 "HTTP/1.0 401 Authorization Required\r\n"
600 "Content-type: text/html\r\n"
601 "WWW-Authenticate: Basic realm=\"example\"\r\n",
602 b"Content-Length")
603 conn = client.HTTPConnection("example.com")
604 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200605 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000606 lambda: conn.request("PUT", "/url", "body"))
607 resp = conn.getresponse()
608 self.assertEqual(401, resp.status)
609 self.assertEqual("Basic realm=\"example\"",
610 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000611
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000612 # Test lines overflowing the max line size (_MAXLINE in http.client)
613
614 def test_overflowing_status_line(self):
615 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
616 resp = client.HTTPResponse(FakeSocket(body))
617 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
618
619 def test_overflowing_header_line(self):
620 body = (
621 'HTTP/1.1 200 OK\r\n'
622 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
623 )
624 resp = client.HTTPResponse(FakeSocket(body))
625 self.assertRaises(client.LineTooLong, resp.begin)
626
627 def test_overflowing_chunked_line(self):
628 body = (
629 'HTTP/1.1 200 OK\r\n'
630 'Transfer-Encoding: chunked\r\n\r\n'
631 + '0' * 65536 + 'a\r\n'
632 'hello world\r\n'
633 '0\r\n'
634 )
635 resp = client.HTTPResponse(FakeSocket(body))
636 resp.begin()
637 self.assertRaises(client.LineTooLong, resp.read)
638
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800639 def test_early_eof(self):
640 # Test httpresponse with no \r\n termination,
641 body = "HTTP/1.1 200 Ok"
642 sock = FakeSocket(body)
643 resp = client.HTTPResponse(sock)
644 resp.begin()
645 self.assertEqual(resp.read(), b'')
646 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200647 self.assertFalse(resp.closed)
648 resp.close()
649 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800650
Antoine Pitrou90e47742013-01-02 22:10:47 +0100651 def test_delayed_ack_opt(self):
652 # Test that Nagle/delayed_ack optimistaion works correctly.
653
654 # For small payloads, it should coalesce the body with
655 # headers, resulting in a single sendall() call
656 conn = client.HTTPConnection('example.com')
657 sock = FakeSocket(None)
658 conn.sock = sock
659 body = b'x' * (conn.mss - 1)
660 conn.request('POST', '/', body)
661 self.assertEqual(sock.sendall_calls, 1)
662
663 # For large payloads, it should send the headers and
664 # then the body, resulting in more than one sendall()
665 # call
666 conn = client.HTTPConnection('example.com')
667 sock = FakeSocket(None)
668 conn.sock = sock
669 body = b'x' * conn.mss
670 conn.request('POST', '/', body)
671 self.assertGreater(sock.sendall_calls, 1)
672
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000673class OfflineTest(TestCase):
674 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000675 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000676
Gregory P. Smithb4066372010-01-03 03:28:29 +0000677
678class SourceAddressTest(TestCase):
679 def setUp(self):
680 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
681 self.port = support.bind_port(self.serv)
682 self.source_port = support.find_unused_port()
683 self.serv.listen(5)
684 self.conn = None
685
686 def tearDown(self):
687 if self.conn:
688 self.conn.close()
689 self.conn = None
690 self.serv.close()
691 self.serv = None
692
693 def testHTTPConnectionSourceAddress(self):
694 self.conn = client.HTTPConnection(HOST, self.port,
695 source_address=('', self.source_port))
696 self.conn.connect()
697 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
698
699 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
700 'http.client.HTTPSConnection not defined')
701 def testHTTPSConnectionSourceAddress(self):
702 self.conn = client.HTTPSConnection(HOST, self.port,
703 source_address=('', self.source_port))
704 # We don't test anything here other the constructor not barfing as
705 # this code doesn't deal with setting up an active running SSL server
706 # for an ssl_wrapped connect() to actually return from.
707
708
Guido van Rossumd8faa362007-04-27 19:54:29 +0000709class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000710 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000711
712 def setUp(self):
713 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000714 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000715 self.serv.listen(5)
716
717 def tearDown(self):
718 self.serv.close()
719 self.serv = None
720
721 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000722 # This will prove that the timeout gets through HTTPConnection
723 # and into the socket.
724
Georg Brandlf78e02b2008-06-10 17:40:04 +0000725 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200726 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000727 socket.setdefaulttimeout(30)
728 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000729 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000730 httpConn.connect()
731 finally:
732 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000733 self.assertEqual(httpConn.sock.gettimeout(), 30)
734 httpConn.close()
735
Georg Brandlf78e02b2008-06-10 17:40:04 +0000736 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200737 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000738 socket.setdefaulttimeout(30)
739 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000740 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000741 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000742 httpConn.connect()
743 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000744 socket.setdefaulttimeout(None)
745 self.assertEqual(httpConn.sock.gettimeout(), None)
746 httpConn.close()
747
748 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000749 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000750 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000751 self.assertEqual(httpConn.sock.gettimeout(), 30)
752 httpConn.close()
753
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000754
755class HTTPSTest(TestCase):
756
757 def setUp(self):
758 if not hasattr(client, 'HTTPSConnection'):
759 self.skipTest('ssl support required')
760
761 def make_server(self, certfile):
762 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100763 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000764
765 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000766 # simple test to check it's storing the timeout
767 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
768 self.assertEqual(h.timeout, 30)
769
770 def _check_svn_python_org(self, resp):
771 # Just a simple check that everything went fine
772 server_string = resp.getheader('server')
773 self.assertIn('Apache', server_string)
774
775 def test_networked(self):
776 # Default settings: no cert verification is done
777 support.requires('network')
778 with support.transient_internet('svn.python.org'):
779 h = client.HTTPSConnection('svn.python.org', 443)
780 h.request('GET', '/')
781 resp = h.getresponse()
782 self._check_svn_python_org(resp)
783
784 def test_networked_good_cert(self):
785 # We feed a CA cert that validates the server's cert
786 import ssl
787 support.requires('network')
788 with support.transient_internet('svn.python.org'):
789 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
790 context.verify_mode = ssl.CERT_REQUIRED
791 context.load_verify_locations(CACERT_svn_python_org)
792 h = client.HTTPSConnection('svn.python.org', 443, context=context)
793 h.request('GET', '/')
794 resp = h.getresponse()
795 self._check_svn_python_org(resp)
796
797 def test_networked_bad_cert(self):
798 # We feed a "CA" cert that is unrelated to the server's cert
799 import ssl
800 support.requires('network')
801 with support.transient_internet('svn.python.org'):
802 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
803 context.verify_mode = ssl.CERT_REQUIRED
804 context.load_verify_locations(CERT_localhost)
805 h = client.HTTPSConnection('svn.python.org', 443, context=context)
806 with self.assertRaises(ssl.SSLError):
807 h.request('GET', '/')
808
809 def test_local_good_hostname(self):
810 # The (valid) cert validates the HTTP hostname
811 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700812 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000813 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
814 context.verify_mode = ssl.CERT_REQUIRED
815 context.load_verify_locations(CERT_localhost)
816 h = client.HTTPSConnection('localhost', server.port, context=context)
817 h.request('GET', '/nonexistent')
818 resp = h.getresponse()
819 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700820 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000821
822 def test_local_bad_hostname(self):
823 # The (valid) cert doesn't validate the HTTP hostname
824 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700825 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000826 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
827 context.verify_mode = ssl.CERT_REQUIRED
828 context.load_verify_locations(CERT_fakehostname)
829 h = client.HTTPSConnection('localhost', server.port, context=context)
830 with self.assertRaises(ssl.CertificateError):
831 h.request('GET', '/')
832 # Same with explicit check_hostname=True
833 h = client.HTTPSConnection('localhost', server.port, context=context,
834 check_hostname=True)
835 with self.assertRaises(ssl.CertificateError):
836 h.request('GET', '/')
837 # With check_hostname=False, the mismatching is ignored
838 h = client.HTTPSConnection('localhost', server.port, context=context,
839 check_hostname=False)
840 h.request('GET', '/nonexistent')
841 resp = h.getresponse()
842 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700843 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000844
Petri Lehtinene119c402011-10-26 21:29:15 +0300845 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
846 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200847 def test_host_port(self):
848 # Check invalid host_port
849
850 for hp in ("www.python.org:abc", "user:password@www.python.org"):
851 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
852
853 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
854 "fe80::207:e9ff:fe9b", 8000),
855 ("www.python.org:443", "www.python.org", 443),
856 ("www.python.org:", "www.python.org", 443),
857 ("www.python.org", "www.python.org", 443),
858 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
859 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
860 443)):
861 c = client.HTTPSConnection(hp)
862 self.assertEqual(h, c.host)
863 self.assertEqual(p, c.port)
864
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000865
Jeremy Hylton236654b2009-03-27 20:24:34 +0000866class RequestBodyTest(TestCase):
867 """Test cases where a request includes a message body."""
868
869 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000870 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000871 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000872 self.conn.sock = self.sock
873
874 def get_headers_and_fp(self):
875 f = io.BytesIO(self.sock.data)
876 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000877 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000878 return message, f
879
880 def test_manual_content_length(self):
881 # Set an incorrect content-length so that we can verify that
882 # it will not be over-ridden by the library.
883 self.conn.request("PUT", "/url", "body",
884 {"Content-Length": "42"})
885 message, f = self.get_headers_and_fp()
886 self.assertEqual("42", message.get("content-length"))
887 self.assertEqual(4, len(f.read()))
888
889 def test_ascii_body(self):
890 self.conn.request("PUT", "/url", "body")
891 message, f = self.get_headers_and_fp()
892 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000893 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000894 self.assertEqual("4", message.get("content-length"))
895 self.assertEqual(b'body', f.read())
896
897 def test_latin1_body(self):
898 self.conn.request("PUT", "/url", "body\xc1")
899 message, f = self.get_headers_and_fp()
900 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000901 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000902 self.assertEqual("5", message.get("content-length"))
903 self.assertEqual(b'body\xc1', f.read())
904
905 def test_bytes_body(self):
906 self.conn.request("PUT", "/url", b"body\xc1")
907 message, f = self.get_headers_and_fp()
908 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000909 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000910 self.assertEqual("5", message.get("content-length"))
911 self.assertEqual(b'body\xc1', f.read())
912
913 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200914 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000915 with open(support.TESTFN, "w") as f:
916 f.write("body")
917 with open(support.TESTFN) as f:
918 self.conn.request("PUT", "/url", f)
919 message, f = self.get_headers_and_fp()
920 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000921 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000922 self.assertEqual("4", message.get("content-length"))
923 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000924
925 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200926 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000927 with open(support.TESTFN, "wb") as f:
928 f.write(b"body\xc1")
929 with open(support.TESTFN, "rb") as f:
930 self.conn.request("PUT", "/url", f)
931 message, f = self.get_headers_and_fp()
932 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000933 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000934 self.assertEqual("5", message.get("content-length"))
935 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000936
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000937
938class HTTPResponseTest(TestCase):
939
940 def setUp(self):
941 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
942 second-value\r\n\r\nText"
943 sock = FakeSocket(body)
944 self.resp = client.HTTPResponse(sock)
945 self.resp.begin()
946
947 def test_getting_header(self):
948 header = self.resp.getheader('My-Header')
949 self.assertEqual(header, 'first-value, second-value')
950
951 header = self.resp.getheader('My-Header', 'some default')
952 self.assertEqual(header, 'first-value, second-value')
953
954 def test_getting_nonexistent_header_with_string_default(self):
955 header = self.resp.getheader('No-Such-Header', 'default-value')
956 self.assertEqual(header, 'default-value')
957
958 def test_getting_nonexistent_header_with_iterable_default(self):
959 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
960 self.assertEqual(header, 'default, values')
961
962 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
963 self.assertEqual(header, 'default, values')
964
965 def test_getting_nonexistent_header_without_default(self):
966 header = self.resp.getheader('No-Such-Header')
967 self.assertEqual(header, None)
968
969 def test_getting_header_defaultint(self):
970 header = self.resp.getheader('No-Such-Header',default=42)
971 self.assertEqual(header, 42)
972
Jeremy Hylton2c178252004-08-07 16:28:14 +0000973def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000974 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000975 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000976 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000977
Thomas Wouters89f507f2006-12-13 04:49:30 +0000978if __name__ == '__main__':
979 test_main()