blob: a2f141ec5e8495146b3c026f16aeef1d6e771f87 [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())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200169 self.assertFalse(resp.closed)
170 resp.close()
171 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000172
Thomas Wouters89f507f2006-12-13 04:49:30 +0000173 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
174 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000175 resp = client.HTTPResponse(sock)
176 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000177
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000178 def test_bad_status_repr(self):
179 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000180 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000181
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000182 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100183 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000184 # same behaviour than when we read the whole thing with read()
185 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
186 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000187 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000188 resp.begin()
189 self.assertEqual(resp.read(2), b'Te')
190 self.assertFalse(resp.isclosed())
191 self.assertEqual(resp.read(2), b'xt')
192 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200193 self.assertFalse(resp.closed)
194 resp.close()
195 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000196
Antoine Pitrou38d96432011-12-06 22:33:57 +0100197 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100198 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100199 # same behaviour than when we read the whole thing with read()
200 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
201 sock = FakeSocket(body)
202 resp = client.HTTPResponse(sock)
203 resp.begin()
204 b = bytearray(2)
205 n = resp.readinto(b)
206 self.assertEqual(n, 2)
207 self.assertEqual(bytes(b), b'Te')
208 self.assertFalse(resp.isclosed())
209 n = resp.readinto(b)
210 self.assertEqual(n, 2)
211 self.assertEqual(bytes(b), b'xt')
212 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200213 self.assertFalse(resp.closed)
214 resp.close()
215 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100216
Antoine Pitrou084daa22012-12-15 19:11:54 +0100217 def test_partial_reads_no_content_length(self):
218 # when no length is present, the socket should be gracefully closed when
219 # all data was read
220 body = "HTTP/1.1 200 Ok\r\n\r\nText"
221 sock = FakeSocket(body)
222 resp = client.HTTPResponse(sock)
223 resp.begin()
224 self.assertEqual(resp.read(2), b'Te')
225 self.assertFalse(resp.isclosed())
226 self.assertEqual(resp.read(2), b'xt')
227 self.assertEqual(resp.read(1), b'')
228 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200229 self.assertFalse(resp.closed)
230 resp.close()
231 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100232
Antoine Pitroud20e7742012-12-15 19:22:30 +0100233 def test_partial_readintos_no_content_length(self):
234 # when no length is present, the socket should be gracefully closed when
235 # all data was read
236 body = "HTTP/1.1 200 Ok\r\n\r\nText"
237 sock = FakeSocket(body)
238 resp = client.HTTPResponse(sock)
239 resp.begin()
240 b = bytearray(2)
241 n = resp.readinto(b)
242 self.assertEqual(n, 2)
243 self.assertEqual(bytes(b), b'Te')
244 self.assertFalse(resp.isclosed())
245 n = resp.readinto(b)
246 self.assertEqual(n, 2)
247 self.assertEqual(bytes(b), b'xt')
248 n = resp.readinto(b)
249 self.assertEqual(n, 0)
250 self.assertTrue(resp.isclosed())
251
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100252 def test_partial_reads_incomplete_body(self):
253 # if the server shuts down the connection before the whole
254 # content-length is delivered, the socket is gracefully closed
255 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
256 sock = FakeSocket(body)
257 resp = client.HTTPResponse(sock)
258 resp.begin()
259 self.assertEqual(resp.read(2), b'Te')
260 self.assertFalse(resp.isclosed())
261 self.assertEqual(resp.read(2), b'xt')
262 self.assertEqual(resp.read(1), b'')
263 self.assertTrue(resp.isclosed())
264
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100265 def test_partial_readintos_incomplete_body(self):
266 # if the server shuts down the connection before the whole
267 # content-length is delivered, the socket is gracefully closed
268 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
269 sock = FakeSocket(body)
270 resp = client.HTTPResponse(sock)
271 resp.begin()
272 b = bytearray(2)
273 n = resp.readinto(b)
274 self.assertEqual(n, 2)
275 self.assertEqual(bytes(b), b'Te')
276 self.assertFalse(resp.isclosed())
277 n = resp.readinto(b)
278 self.assertEqual(n, 2)
279 self.assertEqual(bytes(b), b'xt')
280 n = resp.readinto(b)
281 self.assertEqual(n, 0)
282 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200283 self.assertFalse(resp.closed)
284 resp.close()
285 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100286
Thomas Wouters89f507f2006-12-13 04:49:30 +0000287 def test_host_port(self):
288 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000289
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200290 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000291 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000293 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
294 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200296 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000297 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200298 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
299 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000300 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000301 self.assertEqual(h, c.host)
302 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000303
Thomas Wouters89f507f2006-12-13 04:49:30 +0000304 def test_response_headers(self):
305 # test response with multiple message headers with the same field name.
306 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000307 'Set-Cookie: Customer="WILE_E_COYOTE"; '
308 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000309 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
310 ' Path="/acme"\r\n'
311 '\r\n'
312 'No body\r\n')
313 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
314 ', '
315 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
316 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000317 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000318 r.begin()
319 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000320 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000321
Thomas Wouters89f507f2006-12-13 04:49:30 +0000322 def test_read_head(self):
323 # Test that the library doesn't attempt to read any data
324 # from a HEAD request. (Tickles SF bug #622042.)
325 sock = FakeSocket(
326 'HTTP/1.1 200 OK\r\n'
327 'Content-Length: 14432\r\n'
328 '\r\n',
329 NoEOFStringIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000330 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000331 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000332 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000334
Antoine Pitrou38d96432011-12-06 22:33:57 +0100335 def test_readinto_head(self):
336 # Test that the library doesn't attempt to read any data
337 # from a HEAD request. (Tickles SF bug #622042.)
338 sock = FakeSocket(
339 'HTTP/1.1 200 OK\r\n'
340 'Content-Length: 14432\r\n'
341 '\r\n',
342 NoEOFStringIO)
343 resp = client.HTTPResponse(sock, method="HEAD")
344 resp.begin()
345 b = bytearray(5)
346 if resp.readinto(b) != 0:
347 self.fail("Did not expect response from HEAD request")
348 self.assertEqual(bytes(b), b'\x00'*5)
349
Thomas Wouters89f507f2006-12-13 04:49:30 +0000350 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000351 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
352 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000353
Brett Cannon77b7de62010-10-29 23:31:11 +0000354 with open(__file__, 'rb') as body:
355 conn = client.HTTPConnection('example.com')
356 sock = FakeSocket(body)
357 conn.sock = sock
358 conn.request('GET', '/foo', body)
359 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
360 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000361
Antoine Pitrouead1d622009-09-29 18:44:53 +0000362 def test_send(self):
363 expected = b'this is a test this is only a test'
364 conn = client.HTTPConnection('example.com')
365 sock = FakeSocket(None)
366 conn.sock = sock
367 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000368 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000369 sock.data = b''
370 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000371 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000372 sock.data = b''
373 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000374 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000375
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000376 def test_send_iter(self):
377 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
378 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
379 b'\r\nonetwothree'
380
381 def body():
382 yield b"one"
383 yield b"two"
384 yield b"three"
385
386 conn = client.HTTPConnection('example.com')
387 sock = FakeSocket("")
388 conn.sock = sock
389 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000390 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000391
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800392 def test_send_type_error(self):
393 # See: Issue #12676
394 conn = client.HTTPConnection('example.com')
395 conn.sock = FakeSocket('')
396 with self.assertRaises(TypeError):
397 conn.request('POST', 'test', conn)
398
Christian Heimesa612dc02008-02-24 13:08:18 +0000399 def test_chunked(self):
400 chunked_start = (
401 'HTTP/1.1 200 OK\r\n'
402 'Transfer-Encoding: chunked\r\n\r\n'
403 'a\r\n'
404 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100405 '3\r\n'
406 'd! \r\n'
407 '8\r\n'
408 'and now \r\n'
409 '22\r\n'
410 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000411 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100412 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000413 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000414 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000415 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100416 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000417 resp.close()
418
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100419 # Various read sizes
420 for n in range(1, 12):
421 sock = FakeSocket(chunked_start + '0\r\n')
422 resp = client.HTTPResponse(sock, method="GET")
423 resp.begin()
424 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
425 resp.close()
426
Christian Heimesa612dc02008-02-24 13:08:18 +0000427 for x in ('', 'foo\r\n'):
428 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000429 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000430 resp.begin()
431 try:
432 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000433 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100434 self.assertEqual(i.partial, expected)
435 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
436 self.assertEqual(repr(i), expected_message)
437 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000438 else:
439 self.fail('IncompleteRead expected')
440 finally:
441 resp.close()
442
Antoine Pitrou38d96432011-12-06 22:33:57 +0100443 def test_readinto_chunked(self):
444 chunked_start = (
445 'HTTP/1.1 200 OK\r\n'
446 'Transfer-Encoding: chunked\r\n\r\n'
447 'a\r\n'
448 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100449 '3\r\n'
450 'd! \r\n'
451 '8\r\n'
452 'and now \r\n'
453 '22\r\n'
454 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100455 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100456 expected = b'hello world! and now for something completely different'
457 nexpected = len(expected)
458 b = bytearray(128)
459
Antoine Pitrou38d96432011-12-06 22:33:57 +0100460 sock = FakeSocket(chunked_start + '0\r\n')
461 resp = client.HTTPResponse(sock, method="GET")
462 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100463 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100464 self.assertEqual(b[:nexpected], expected)
465 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100466 resp.close()
467
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100468 # Various read sizes
469 for n in range(1, 12):
470 sock = FakeSocket(chunked_start + '0\r\n')
471 resp = client.HTTPResponse(sock, method="GET")
472 resp.begin()
473 m = memoryview(b)
474 i = resp.readinto(m[0:n])
475 i += resp.readinto(m[i:n + i])
476 i += resp.readinto(m[i:])
477 self.assertEqual(b[:nexpected], expected)
478 self.assertEqual(i, nexpected)
479 resp.close()
480
Antoine Pitrou38d96432011-12-06 22:33:57 +0100481 for x in ('', 'foo\r\n'):
482 sock = FakeSocket(chunked_start + x)
483 resp = client.HTTPResponse(sock, method="GET")
484 resp.begin()
485 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100486 n = resp.readinto(b)
487 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100488 self.assertEqual(i.partial, expected)
489 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
490 self.assertEqual(repr(i), expected_message)
491 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100492 else:
493 self.fail('IncompleteRead expected')
494 finally:
495 resp.close()
496
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000497 def test_chunked_head(self):
498 chunked_start = (
499 'HTTP/1.1 200 OK\r\n'
500 'Transfer-Encoding: chunked\r\n\r\n'
501 'a\r\n'
502 'hello world\r\n'
503 '1\r\n'
504 'd\r\n'
505 )
506 sock = FakeSocket(chunked_start + '0\r\n')
507 resp = client.HTTPResponse(sock, method="HEAD")
508 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000509 self.assertEqual(resp.read(), b'')
510 self.assertEqual(resp.status, 200)
511 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000512 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200513 self.assertFalse(resp.closed)
514 resp.close()
515 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000516
Antoine Pitrou38d96432011-12-06 22:33:57 +0100517 def test_readinto_chunked_head(self):
518 chunked_start = (
519 'HTTP/1.1 200 OK\r\n'
520 'Transfer-Encoding: chunked\r\n\r\n'
521 'a\r\n'
522 'hello world\r\n'
523 '1\r\n'
524 'd\r\n'
525 )
526 sock = FakeSocket(chunked_start + '0\r\n')
527 resp = client.HTTPResponse(sock, method="HEAD")
528 resp.begin()
529 b = bytearray(5)
530 n = resp.readinto(b)
531 self.assertEqual(n, 0)
532 self.assertEqual(bytes(b), b'\x00'*5)
533 self.assertEqual(resp.status, 200)
534 self.assertEqual(resp.reason, 'OK')
535 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200536 self.assertFalse(resp.closed)
537 resp.close()
538 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100539
Christian Heimesa612dc02008-02-24 13:08:18 +0000540 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000541 sock = FakeSocket(
542 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000543 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000544 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000545 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100546 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000547
Benjamin Peterson6accb982009-03-02 22:50:25 +0000548 def test_incomplete_read(self):
549 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000550 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000551 resp.begin()
552 try:
553 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000554 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000555 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000556 self.assertEqual(repr(i),
557 "IncompleteRead(7 bytes read, 3 more expected)")
558 self.assertEqual(str(i),
559 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100560 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000561 else:
562 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000563
Jeremy Hylton636950f2009-03-28 04:34:21 +0000564 def test_epipe(self):
565 sock = EPipeSocket(
566 "HTTP/1.0 401 Authorization Required\r\n"
567 "Content-type: text/html\r\n"
568 "WWW-Authenticate: Basic realm=\"example\"\r\n",
569 b"Content-Length")
570 conn = client.HTTPConnection("example.com")
571 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200572 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000573 lambda: conn.request("PUT", "/url", "body"))
574 resp = conn.getresponse()
575 self.assertEqual(401, resp.status)
576 self.assertEqual("Basic realm=\"example\"",
577 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000578
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000579 # Test lines overflowing the max line size (_MAXLINE in http.client)
580
581 def test_overflowing_status_line(self):
582 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
583 resp = client.HTTPResponse(FakeSocket(body))
584 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
585
586 def test_overflowing_header_line(self):
587 body = (
588 'HTTP/1.1 200 OK\r\n'
589 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
590 )
591 resp = client.HTTPResponse(FakeSocket(body))
592 self.assertRaises(client.LineTooLong, resp.begin)
593
594 def test_overflowing_chunked_line(self):
595 body = (
596 'HTTP/1.1 200 OK\r\n'
597 'Transfer-Encoding: chunked\r\n\r\n'
598 + '0' * 65536 + 'a\r\n'
599 'hello world\r\n'
600 '0\r\n'
601 )
602 resp = client.HTTPResponse(FakeSocket(body))
603 resp.begin()
604 self.assertRaises(client.LineTooLong, resp.read)
605
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800606 def test_early_eof(self):
607 # Test httpresponse with no \r\n termination,
608 body = "HTTP/1.1 200 Ok"
609 sock = FakeSocket(body)
610 resp = client.HTTPResponse(sock)
611 resp.begin()
612 self.assertEqual(resp.read(), b'')
613 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200614 self.assertFalse(resp.closed)
615 resp.close()
616 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800617
Antoine Pitrou90e47742013-01-02 22:10:47 +0100618 def test_delayed_ack_opt(self):
619 # Test that Nagle/delayed_ack optimistaion works correctly.
620
621 # For small payloads, it should coalesce the body with
622 # headers, resulting in a single sendall() call
623 conn = client.HTTPConnection('example.com')
624 sock = FakeSocket(None)
625 conn.sock = sock
626 body = b'x' * (conn.mss - 1)
627 conn.request('POST', '/', body)
628 self.assertEqual(sock.sendall_calls, 1)
629
630 # For large payloads, it should send the headers and
631 # then the body, resulting in more than one sendall()
632 # call
633 conn = client.HTTPConnection('example.com')
634 sock = FakeSocket(None)
635 conn.sock = sock
636 body = b'x' * conn.mss
637 conn.request('POST', '/', body)
638 self.assertGreater(sock.sendall_calls, 1)
639
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000640class OfflineTest(TestCase):
641 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000642 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000643
Gregory P. Smithb4066372010-01-03 03:28:29 +0000644
645class SourceAddressTest(TestCase):
646 def setUp(self):
647 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
648 self.port = support.bind_port(self.serv)
649 self.source_port = support.find_unused_port()
650 self.serv.listen(5)
651 self.conn = None
652
653 def tearDown(self):
654 if self.conn:
655 self.conn.close()
656 self.conn = None
657 self.serv.close()
658 self.serv = None
659
660 def testHTTPConnectionSourceAddress(self):
661 self.conn = client.HTTPConnection(HOST, self.port,
662 source_address=('', self.source_port))
663 self.conn.connect()
664 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
665
666 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
667 'http.client.HTTPSConnection not defined')
668 def testHTTPSConnectionSourceAddress(self):
669 self.conn = client.HTTPSConnection(HOST, self.port,
670 source_address=('', self.source_port))
671 # We don't test anything here other the constructor not barfing as
672 # this code doesn't deal with setting up an active running SSL server
673 # for an ssl_wrapped connect() to actually return from.
674
675
Guido van Rossumd8faa362007-04-27 19:54:29 +0000676class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000677 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000678
679 def setUp(self):
680 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000681 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000682 self.serv.listen(5)
683
684 def tearDown(self):
685 self.serv.close()
686 self.serv = None
687
688 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000689 # This will prove that the timeout gets through HTTPConnection
690 # and into the socket.
691
Georg Brandlf78e02b2008-06-10 17:40:04 +0000692 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000693 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000694 socket.setdefaulttimeout(30)
695 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000696 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000697 httpConn.connect()
698 finally:
699 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000700 self.assertEqual(httpConn.sock.gettimeout(), 30)
701 httpConn.close()
702
Georg Brandlf78e02b2008-06-10 17:40:04 +0000703 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000704 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000705 socket.setdefaulttimeout(30)
706 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000707 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000708 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000709 httpConn.connect()
710 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000711 socket.setdefaulttimeout(None)
712 self.assertEqual(httpConn.sock.gettimeout(), None)
713 httpConn.close()
714
715 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000716 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000717 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718 self.assertEqual(httpConn.sock.gettimeout(), 30)
719 httpConn.close()
720
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000721
722class HTTPSTest(TestCase):
723
724 def setUp(self):
725 if not hasattr(client, 'HTTPSConnection'):
726 self.skipTest('ssl support required')
727
728 def make_server(self, certfile):
729 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100730 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000731
732 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000733 # simple test to check it's storing the timeout
734 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
735 self.assertEqual(h.timeout, 30)
736
737 def _check_svn_python_org(self, resp):
738 # Just a simple check that everything went fine
739 server_string = resp.getheader('server')
740 self.assertIn('Apache', server_string)
741
742 def test_networked(self):
743 # Default settings: no cert verification is done
744 support.requires('network')
745 with support.transient_internet('svn.python.org'):
746 h = client.HTTPSConnection('svn.python.org', 443)
747 h.request('GET', '/')
748 resp = h.getresponse()
749 self._check_svn_python_org(resp)
750
751 def test_networked_good_cert(self):
752 # We feed a CA cert that validates the server's cert
753 import ssl
754 support.requires('network')
755 with support.transient_internet('svn.python.org'):
756 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
757 context.verify_mode = ssl.CERT_REQUIRED
758 context.load_verify_locations(CACERT_svn_python_org)
759 h = client.HTTPSConnection('svn.python.org', 443, context=context)
760 h.request('GET', '/')
761 resp = h.getresponse()
762 self._check_svn_python_org(resp)
763
764 def test_networked_bad_cert(self):
765 # We feed a "CA" cert that is unrelated to the server's cert
766 import ssl
767 support.requires('network')
768 with support.transient_internet('svn.python.org'):
769 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
770 context.verify_mode = ssl.CERT_REQUIRED
771 context.load_verify_locations(CERT_localhost)
772 h = client.HTTPSConnection('svn.python.org', 443, context=context)
773 with self.assertRaises(ssl.SSLError):
774 h.request('GET', '/')
775
776 def test_local_good_hostname(self):
777 # The (valid) cert validates the HTTP hostname
778 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700779 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000780 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
781 context.verify_mode = ssl.CERT_REQUIRED
782 context.load_verify_locations(CERT_localhost)
783 h = client.HTTPSConnection('localhost', server.port, context=context)
784 h.request('GET', '/nonexistent')
785 resp = h.getresponse()
786 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700787 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000788
789 def test_local_bad_hostname(self):
790 # The (valid) cert doesn't validate the HTTP hostname
791 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700792 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000793 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
794 context.verify_mode = ssl.CERT_REQUIRED
795 context.load_verify_locations(CERT_fakehostname)
796 h = client.HTTPSConnection('localhost', server.port, context=context)
797 with self.assertRaises(ssl.CertificateError):
798 h.request('GET', '/')
799 # Same with explicit check_hostname=True
800 h = client.HTTPSConnection('localhost', server.port, context=context,
801 check_hostname=True)
802 with self.assertRaises(ssl.CertificateError):
803 h.request('GET', '/')
804 # With check_hostname=False, the mismatching is ignored
805 h = client.HTTPSConnection('localhost', server.port, context=context,
806 check_hostname=False)
807 h.request('GET', '/nonexistent')
808 resp = h.getresponse()
809 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700810 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000811
Petri Lehtinene119c402011-10-26 21:29:15 +0300812 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
813 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200814 def test_host_port(self):
815 # Check invalid host_port
816
817 for hp in ("www.python.org:abc", "user:password@www.python.org"):
818 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
819
820 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
821 "fe80::207:e9ff:fe9b", 8000),
822 ("www.python.org:443", "www.python.org", 443),
823 ("www.python.org:", "www.python.org", 443),
824 ("www.python.org", "www.python.org", 443),
825 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
826 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
827 443)):
828 c = client.HTTPSConnection(hp)
829 self.assertEqual(h, c.host)
830 self.assertEqual(p, c.port)
831
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000832
Jeremy Hylton236654b2009-03-27 20:24:34 +0000833class RequestBodyTest(TestCase):
834 """Test cases where a request includes a message body."""
835
836 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000837 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000838 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000839 self.conn.sock = self.sock
840
841 def get_headers_and_fp(self):
842 f = io.BytesIO(self.sock.data)
843 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000844 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000845 return message, f
846
847 def test_manual_content_length(self):
848 # Set an incorrect content-length so that we can verify that
849 # it will not be over-ridden by the library.
850 self.conn.request("PUT", "/url", "body",
851 {"Content-Length": "42"})
852 message, f = self.get_headers_and_fp()
853 self.assertEqual("42", message.get("content-length"))
854 self.assertEqual(4, len(f.read()))
855
856 def test_ascii_body(self):
857 self.conn.request("PUT", "/url", "body")
858 message, f = self.get_headers_and_fp()
859 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000860 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000861 self.assertEqual("4", message.get("content-length"))
862 self.assertEqual(b'body', f.read())
863
864 def test_latin1_body(self):
865 self.conn.request("PUT", "/url", "body\xc1")
866 message, f = self.get_headers_and_fp()
867 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000868 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000869 self.assertEqual("5", message.get("content-length"))
870 self.assertEqual(b'body\xc1', f.read())
871
872 def test_bytes_body(self):
873 self.conn.request("PUT", "/url", b"body\xc1")
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())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000877 self.assertEqual("5", message.get("content-length"))
878 self.assertEqual(b'body\xc1', f.read())
879
880 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200881 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000882 with open(support.TESTFN, "w") as f:
883 f.write("body")
884 with open(support.TESTFN) as f:
885 self.conn.request("PUT", "/url", f)
886 message, f = self.get_headers_and_fp()
887 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000888 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000889 self.assertEqual("4", message.get("content-length"))
890 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000891
892 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200893 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000894 with open(support.TESTFN, "wb") as f:
895 f.write(b"body\xc1")
896 with open(support.TESTFN, "rb") as f:
897 self.conn.request("PUT", "/url", f)
898 message, f = self.get_headers_and_fp()
899 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000900 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000901 self.assertEqual("5", message.get("content-length"))
902 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000903
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000904
905class HTTPResponseTest(TestCase):
906
907 def setUp(self):
908 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
909 second-value\r\n\r\nText"
910 sock = FakeSocket(body)
911 self.resp = client.HTTPResponse(sock)
912 self.resp.begin()
913
914 def test_getting_header(self):
915 header = self.resp.getheader('My-Header')
916 self.assertEqual(header, 'first-value, second-value')
917
918 header = self.resp.getheader('My-Header', 'some default')
919 self.assertEqual(header, 'first-value, second-value')
920
921 def test_getting_nonexistent_header_with_string_default(self):
922 header = self.resp.getheader('No-Such-Header', 'default-value')
923 self.assertEqual(header, 'default-value')
924
925 def test_getting_nonexistent_header_with_iterable_default(self):
926 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
927 self.assertEqual(header, 'default, values')
928
929 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
930 self.assertEqual(header, 'default, values')
931
932 def test_getting_nonexistent_header_without_default(self):
933 header = self.resp.getheader('No-Such-Header')
934 self.assertEqual(header, None)
935
936 def test_getting_header_defaultint(self):
937 header = self.resp.getheader('No-Such-Header',default=42)
938 self.assertEqual(header, 42)
939
Jeremy Hylton2c178252004-08-07 16:28:14 +0000940def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000941 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000942 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000943 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000944
Thomas Wouters89f507f2006-12-13 04:49:30 +0000945if __name__ == '__main__':
946 test_main()