blob: be2d77160c61c3fd5cde8d6d8e3cd13e02b7764d [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
Jeremy Hylton8fff7922007-08-03 20:56:14 +000056class NoEOFStringIO(io.BytesIO):
Jeremy Hylton121d34a2003-07-08 12:36:58 +000057 """Like StringIO, but raises AssertionError on EOF.
58
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)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000137 self.assertTrue(b'Content-length: 42' in conn._buffer)
138
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()
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000167 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000168 self.assertTrue(resp.isclosed())
Jeremy Hyltonba603192003-01-23 18:02:20 +0000169
Thomas Wouters89f507f2006-12-13 04:49:30 +0000170 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
171 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000172 resp = client.HTTPResponse(sock)
173 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000174
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000175 def test_bad_status_repr(self):
176 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000177 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000178
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000179 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100180 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000181 # same behaviour than when we read the whole thing with read()
182 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
183 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000184 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000185 resp.begin()
186 self.assertEqual(resp.read(2), b'Te')
187 self.assertFalse(resp.isclosed())
188 self.assertEqual(resp.read(2), b'xt')
189 self.assertTrue(resp.isclosed())
190
Antoine Pitrou38d96432011-12-06 22:33:57 +0100191 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100192 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100193 # same behaviour than when we read the whole thing with read()
194 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
195 sock = FakeSocket(body)
196 resp = client.HTTPResponse(sock)
197 resp.begin()
198 b = bytearray(2)
199 n = resp.readinto(b)
200 self.assertEqual(n, 2)
201 self.assertEqual(bytes(b), b'Te')
202 self.assertFalse(resp.isclosed())
203 n = resp.readinto(b)
204 self.assertEqual(n, 2)
205 self.assertEqual(bytes(b), b'xt')
206 self.assertTrue(resp.isclosed())
207
Antoine Pitrou084daa22012-12-15 19:11:54 +0100208 def test_partial_reads_no_content_length(self):
209 # when no length is present, the socket should be gracefully closed when
210 # all data was read
211 body = "HTTP/1.1 200 Ok\r\n\r\nText"
212 sock = FakeSocket(body)
213 resp = client.HTTPResponse(sock)
214 resp.begin()
215 self.assertEqual(resp.read(2), b'Te')
216 self.assertFalse(resp.isclosed())
217 self.assertEqual(resp.read(2), b'xt')
218 self.assertEqual(resp.read(1), b'')
219 self.assertTrue(resp.isclosed())
220
Antoine Pitroud20e7742012-12-15 19:22:30 +0100221 def test_partial_readintos_no_content_length(self):
222 # when no length is present, the socket should be gracefully closed when
223 # all data was read
224 body = "HTTP/1.1 200 Ok\r\n\r\nText"
225 sock = FakeSocket(body)
226 resp = client.HTTPResponse(sock)
227 resp.begin()
228 b = bytearray(2)
229 n = resp.readinto(b)
230 self.assertEqual(n, 2)
231 self.assertEqual(bytes(b), b'Te')
232 self.assertFalse(resp.isclosed())
233 n = resp.readinto(b)
234 self.assertEqual(n, 2)
235 self.assertEqual(bytes(b), b'xt')
236 n = resp.readinto(b)
237 self.assertEqual(n, 0)
238 self.assertTrue(resp.isclosed())
239
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100240 def test_partial_reads_incomplete_body(self):
241 # if the server shuts down the connection before the whole
242 # content-length is delivered, the socket is gracefully closed
243 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
244 sock = FakeSocket(body)
245 resp = client.HTTPResponse(sock)
246 resp.begin()
247 self.assertEqual(resp.read(2), b'Te')
248 self.assertFalse(resp.isclosed())
249 self.assertEqual(resp.read(2), b'xt')
250 self.assertEqual(resp.read(1), b'')
251 self.assertTrue(resp.isclosed())
252
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100253 def test_partial_readintos_incomplete_body(self):
254 # if the server shuts down the connection before the whole
255 # content-length is delivered, the socket is gracefully closed
256 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
257 sock = FakeSocket(body)
258 resp = client.HTTPResponse(sock)
259 resp.begin()
260 b = bytearray(2)
261 n = resp.readinto(b)
262 self.assertEqual(n, 2)
263 self.assertEqual(bytes(b), b'Te')
264 self.assertFalse(resp.isclosed())
265 n = resp.readinto(b)
266 self.assertEqual(n, 2)
267 self.assertEqual(bytes(b), b'xt')
268 n = resp.readinto(b)
269 self.assertEqual(n, 0)
270 self.assertTrue(resp.isclosed())
271
Thomas Wouters89f507f2006-12-13 04:49:30 +0000272 def test_host_port(self):
273 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000274
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200275 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000276 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000277
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000278 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
279 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200281 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000282 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200283 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
284 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000285 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000286 self.assertEqual(h, c.host)
287 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000288
Thomas Wouters89f507f2006-12-13 04:49:30 +0000289 def test_response_headers(self):
290 # test response with multiple message headers with the same field name.
291 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000292 'Set-Cookie: Customer="WILE_E_COYOTE"; '
293 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000294 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
295 ' Path="/acme"\r\n'
296 '\r\n'
297 'No body\r\n')
298 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
299 ', '
300 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
301 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000302 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000303 r.begin()
304 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000305 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000306
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 def test_read_head(self):
308 # Test that the library doesn't attempt to read any data
309 # from a HEAD request. (Tickles SF bug #622042.)
310 sock = FakeSocket(
311 'HTTP/1.1 200 OK\r\n'
312 'Content-Length: 14432\r\n'
313 '\r\n',
314 NoEOFStringIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000315 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000316 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000317 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000319
Antoine Pitrou38d96432011-12-06 22:33:57 +0100320 def test_readinto_head(self):
321 # Test that the library doesn't attempt to read any data
322 # from a HEAD request. (Tickles SF bug #622042.)
323 sock = FakeSocket(
324 'HTTP/1.1 200 OK\r\n'
325 'Content-Length: 14432\r\n'
326 '\r\n',
327 NoEOFStringIO)
328 resp = client.HTTPResponse(sock, method="HEAD")
329 resp.begin()
330 b = bytearray(5)
331 if resp.readinto(b) != 0:
332 self.fail("Did not expect response from HEAD request")
333 self.assertEqual(bytes(b), b'\x00'*5)
334
Thomas Wouters89f507f2006-12-13 04:49:30 +0000335 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000336 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
337 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000338
Brett Cannon77b7de62010-10-29 23:31:11 +0000339 with open(__file__, 'rb') as body:
340 conn = client.HTTPConnection('example.com')
341 sock = FakeSocket(body)
342 conn.sock = sock
343 conn.request('GET', '/foo', body)
344 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
345 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000346
Antoine Pitrouead1d622009-09-29 18:44:53 +0000347 def test_send(self):
348 expected = b'this is a test this is only a test'
349 conn = client.HTTPConnection('example.com')
350 sock = FakeSocket(None)
351 conn.sock = sock
352 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000353 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000354 sock.data = b''
355 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000356 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000357 sock.data = b''
358 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000359 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000360
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000361 def test_send_iter(self):
362 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
363 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
364 b'\r\nonetwothree'
365
366 def body():
367 yield b"one"
368 yield b"two"
369 yield b"three"
370
371 conn = client.HTTPConnection('example.com')
372 sock = FakeSocket("")
373 conn.sock = sock
374 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000375 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000376
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800377 def test_send_type_error(self):
378 # See: Issue #12676
379 conn = client.HTTPConnection('example.com')
380 conn.sock = FakeSocket('')
381 with self.assertRaises(TypeError):
382 conn.request('POST', 'test', conn)
383
Christian Heimesa612dc02008-02-24 13:08:18 +0000384 def test_chunked(self):
385 chunked_start = (
386 'HTTP/1.1 200 OK\r\n'
387 'Transfer-Encoding: chunked\r\n\r\n'
388 'a\r\n'
389 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100390 '3\r\n'
391 'd! \r\n'
392 '8\r\n'
393 'and now \r\n'
394 '22\r\n'
395 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000396 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100397 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000398 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000399 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000400 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100401 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000402 resp.close()
403
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100404 # Various read sizes
405 for n in range(1, 12):
406 sock = FakeSocket(chunked_start + '0\r\n')
407 resp = client.HTTPResponse(sock, method="GET")
408 resp.begin()
409 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
410 resp.close()
411
Christian Heimesa612dc02008-02-24 13:08:18 +0000412 for x in ('', 'foo\r\n'):
413 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000414 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000415 resp.begin()
416 try:
417 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000418 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100419 self.assertEqual(i.partial, expected)
420 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
421 self.assertEqual(repr(i), expected_message)
422 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000423 else:
424 self.fail('IncompleteRead expected')
425 finally:
426 resp.close()
427
Antoine Pitrou38d96432011-12-06 22:33:57 +0100428 def test_readinto_chunked(self):
429 chunked_start = (
430 'HTTP/1.1 200 OK\r\n'
431 'Transfer-Encoding: chunked\r\n\r\n'
432 'a\r\n'
433 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100434 '3\r\n'
435 'd! \r\n'
436 '8\r\n'
437 'and now \r\n'
438 '22\r\n'
439 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100440 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100441 expected = b'hello world! and now for something completely different'
442 nexpected = len(expected)
443 b = bytearray(128)
444
Antoine Pitrou38d96432011-12-06 22:33:57 +0100445 sock = FakeSocket(chunked_start + '0\r\n')
446 resp = client.HTTPResponse(sock, method="GET")
447 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100448 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100449 self.assertEqual(b[:nexpected], expected)
450 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100451 resp.close()
452
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100453 # Various read sizes
454 for n in range(1, 12):
455 sock = FakeSocket(chunked_start + '0\r\n')
456 resp = client.HTTPResponse(sock, method="GET")
457 resp.begin()
458 m = memoryview(b)
459 i = resp.readinto(m[0:n])
460 i += resp.readinto(m[i:n + i])
461 i += resp.readinto(m[i:])
462 self.assertEqual(b[:nexpected], expected)
463 self.assertEqual(i, nexpected)
464 resp.close()
465
Antoine Pitrou38d96432011-12-06 22:33:57 +0100466 for x in ('', 'foo\r\n'):
467 sock = FakeSocket(chunked_start + x)
468 resp = client.HTTPResponse(sock, method="GET")
469 resp.begin()
470 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100471 n = resp.readinto(b)
472 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100473 self.assertEqual(i.partial, expected)
474 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
475 self.assertEqual(repr(i), expected_message)
476 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100477 else:
478 self.fail('IncompleteRead expected')
479 finally:
480 resp.close()
481
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000482 def test_chunked_head(self):
483 chunked_start = (
484 'HTTP/1.1 200 OK\r\n'
485 'Transfer-Encoding: chunked\r\n\r\n'
486 'a\r\n'
487 'hello world\r\n'
488 '1\r\n'
489 'd\r\n'
490 )
491 sock = FakeSocket(chunked_start + '0\r\n')
492 resp = client.HTTPResponse(sock, method="HEAD")
493 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000494 self.assertEqual(resp.read(), b'')
495 self.assertEqual(resp.status, 200)
496 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000497 self.assertTrue(resp.isclosed())
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000498
Antoine Pitrou38d96432011-12-06 22:33:57 +0100499 def test_readinto_chunked_head(self):
500 chunked_start = (
501 'HTTP/1.1 200 OK\r\n'
502 'Transfer-Encoding: chunked\r\n\r\n'
503 'a\r\n'
504 'hello world\r\n'
505 '1\r\n'
506 'd\r\n'
507 )
508 sock = FakeSocket(chunked_start + '0\r\n')
509 resp = client.HTTPResponse(sock, method="HEAD")
510 resp.begin()
511 b = bytearray(5)
512 n = resp.readinto(b)
513 self.assertEqual(n, 0)
514 self.assertEqual(bytes(b), b'\x00'*5)
515 self.assertEqual(resp.status, 200)
516 self.assertEqual(resp.reason, 'OK')
517 self.assertTrue(resp.isclosed())
518
Christian Heimesa612dc02008-02-24 13:08:18 +0000519 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000520 sock = FakeSocket(
521 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000522 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000523 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000524 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100525 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000526
Benjamin Peterson6accb982009-03-02 22:50:25 +0000527 def test_incomplete_read(self):
528 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000529 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000530 resp.begin()
531 try:
532 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000533 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000534 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000535 self.assertEqual(repr(i),
536 "IncompleteRead(7 bytes read, 3 more expected)")
537 self.assertEqual(str(i),
538 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100539 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000540 else:
541 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000542
Jeremy Hylton636950f2009-03-28 04:34:21 +0000543 def test_epipe(self):
544 sock = EPipeSocket(
545 "HTTP/1.0 401 Authorization Required\r\n"
546 "Content-type: text/html\r\n"
547 "WWW-Authenticate: Basic realm=\"example\"\r\n",
548 b"Content-Length")
549 conn = client.HTTPConnection("example.com")
550 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200551 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000552 lambda: conn.request("PUT", "/url", "body"))
553 resp = conn.getresponse()
554 self.assertEqual(401, resp.status)
555 self.assertEqual("Basic realm=\"example\"",
556 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000557
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000558 # Test lines overflowing the max line size (_MAXLINE in http.client)
559
560 def test_overflowing_status_line(self):
561 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
562 resp = client.HTTPResponse(FakeSocket(body))
563 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
564
565 def test_overflowing_header_line(self):
566 body = (
567 'HTTP/1.1 200 OK\r\n'
568 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
569 )
570 resp = client.HTTPResponse(FakeSocket(body))
571 self.assertRaises(client.LineTooLong, resp.begin)
572
573 def test_overflowing_chunked_line(self):
574 body = (
575 'HTTP/1.1 200 OK\r\n'
576 'Transfer-Encoding: chunked\r\n\r\n'
577 + '0' * 65536 + 'a\r\n'
578 'hello world\r\n'
579 '0\r\n'
580 )
581 resp = client.HTTPResponse(FakeSocket(body))
582 resp.begin()
583 self.assertRaises(client.LineTooLong, resp.read)
584
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800585 def test_early_eof(self):
586 # Test httpresponse with no \r\n termination,
587 body = "HTTP/1.1 200 Ok"
588 sock = FakeSocket(body)
589 resp = client.HTTPResponse(sock)
590 resp.begin()
591 self.assertEqual(resp.read(), b'')
592 self.assertTrue(resp.isclosed())
593
Antoine Pitrou90e47742013-01-02 22:10:47 +0100594 def test_delayed_ack_opt(self):
595 # Test that Nagle/delayed_ack optimistaion works correctly.
596
597 # For small payloads, it should coalesce the body with
598 # headers, resulting in a single sendall() call
599 conn = client.HTTPConnection('example.com')
600 sock = FakeSocket(None)
601 conn.sock = sock
602 body = b'x' * (conn.mss - 1)
603 conn.request('POST', '/', body)
604 self.assertEqual(sock.sendall_calls, 1)
605
606 # For large payloads, it should send the headers and
607 # then the body, resulting in more than one sendall()
608 # call
609 conn = client.HTTPConnection('example.com')
610 sock = FakeSocket(None)
611 conn.sock = sock
612 body = b'x' * conn.mss
613 conn.request('POST', '/', body)
614 self.assertGreater(sock.sendall_calls, 1)
615
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000616class OfflineTest(TestCase):
617 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000618 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000619
Gregory P. Smithb4066372010-01-03 03:28:29 +0000620
621class SourceAddressTest(TestCase):
622 def setUp(self):
623 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
624 self.port = support.bind_port(self.serv)
625 self.source_port = support.find_unused_port()
626 self.serv.listen(5)
627 self.conn = None
628
629 def tearDown(self):
630 if self.conn:
631 self.conn.close()
632 self.conn = None
633 self.serv.close()
634 self.serv = None
635
636 def testHTTPConnectionSourceAddress(self):
637 self.conn = client.HTTPConnection(HOST, self.port,
638 source_address=('', self.source_port))
639 self.conn.connect()
640 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
641
642 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
643 'http.client.HTTPSConnection not defined')
644 def testHTTPSConnectionSourceAddress(self):
645 self.conn = client.HTTPSConnection(HOST, self.port,
646 source_address=('', self.source_port))
647 # We don't test anything here other the constructor not barfing as
648 # this code doesn't deal with setting up an active running SSL server
649 # for an ssl_wrapped connect() to actually return from.
650
651
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000653 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654
655 def setUp(self):
656 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000657 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000658 self.serv.listen(5)
659
660 def tearDown(self):
661 self.serv.close()
662 self.serv = None
663
664 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000665 # This will prove that the timeout gets through HTTPConnection
666 # and into the socket.
667
Georg Brandlf78e02b2008-06-10 17:40:04 +0000668 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000669 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000670 socket.setdefaulttimeout(30)
671 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000672 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000673 httpConn.connect()
674 finally:
675 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000676 self.assertEqual(httpConn.sock.gettimeout(), 30)
677 httpConn.close()
678
Georg Brandlf78e02b2008-06-10 17:40:04 +0000679 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000680 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000681 socket.setdefaulttimeout(30)
682 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000683 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000684 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685 httpConn.connect()
686 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000687 socket.setdefaulttimeout(None)
688 self.assertEqual(httpConn.sock.gettimeout(), None)
689 httpConn.close()
690
691 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000692 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000693 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000694 self.assertEqual(httpConn.sock.gettimeout(), 30)
695 httpConn.close()
696
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000697
698class HTTPSTest(TestCase):
699
700 def setUp(self):
701 if not hasattr(client, 'HTTPSConnection'):
702 self.skipTest('ssl support required')
703
704 def make_server(self, certfile):
705 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100706 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000707
708 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000709 # simple test to check it's storing the timeout
710 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
711 self.assertEqual(h.timeout, 30)
712
713 def _check_svn_python_org(self, resp):
714 # Just a simple check that everything went fine
715 server_string = resp.getheader('server')
716 self.assertIn('Apache', server_string)
717
718 def test_networked(self):
719 # Default settings: no cert verification is done
720 support.requires('network')
721 with support.transient_internet('svn.python.org'):
722 h = client.HTTPSConnection('svn.python.org', 443)
723 h.request('GET', '/')
724 resp = h.getresponse()
725 self._check_svn_python_org(resp)
726
727 def test_networked_good_cert(self):
728 # We feed a CA cert that validates the server's cert
729 import ssl
730 support.requires('network')
731 with support.transient_internet('svn.python.org'):
732 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
733 context.verify_mode = ssl.CERT_REQUIRED
734 context.load_verify_locations(CACERT_svn_python_org)
735 h = client.HTTPSConnection('svn.python.org', 443, context=context)
736 h.request('GET', '/')
737 resp = h.getresponse()
738 self._check_svn_python_org(resp)
739
740 def test_networked_bad_cert(self):
741 # We feed a "CA" cert that is unrelated to the server's cert
742 import ssl
743 support.requires('network')
744 with support.transient_internet('svn.python.org'):
745 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
746 context.verify_mode = ssl.CERT_REQUIRED
747 context.load_verify_locations(CERT_localhost)
748 h = client.HTTPSConnection('svn.python.org', 443, context=context)
749 with self.assertRaises(ssl.SSLError):
750 h.request('GET', '/')
751
752 def test_local_good_hostname(self):
753 # The (valid) cert validates the HTTP hostname
754 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700755 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000756 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
757 context.verify_mode = ssl.CERT_REQUIRED
758 context.load_verify_locations(CERT_localhost)
759 h = client.HTTPSConnection('localhost', server.port, context=context)
760 h.request('GET', '/nonexistent')
761 resp = h.getresponse()
762 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700763 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000764
765 def test_local_bad_hostname(self):
766 # The (valid) cert doesn't validate the HTTP hostname
767 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700768 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000769 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
770 context.verify_mode = ssl.CERT_REQUIRED
771 context.load_verify_locations(CERT_fakehostname)
772 h = client.HTTPSConnection('localhost', server.port, context=context)
773 with self.assertRaises(ssl.CertificateError):
774 h.request('GET', '/')
775 # Same with explicit check_hostname=True
776 h = client.HTTPSConnection('localhost', server.port, context=context,
777 check_hostname=True)
778 with self.assertRaises(ssl.CertificateError):
779 h.request('GET', '/')
780 # With check_hostname=False, the mismatching is ignored
781 h = client.HTTPSConnection('localhost', server.port, context=context,
782 check_hostname=False)
783 h.request('GET', '/nonexistent')
784 resp = h.getresponse()
785 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700786 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000787
Petri Lehtinene119c402011-10-26 21:29:15 +0300788 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
789 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200790 def test_host_port(self):
791 # Check invalid host_port
792
793 for hp in ("www.python.org:abc", "user:password@www.python.org"):
794 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
795
796 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
797 "fe80::207:e9ff:fe9b", 8000),
798 ("www.python.org:443", "www.python.org", 443),
799 ("www.python.org:", "www.python.org", 443),
800 ("www.python.org", "www.python.org", 443),
801 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
802 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
803 443)):
804 c = client.HTTPSConnection(hp)
805 self.assertEqual(h, c.host)
806 self.assertEqual(p, c.port)
807
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000808
Jeremy Hylton236654b2009-03-27 20:24:34 +0000809class RequestBodyTest(TestCase):
810 """Test cases where a request includes a message body."""
811
812 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000813 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000814 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000815 self.conn.sock = self.sock
816
817 def get_headers_and_fp(self):
818 f = io.BytesIO(self.sock.data)
819 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000820 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000821 return message, f
822
823 def test_manual_content_length(self):
824 # Set an incorrect content-length so that we can verify that
825 # it will not be over-ridden by the library.
826 self.conn.request("PUT", "/url", "body",
827 {"Content-Length": "42"})
828 message, f = self.get_headers_and_fp()
829 self.assertEqual("42", message.get("content-length"))
830 self.assertEqual(4, len(f.read()))
831
832 def test_ascii_body(self):
833 self.conn.request("PUT", "/url", "body")
834 message, f = self.get_headers_and_fp()
835 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000836 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000837 self.assertEqual("4", message.get("content-length"))
838 self.assertEqual(b'body', f.read())
839
840 def test_latin1_body(self):
841 self.conn.request("PUT", "/url", "body\xc1")
842 message, f = self.get_headers_and_fp()
843 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000844 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000845 self.assertEqual("5", message.get("content-length"))
846 self.assertEqual(b'body\xc1', f.read())
847
848 def test_bytes_body(self):
849 self.conn.request("PUT", "/url", b"body\xc1")
850 message, f = self.get_headers_and_fp()
851 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000852 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000853 self.assertEqual("5", message.get("content-length"))
854 self.assertEqual(b'body\xc1', f.read())
855
856 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200857 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000858 with open(support.TESTFN, "w") as f:
859 f.write("body")
860 with open(support.TESTFN) as f:
861 self.conn.request("PUT", "/url", f)
862 message, f = self.get_headers_and_fp()
863 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000864 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000865 self.assertEqual("4", message.get("content-length"))
866 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000867
868 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200869 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000870 with open(support.TESTFN, "wb") as f:
871 f.write(b"body\xc1")
872 with open(support.TESTFN, "rb") as f:
873 self.conn.request("PUT", "/url", f)
874 message, f = self.get_headers_and_fp()
875 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000876 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000877 self.assertEqual("5", message.get("content-length"))
878 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000879
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000880
881class HTTPResponseTest(TestCase):
882
883 def setUp(self):
884 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
885 second-value\r\n\r\nText"
886 sock = FakeSocket(body)
887 self.resp = client.HTTPResponse(sock)
888 self.resp.begin()
889
890 def test_getting_header(self):
891 header = self.resp.getheader('My-Header')
892 self.assertEqual(header, 'first-value, second-value')
893
894 header = self.resp.getheader('My-Header', 'some default')
895 self.assertEqual(header, 'first-value, second-value')
896
897 def test_getting_nonexistent_header_with_string_default(self):
898 header = self.resp.getheader('No-Such-Header', 'default-value')
899 self.assertEqual(header, 'default-value')
900
901 def test_getting_nonexistent_header_with_iterable_default(self):
902 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
903 self.assertEqual(header, 'default, values')
904
905 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
906 self.assertEqual(header, 'default, values')
907
908 def test_getting_nonexistent_header_without_default(self):
909 header = self.resp.getheader('No-Such-Header')
910 self.assertEqual(header, None)
911
912 def test_getting_header_defaultint(self):
913 header = self.resp.getheader('No-Such-Header',default=42)
914 self.assertEqual(header, 42)
915
Jeremy Hylton2c178252004-08-07 16:28:14 +0000916def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000917 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000918 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000919 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000920
Thomas Wouters89f507f2006-12-13 04:49:30 +0000921if __name__ == '__main__':
922 test_main()