blob: b3688af89506d6b3ed0a1162f02d28516c47814c [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
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300376 def test_send_updating_file(self):
377 def data():
378 yield 'data'
379 yield None
380 yield 'data_two'
381
382 class UpdatingFile():
383 mode = 'r'
384 d = data()
385 def read(self, blocksize=-1):
386 return self.d.__next__()
387
388 expected = b'data'
389
390 conn = client.HTTPConnection('example.com')
391 sock = FakeSocket("")
392 conn.sock = sock
393 conn.send(UpdatingFile())
394 self.assertEqual(sock.data, expected)
395
396
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000397 def test_send_iter(self):
398 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
399 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
400 b'\r\nonetwothree'
401
402 def body():
403 yield b"one"
404 yield b"two"
405 yield b"three"
406
407 conn = client.HTTPConnection('example.com')
408 sock = FakeSocket("")
409 conn.sock = sock
410 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000411 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000412
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800413 def test_send_type_error(self):
414 # See: Issue #12676
415 conn = client.HTTPConnection('example.com')
416 conn.sock = FakeSocket('')
417 with self.assertRaises(TypeError):
418 conn.request('POST', 'test', conn)
419
Christian Heimesa612dc02008-02-24 13:08:18 +0000420 def test_chunked(self):
421 chunked_start = (
422 'HTTP/1.1 200 OK\r\n'
423 'Transfer-Encoding: chunked\r\n\r\n'
424 'a\r\n'
425 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100426 '3\r\n'
427 'd! \r\n'
428 '8\r\n'
429 'and now \r\n'
430 '22\r\n'
431 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000432 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100433 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000434 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000435 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000436 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100437 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000438 resp.close()
439
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100440 # Various read sizes
441 for n in range(1, 12):
442 sock = FakeSocket(chunked_start + '0\r\n')
443 resp = client.HTTPResponse(sock, method="GET")
444 resp.begin()
445 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
446 resp.close()
447
Christian Heimesa612dc02008-02-24 13:08:18 +0000448 for x in ('', 'foo\r\n'):
449 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000450 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000451 resp.begin()
452 try:
453 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000454 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100455 self.assertEqual(i.partial, expected)
456 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
457 self.assertEqual(repr(i), expected_message)
458 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000459 else:
460 self.fail('IncompleteRead expected')
461 finally:
462 resp.close()
463
Antoine Pitrou38d96432011-12-06 22:33:57 +0100464 def test_readinto_chunked(self):
465 chunked_start = (
466 'HTTP/1.1 200 OK\r\n'
467 'Transfer-Encoding: chunked\r\n\r\n'
468 'a\r\n'
469 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100470 '3\r\n'
471 'd! \r\n'
472 '8\r\n'
473 'and now \r\n'
474 '22\r\n'
475 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100476 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100477 expected = b'hello world! and now for something completely different'
478 nexpected = len(expected)
479 b = bytearray(128)
480
Antoine Pitrou38d96432011-12-06 22:33:57 +0100481 sock = FakeSocket(chunked_start + '0\r\n')
482 resp = client.HTTPResponse(sock, method="GET")
483 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100484 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100485 self.assertEqual(b[:nexpected], expected)
486 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100487 resp.close()
488
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100489 # Various read sizes
490 for n in range(1, 12):
491 sock = FakeSocket(chunked_start + '0\r\n')
492 resp = client.HTTPResponse(sock, method="GET")
493 resp.begin()
494 m = memoryview(b)
495 i = resp.readinto(m[0:n])
496 i += resp.readinto(m[i:n + i])
497 i += resp.readinto(m[i:])
498 self.assertEqual(b[:nexpected], expected)
499 self.assertEqual(i, nexpected)
500 resp.close()
501
Antoine Pitrou38d96432011-12-06 22:33:57 +0100502 for x in ('', 'foo\r\n'):
503 sock = FakeSocket(chunked_start + x)
504 resp = client.HTTPResponse(sock, method="GET")
505 resp.begin()
506 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100507 n = resp.readinto(b)
508 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100509 self.assertEqual(i.partial, expected)
510 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
511 self.assertEqual(repr(i), expected_message)
512 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100513 else:
514 self.fail('IncompleteRead expected')
515 finally:
516 resp.close()
517
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000518 def test_chunked_head(self):
519 chunked_start = (
520 'HTTP/1.1 200 OK\r\n'
521 'Transfer-Encoding: chunked\r\n\r\n'
522 'a\r\n'
523 'hello world\r\n'
524 '1\r\n'
525 'd\r\n'
526 )
527 sock = FakeSocket(chunked_start + '0\r\n')
528 resp = client.HTTPResponse(sock, method="HEAD")
529 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000530 self.assertEqual(resp.read(), b'')
531 self.assertEqual(resp.status, 200)
532 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000533 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200534 self.assertFalse(resp.closed)
535 resp.close()
536 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000537
Antoine Pitrou38d96432011-12-06 22:33:57 +0100538 def test_readinto_chunked_head(self):
539 chunked_start = (
540 'HTTP/1.1 200 OK\r\n'
541 'Transfer-Encoding: chunked\r\n\r\n'
542 'a\r\n'
543 'hello world\r\n'
544 '1\r\n'
545 'd\r\n'
546 )
547 sock = FakeSocket(chunked_start + '0\r\n')
548 resp = client.HTTPResponse(sock, method="HEAD")
549 resp.begin()
550 b = bytearray(5)
551 n = resp.readinto(b)
552 self.assertEqual(n, 0)
553 self.assertEqual(bytes(b), b'\x00'*5)
554 self.assertEqual(resp.status, 200)
555 self.assertEqual(resp.reason, 'OK')
556 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200557 self.assertFalse(resp.closed)
558 resp.close()
559 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100560
Christian Heimesa612dc02008-02-24 13:08:18 +0000561 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000562 sock = FakeSocket(
563 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000564 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000565 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000566 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100567 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000568
Benjamin Peterson6accb982009-03-02 22:50:25 +0000569 def test_incomplete_read(self):
570 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000571 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000572 resp.begin()
573 try:
574 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000575 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000576 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000577 self.assertEqual(repr(i),
578 "IncompleteRead(7 bytes read, 3 more expected)")
579 self.assertEqual(str(i),
580 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100581 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000582 else:
583 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000584
Jeremy Hylton636950f2009-03-28 04:34:21 +0000585 def test_epipe(self):
586 sock = EPipeSocket(
587 "HTTP/1.0 401 Authorization Required\r\n"
588 "Content-type: text/html\r\n"
589 "WWW-Authenticate: Basic realm=\"example\"\r\n",
590 b"Content-Length")
591 conn = client.HTTPConnection("example.com")
592 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200593 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000594 lambda: conn.request("PUT", "/url", "body"))
595 resp = conn.getresponse()
596 self.assertEqual(401, resp.status)
597 self.assertEqual("Basic realm=\"example\"",
598 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000599
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000600 # Test lines overflowing the max line size (_MAXLINE in http.client)
601
602 def test_overflowing_status_line(self):
603 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
604 resp = client.HTTPResponse(FakeSocket(body))
605 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
606
607 def test_overflowing_header_line(self):
608 body = (
609 'HTTP/1.1 200 OK\r\n'
610 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
611 )
612 resp = client.HTTPResponse(FakeSocket(body))
613 self.assertRaises(client.LineTooLong, resp.begin)
614
615 def test_overflowing_chunked_line(self):
616 body = (
617 'HTTP/1.1 200 OK\r\n'
618 'Transfer-Encoding: chunked\r\n\r\n'
619 + '0' * 65536 + 'a\r\n'
620 'hello world\r\n'
621 '0\r\n'
622 )
623 resp = client.HTTPResponse(FakeSocket(body))
624 resp.begin()
625 self.assertRaises(client.LineTooLong, resp.read)
626
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800627 def test_early_eof(self):
628 # Test httpresponse with no \r\n termination,
629 body = "HTTP/1.1 200 Ok"
630 sock = FakeSocket(body)
631 resp = client.HTTPResponse(sock)
632 resp.begin()
633 self.assertEqual(resp.read(), b'')
634 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200635 self.assertFalse(resp.closed)
636 resp.close()
637 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800638
Antoine Pitrou90e47742013-01-02 22:10:47 +0100639 def test_delayed_ack_opt(self):
640 # Test that Nagle/delayed_ack optimistaion works correctly.
641
642 # For small payloads, it should coalesce the body with
643 # headers, resulting in a single sendall() call
644 conn = client.HTTPConnection('example.com')
645 sock = FakeSocket(None)
646 conn.sock = sock
647 body = b'x' * (conn.mss - 1)
648 conn.request('POST', '/', body)
649 self.assertEqual(sock.sendall_calls, 1)
650
651 # For large payloads, it should send the headers and
652 # then the body, resulting in more than one sendall()
653 # call
654 conn = client.HTTPConnection('example.com')
655 sock = FakeSocket(None)
656 conn.sock = sock
657 body = b'x' * conn.mss
658 conn.request('POST', '/', body)
659 self.assertGreater(sock.sendall_calls, 1)
660
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000661class OfflineTest(TestCase):
662 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000663 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000664
Gregory P. Smithb4066372010-01-03 03:28:29 +0000665
666class SourceAddressTest(TestCase):
667 def setUp(self):
668 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
669 self.port = support.bind_port(self.serv)
670 self.source_port = support.find_unused_port()
671 self.serv.listen(5)
672 self.conn = None
673
674 def tearDown(self):
675 if self.conn:
676 self.conn.close()
677 self.conn = None
678 self.serv.close()
679 self.serv = None
680
681 def testHTTPConnectionSourceAddress(self):
682 self.conn = client.HTTPConnection(HOST, self.port,
683 source_address=('', self.source_port))
684 self.conn.connect()
685 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
686
687 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
688 'http.client.HTTPSConnection not defined')
689 def testHTTPSConnectionSourceAddress(self):
690 self.conn = client.HTTPSConnection(HOST, self.port,
691 source_address=('', self.source_port))
692 # We don't test anything here other the constructor not barfing as
693 # this code doesn't deal with setting up an active running SSL server
694 # for an ssl_wrapped connect() to actually return from.
695
696
Guido van Rossumd8faa362007-04-27 19:54:29 +0000697class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000698 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000699
700 def setUp(self):
701 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000702 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000703 self.serv.listen(5)
704
705 def tearDown(self):
706 self.serv.close()
707 self.serv = None
708
709 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000710 # This will prove that the timeout gets through HTTPConnection
711 # and into the socket.
712
Georg Brandlf78e02b2008-06-10 17:40:04 +0000713 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000714 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000715 socket.setdefaulttimeout(30)
716 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000717 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000718 httpConn.connect()
719 finally:
720 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000721 self.assertEqual(httpConn.sock.gettimeout(), 30)
722 httpConn.close()
723
Georg Brandlf78e02b2008-06-10 17:40:04 +0000724 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000725 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000726 socket.setdefaulttimeout(30)
727 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000728 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000729 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730 httpConn.connect()
731 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000732 socket.setdefaulttimeout(None)
733 self.assertEqual(httpConn.sock.gettimeout(), None)
734 httpConn.close()
735
736 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000737 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000738 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000739 self.assertEqual(httpConn.sock.gettimeout(), 30)
740 httpConn.close()
741
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000742
743class HTTPSTest(TestCase):
744
745 def setUp(self):
746 if not hasattr(client, 'HTTPSConnection'):
747 self.skipTest('ssl support required')
748
749 def make_server(self, certfile):
750 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100751 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000752
753 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000754 # simple test to check it's storing the timeout
755 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
756 self.assertEqual(h.timeout, 30)
757
758 def _check_svn_python_org(self, resp):
759 # Just a simple check that everything went fine
760 server_string = resp.getheader('server')
761 self.assertIn('Apache', server_string)
762
763 def test_networked(self):
764 # Default settings: no cert verification is done
765 support.requires('network')
766 with support.transient_internet('svn.python.org'):
767 h = client.HTTPSConnection('svn.python.org', 443)
768 h.request('GET', '/')
769 resp = h.getresponse()
770 self._check_svn_python_org(resp)
771
772 def test_networked_good_cert(self):
773 # We feed a CA cert that validates the server's cert
774 import ssl
775 support.requires('network')
776 with support.transient_internet('svn.python.org'):
777 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
778 context.verify_mode = ssl.CERT_REQUIRED
779 context.load_verify_locations(CACERT_svn_python_org)
780 h = client.HTTPSConnection('svn.python.org', 443, context=context)
781 h.request('GET', '/')
782 resp = h.getresponse()
783 self._check_svn_python_org(resp)
784
785 def test_networked_bad_cert(self):
786 # We feed a "CA" cert that is unrelated to the server's cert
787 import ssl
788 support.requires('network')
789 with support.transient_internet('svn.python.org'):
790 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
791 context.verify_mode = ssl.CERT_REQUIRED
792 context.load_verify_locations(CERT_localhost)
793 h = client.HTTPSConnection('svn.python.org', 443, context=context)
794 with self.assertRaises(ssl.SSLError):
795 h.request('GET', '/')
796
797 def test_local_good_hostname(self):
798 # The (valid) cert validates the HTTP hostname
799 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700800 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000801 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
802 context.verify_mode = ssl.CERT_REQUIRED
803 context.load_verify_locations(CERT_localhost)
804 h = client.HTTPSConnection('localhost', server.port, context=context)
805 h.request('GET', '/nonexistent')
806 resp = h.getresponse()
807 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700808 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000809
810 def test_local_bad_hostname(self):
811 # The (valid) cert doesn't validate the HTTP hostname
812 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700813 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000814 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
815 context.verify_mode = ssl.CERT_REQUIRED
816 context.load_verify_locations(CERT_fakehostname)
817 h = client.HTTPSConnection('localhost', server.port, context=context)
818 with self.assertRaises(ssl.CertificateError):
819 h.request('GET', '/')
820 # Same with explicit check_hostname=True
821 h = client.HTTPSConnection('localhost', server.port, context=context,
822 check_hostname=True)
823 with self.assertRaises(ssl.CertificateError):
824 h.request('GET', '/')
825 # With check_hostname=False, the mismatching is ignored
826 h = client.HTTPSConnection('localhost', server.port, context=context,
827 check_hostname=False)
828 h.request('GET', '/nonexistent')
829 resp = h.getresponse()
830 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700831 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000832
Petri Lehtinene119c402011-10-26 21:29:15 +0300833 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
834 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200835 def test_host_port(self):
836 # Check invalid host_port
837
838 for hp in ("www.python.org:abc", "user:password@www.python.org"):
839 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
840
841 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
842 "fe80::207:e9ff:fe9b", 8000),
843 ("www.python.org:443", "www.python.org", 443),
844 ("www.python.org:", "www.python.org", 443),
845 ("www.python.org", "www.python.org", 443),
846 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
847 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
848 443)):
849 c = client.HTTPSConnection(hp)
850 self.assertEqual(h, c.host)
851 self.assertEqual(p, c.port)
852
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000853
Jeremy Hylton236654b2009-03-27 20:24:34 +0000854class RequestBodyTest(TestCase):
855 """Test cases where a request includes a message body."""
856
857 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000858 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000859 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000860 self.conn.sock = self.sock
861
862 def get_headers_and_fp(self):
863 f = io.BytesIO(self.sock.data)
864 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000865 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000866 return message, f
867
868 def test_manual_content_length(self):
869 # Set an incorrect content-length so that we can verify that
870 # it will not be over-ridden by the library.
871 self.conn.request("PUT", "/url", "body",
872 {"Content-Length": "42"})
873 message, f = self.get_headers_and_fp()
874 self.assertEqual("42", message.get("content-length"))
875 self.assertEqual(4, len(f.read()))
876
877 def test_ascii_body(self):
878 self.conn.request("PUT", "/url", "body")
879 message, f = self.get_headers_and_fp()
880 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000881 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000882 self.assertEqual("4", message.get("content-length"))
883 self.assertEqual(b'body', f.read())
884
885 def test_latin1_body(self):
886 self.conn.request("PUT", "/url", "body\xc1")
887 message, f = self.get_headers_and_fp()
888 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000889 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000890 self.assertEqual("5", message.get("content-length"))
891 self.assertEqual(b'body\xc1', f.read())
892
893 def test_bytes_body(self):
894 self.conn.request("PUT", "/url", b"body\xc1")
895 message, f = self.get_headers_and_fp()
896 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000897 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000898 self.assertEqual("5", message.get("content-length"))
899 self.assertEqual(b'body\xc1', f.read())
900
901 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200902 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000903 with open(support.TESTFN, "w") as f:
904 f.write("body")
905 with open(support.TESTFN) as f:
906 self.conn.request("PUT", "/url", f)
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())
Brett Cannon77b7de62010-10-29 23:31:11 +0000910 self.assertEqual("4", message.get("content-length"))
911 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000912
913 def test_binary_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, "wb") as f:
916 f.write(b"body\xc1")
917 with open(support.TESTFN, "rb") 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("5", message.get("content-length"))
923 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000924
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000925
926class HTTPResponseTest(TestCase):
927
928 def setUp(self):
929 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
930 second-value\r\n\r\nText"
931 sock = FakeSocket(body)
932 self.resp = client.HTTPResponse(sock)
933 self.resp.begin()
934
935 def test_getting_header(self):
936 header = self.resp.getheader('My-Header')
937 self.assertEqual(header, 'first-value, second-value')
938
939 header = self.resp.getheader('My-Header', 'some default')
940 self.assertEqual(header, 'first-value, second-value')
941
942 def test_getting_nonexistent_header_with_string_default(self):
943 header = self.resp.getheader('No-Such-Header', 'default-value')
944 self.assertEqual(header, 'default-value')
945
946 def test_getting_nonexistent_header_with_iterable_default(self):
947 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
948 self.assertEqual(header, 'default, values')
949
950 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
951 self.assertEqual(header, 'default, values')
952
953 def test_getting_nonexistent_header_without_default(self):
954 header = self.resp.getheader('No-Such-Header')
955 self.assertEqual(header, None)
956
957 def test_getting_header_defaultint(self):
958 header = self.resp.getheader('No-Such-Header',default=42)
959 self.assertEqual(header, 42)
960
Jeremy Hylton2c178252004-08-07 16:28:14 +0000961def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000962 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000963 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000964 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000965
Thomas Wouters89f507f2006-12-13 04:49:30 +0000966if __name__ == '__main__':
967 test_main()