blob: db123dcb56f7b4a4dd83f47a7735d48a9b51d0e1 [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''
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000030
Jeremy Hylton2c178252004-08-07 16:28:14 +000031 def sendall(self, data):
Thomas Wouters89f507f2006-12-13 04:49:30 +000032 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000033
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000034 def makefile(self, mode, bufsize=None):
35 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000036 raise client.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000037 return self.fileclass(self.text)
38
Jeremy Hylton636950f2009-03-28 04:34:21 +000039class EPipeSocket(FakeSocket):
40
41 def __init__(self, text, pipe_trigger):
42 # When sendall() is called with pipe_trigger, raise EPIPE.
43 FakeSocket.__init__(self, text)
44 self.pipe_trigger = pipe_trigger
45
46 def sendall(self, data):
47 if self.pipe_trigger in data:
48 raise socket.error(errno.EPIPE, "gotcha")
49 self.data += data
50
51 def close(self):
52 pass
53
Jeremy Hylton8fff7922007-08-03 20:56:14 +000054class NoEOFStringIO(io.BytesIO):
Jeremy Hylton121d34a2003-07-08 12:36:58 +000055 """Like StringIO, but raises AssertionError on EOF.
56
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000057 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000058 more from the underlying file than it should.
59 """
60 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000061 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000062 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000063 raise AssertionError('caller tried to read past EOF')
64 return data
65
66 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000067 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000068 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000069 raise AssertionError('caller tried to read past EOF')
70 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000071
Jeremy Hylton2c178252004-08-07 16:28:14 +000072class HeaderTests(TestCase):
73 def test_auto_headers(self):
74 # Some headers are added automatically, but should not be added by
75 # .request() if they are explicitly set.
76
Jeremy Hylton2c178252004-08-07 16:28:14 +000077 class HeaderCountingBuffer(list):
78 def __init__(self):
79 self.count = {}
80 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000081 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000082 if len(kv) > 1:
83 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000084 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000085 self.count.setdefault(lcKey, 0)
86 self.count[lcKey] += 1
87 list.append(self, item)
88
89 for explicit_header in True, False:
90 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000091 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +000092 conn.sock = FakeSocket('blahblahblah')
93 conn._buffer = HeaderCountingBuffer()
94
95 body = 'spamspamspam'
96 headers = {}
97 if explicit_header:
98 headers[header] = str(len(body))
99 conn.request('POST', '/', body, headers)
100 self.assertEqual(conn._buffer.count[header.lower()], 1)
101
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800102 def test_content_length_0(self):
103
104 class ContentLengthChecker(list):
105 def __init__(self):
106 list.__init__(self)
107 self.content_length = None
108 def append(self, item):
109 kv = item.split(b':', 1)
110 if len(kv) > 1 and kv[0].lower() == b'content-length':
111 self.content_length = kv[1].strip()
112 list.append(self, item)
113
114 # POST with empty body
115 conn = client.HTTPConnection('example.com')
116 conn.sock = FakeSocket(None)
117 conn._buffer = ContentLengthChecker()
118 conn.request('POST', '/', '')
119 self.assertEqual(conn._buffer.content_length, b'0',
120 'Header Content-Length not set')
121
122 # PUT request with empty body
123 conn = client.HTTPConnection('example.com')
124 conn.sock = FakeSocket(None)
125 conn._buffer = ContentLengthChecker()
126 conn.request('PUT', '/', '')
127 self.assertEqual(conn._buffer.content_length, b'0',
128 'Header Content-Length not set')
129
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000130 def test_putheader(self):
131 conn = client.HTTPConnection('example.com')
132 conn.sock = FakeSocket(None)
133 conn.putrequest('GET','/')
134 conn.putheader('Content-length', 42)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000135 self.assertTrue(b'Content-length: 42' in conn._buffer)
136
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000137 def test_ipv6host_header(self):
138 # Default host header on IPv6 transaction should wrapped by [] if
139 # its actual IPv6 address
140 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
141 b'Accept-Encoding: identity\r\n\r\n'
142 conn = client.HTTPConnection('[2001::]:81')
143 sock = FakeSocket('')
144 conn.sock = sock
145 conn.request('GET', '/foo')
146 self.assertTrue(sock.data.startswith(expected))
147
148 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
149 b'Accept-Encoding: identity\r\n\r\n'
150 conn = client.HTTPConnection('[2001:102A::]')
151 sock = FakeSocket('')
152 conn.sock = sock
153 conn.request('GET', '/foo')
154 self.assertTrue(sock.data.startswith(expected))
155
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000156
Thomas Wouters89f507f2006-12-13 04:49:30 +0000157class BasicTest(TestCase):
158 def test_status_lines(self):
159 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000160
Thomas Wouters89f507f2006-12-13 04:49:30 +0000161 body = "HTTP/1.1 200 Ok\r\n\r\nText"
162 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000163 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000164 resp.begin()
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000165 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000166 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200167 self.assertFalse(resp.closed)
168 resp.close()
169 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000170
Thomas Wouters89f507f2006-12-13 04:49:30 +0000171 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
172 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000173 resp = client.HTTPResponse(sock)
174 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000175
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000176 def test_bad_status_repr(self):
177 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000178 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000179
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000180 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100181 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000182 # same behaviour than when we read the whole thing with read()
183 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
184 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000185 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000186 resp.begin()
187 self.assertEqual(resp.read(2), b'Te')
188 self.assertFalse(resp.isclosed())
189 self.assertEqual(resp.read(2), b'xt')
190 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200191 self.assertFalse(resp.closed)
192 resp.close()
193 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000194
Antoine Pitrou38d96432011-12-06 22:33:57 +0100195 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100196 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100197 # same behaviour than when we read the whole thing with read()
198 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
199 sock = FakeSocket(body)
200 resp = client.HTTPResponse(sock)
201 resp.begin()
202 b = bytearray(2)
203 n = resp.readinto(b)
204 self.assertEqual(n, 2)
205 self.assertEqual(bytes(b), b'Te')
206 self.assertFalse(resp.isclosed())
207 n = resp.readinto(b)
208 self.assertEqual(n, 2)
209 self.assertEqual(bytes(b), b'xt')
210 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200211 self.assertFalse(resp.closed)
212 resp.close()
213 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100214
Antoine Pitrou084daa22012-12-15 19:11:54 +0100215 def test_partial_reads_no_content_length(self):
216 # when no length is present, the socket should be gracefully closed when
217 # all data was read
218 body = "HTTP/1.1 200 Ok\r\n\r\nText"
219 sock = FakeSocket(body)
220 resp = client.HTTPResponse(sock)
221 resp.begin()
222 self.assertEqual(resp.read(2), b'Te')
223 self.assertFalse(resp.isclosed())
224 self.assertEqual(resp.read(2), b'xt')
225 self.assertEqual(resp.read(1), b'')
226 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200227 self.assertFalse(resp.closed)
228 resp.close()
229 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100230
Antoine Pitroud20e7742012-12-15 19:22:30 +0100231 def test_partial_readintos_no_content_length(self):
232 # when no length is present, the socket should be gracefully closed when
233 # all data was read
234 body = "HTTP/1.1 200 Ok\r\n\r\nText"
235 sock = FakeSocket(body)
236 resp = client.HTTPResponse(sock)
237 resp.begin()
238 b = bytearray(2)
239 n = resp.readinto(b)
240 self.assertEqual(n, 2)
241 self.assertEqual(bytes(b), b'Te')
242 self.assertFalse(resp.isclosed())
243 n = resp.readinto(b)
244 self.assertEqual(n, 2)
245 self.assertEqual(bytes(b), b'xt')
246 n = resp.readinto(b)
247 self.assertEqual(n, 0)
248 self.assertTrue(resp.isclosed())
249
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100250 def test_partial_reads_incomplete_body(self):
251 # if the server shuts down the connection before the whole
252 # content-length is delivered, the socket is gracefully closed
253 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
254 sock = FakeSocket(body)
255 resp = client.HTTPResponse(sock)
256 resp.begin()
257 self.assertEqual(resp.read(2), b'Te')
258 self.assertFalse(resp.isclosed())
259 self.assertEqual(resp.read(2), b'xt')
260 self.assertEqual(resp.read(1), b'')
261 self.assertTrue(resp.isclosed())
262
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100263 def test_partial_readintos_incomplete_body(self):
264 # if the server shuts down the connection before the whole
265 # content-length is delivered, the socket is gracefully closed
266 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
267 sock = FakeSocket(body)
268 resp = client.HTTPResponse(sock)
269 resp.begin()
270 b = bytearray(2)
271 n = resp.readinto(b)
272 self.assertEqual(n, 2)
273 self.assertEqual(bytes(b), b'Te')
274 self.assertFalse(resp.isclosed())
275 n = resp.readinto(b)
276 self.assertEqual(n, 2)
277 self.assertEqual(bytes(b), b'xt')
278 n = resp.readinto(b)
279 self.assertEqual(n, 0)
280 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200281 self.assertFalse(resp.closed)
282 resp.close()
283 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100284
Thomas Wouters89f507f2006-12-13 04:49:30 +0000285 def test_host_port(self):
286 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000287
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200288 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000289 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000290
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000291 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
292 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000293 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200294 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000295 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200296 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
297 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000298 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000299 self.assertEqual(h, c.host)
300 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000301
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 def test_response_headers(self):
303 # test response with multiple message headers with the same field name.
304 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000305 'Set-Cookie: Customer="WILE_E_COYOTE"; '
306 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000307 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
308 ' Path="/acme"\r\n'
309 '\r\n'
310 'No body\r\n')
311 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
312 ', '
313 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
314 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000315 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000316 r.begin()
317 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000318 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000319
Thomas Wouters89f507f2006-12-13 04:49:30 +0000320 def test_read_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)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000328 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000329 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000330 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000331 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000332
Antoine Pitrou38d96432011-12-06 22:33:57 +0100333 def test_readinto_head(self):
334 # Test that the library doesn't attempt to read any data
335 # from a HEAD request. (Tickles SF bug #622042.)
336 sock = FakeSocket(
337 'HTTP/1.1 200 OK\r\n'
338 'Content-Length: 14432\r\n'
339 '\r\n',
340 NoEOFStringIO)
341 resp = client.HTTPResponse(sock, method="HEAD")
342 resp.begin()
343 b = bytearray(5)
344 if resp.readinto(b) != 0:
345 self.fail("Did not expect response from HEAD request")
346 self.assertEqual(bytes(b), b'\x00'*5)
347
Thomas Wouters89f507f2006-12-13 04:49:30 +0000348 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000349 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
350 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000351
Brett Cannon77b7de62010-10-29 23:31:11 +0000352 with open(__file__, 'rb') as body:
353 conn = client.HTTPConnection('example.com')
354 sock = FakeSocket(body)
355 conn.sock = sock
356 conn.request('GET', '/foo', body)
357 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
358 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000359
Antoine Pitrouead1d622009-09-29 18:44:53 +0000360 def test_send(self):
361 expected = b'this is a test this is only a test'
362 conn = client.HTTPConnection('example.com')
363 sock = FakeSocket(None)
364 conn.sock = sock
365 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000366 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000367 sock.data = b''
368 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000369 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000370 sock.data = b''
371 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000372 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000373
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000374 def test_send_iter(self):
375 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
376 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
377 b'\r\nonetwothree'
378
379 def body():
380 yield b"one"
381 yield b"two"
382 yield b"three"
383
384 conn = client.HTTPConnection('example.com')
385 sock = FakeSocket("")
386 conn.sock = sock
387 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000388 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000389
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800390 def test_send_type_error(self):
391 # See: Issue #12676
392 conn = client.HTTPConnection('example.com')
393 conn.sock = FakeSocket('')
394 with self.assertRaises(TypeError):
395 conn.request('POST', 'test', conn)
396
Christian Heimesa612dc02008-02-24 13:08:18 +0000397 def test_chunked(self):
398 chunked_start = (
399 'HTTP/1.1 200 OK\r\n'
400 'Transfer-Encoding: chunked\r\n\r\n'
401 'a\r\n'
402 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100403 '3\r\n'
404 'd! \r\n'
405 '8\r\n'
406 'and now \r\n'
407 '22\r\n'
408 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000409 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100410 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000411 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000412 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000413 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100414 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000415 resp.close()
416
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100417 # Various read sizes
418 for n in range(1, 12):
419 sock = FakeSocket(chunked_start + '0\r\n')
420 resp = client.HTTPResponse(sock, method="GET")
421 resp.begin()
422 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
423 resp.close()
424
Christian Heimesa612dc02008-02-24 13:08:18 +0000425 for x in ('', 'foo\r\n'):
426 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000427 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000428 resp.begin()
429 try:
430 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000431 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100432 self.assertEqual(i.partial, expected)
433 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
434 self.assertEqual(repr(i), expected_message)
435 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000436 else:
437 self.fail('IncompleteRead expected')
438 finally:
439 resp.close()
440
Antoine Pitrou38d96432011-12-06 22:33:57 +0100441 def test_readinto_chunked(self):
442 chunked_start = (
443 'HTTP/1.1 200 OK\r\n'
444 'Transfer-Encoding: chunked\r\n\r\n'
445 'a\r\n'
446 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100447 '3\r\n'
448 'd! \r\n'
449 '8\r\n'
450 'and now \r\n'
451 '22\r\n'
452 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100453 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100454 expected = b'hello world! and now for something completely different'
455 nexpected = len(expected)
456 b = bytearray(128)
457
Antoine Pitrou38d96432011-12-06 22:33:57 +0100458 sock = FakeSocket(chunked_start + '0\r\n')
459 resp = client.HTTPResponse(sock, method="GET")
460 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100461 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100462 self.assertEqual(b[:nexpected], expected)
463 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100464 resp.close()
465
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100466 # Various read sizes
467 for n in range(1, 12):
468 sock = FakeSocket(chunked_start + '0\r\n')
469 resp = client.HTTPResponse(sock, method="GET")
470 resp.begin()
471 m = memoryview(b)
472 i = resp.readinto(m[0:n])
473 i += resp.readinto(m[i:n + i])
474 i += resp.readinto(m[i:])
475 self.assertEqual(b[:nexpected], expected)
476 self.assertEqual(i, nexpected)
477 resp.close()
478
Antoine Pitrou38d96432011-12-06 22:33:57 +0100479 for x in ('', 'foo\r\n'):
480 sock = FakeSocket(chunked_start + x)
481 resp = client.HTTPResponse(sock, method="GET")
482 resp.begin()
483 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100484 n = resp.readinto(b)
485 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100486 self.assertEqual(i.partial, expected)
487 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
488 self.assertEqual(repr(i), expected_message)
489 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100490 else:
491 self.fail('IncompleteRead expected')
492 finally:
493 resp.close()
494
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000495 def test_chunked_head(self):
496 chunked_start = (
497 'HTTP/1.1 200 OK\r\n'
498 'Transfer-Encoding: chunked\r\n\r\n'
499 'a\r\n'
500 'hello world\r\n'
501 '1\r\n'
502 'd\r\n'
503 )
504 sock = FakeSocket(chunked_start + '0\r\n')
505 resp = client.HTTPResponse(sock, method="HEAD")
506 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000507 self.assertEqual(resp.read(), b'')
508 self.assertEqual(resp.status, 200)
509 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000510 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200511 self.assertFalse(resp.closed)
512 resp.close()
513 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000514
Antoine Pitrou38d96432011-12-06 22:33:57 +0100515 def test_readinto_chunked_head(self):
516 chunked_start = (
517 'HTTP/1.1 200 OK\r\n'
518 'Transfer-Encoding: chunked\r\n\r\n'
519 'a\r\n'
520 'hello world\r\n'
521 '1\r\n'
522 'd\r\n'
523 )
524 sock = FakeSocket(chunked_start + '0\r\n')
525 resp = client.HTTPResponse(sock, method="HEAD")
526 resp.begin()
527 b = bytearray(5)
528 n = resp.readinto(b)
529 self.assertEqual(n, 0)
530 self.assertEqual(bytes(b), b'\x00'*5)
531 self.assertEqual(resp.status, 200)
532 self.assertEqual(resp.reason, 'OK')
533 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200534 self.assertFalse(resp.closed)
535 resp.close()
536 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100537
Christian Heimesa612dc02008-02-24 13:08:18 +0000538 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000539 sock = FakeSocket(
540 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000541 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000542 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000543 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100544 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000545
Benjamin Peterson6accb982009-03-02 22:50:25 +0000546 def test_incomplete_read(self):
547 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000548 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000549 resp.begin()
550 try:
551 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000552 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000553 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000554 self.assertEqual(repr(i),
555 "IncompleteRead(7 bytes read, 3 more expected)")
556 self.assertEqual(str(i),
557 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100558 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000559 else:
560 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000561
Jeremy Hylton636950f2009-03-28 04:34:21 +0000562 def test_epipe(self):
563 sock = EPipeSocket(
564 "HTTP/1.0 401 Authorization Required\r\n"
565 "Content-type: text/html\r\n"
566 "WWW-Authenticate: Basic realm=\"example\"\r\n",
567 b"Content-Length")
568 conn = client.HTTPConnection("example.com")
569 conn.sock = sock
570 self.assertRaises(socket.error,
571 lambda: conn.request("PUT", "/url", "body"))
572 resp = conn.getresponse()
573 self.assertEqual(401, resp.status)
574 self.assertEqual("Basic realm=\"example\"",
575 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000576
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000577 # Test lines overflowing the max line size (_MAXLINE in http.client)
578
579 def test_overflowing_status_line(self):
580 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
581 resp = client.HTTPResponse(FakeSocket(body))
582 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
583
584 def test_overflowing_header_line(self):
585 body = (
586 'HTTP/1.1 200 OK\r\n'
587 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
588 )
589 resp = client.HTTPResponse(FakeSocket(body))
590 self.assertRaises(client.LineTooLong, resp.begin)
591
592 def test_overflowing_chunked_line(self):
593 body = (
594 'HTTP/1.1 200 OK\r\n'
595 'Transfer-Encoding: chunked\r\n\r\n'
596 + '0' * 65536 + 'a\r\n'
597 'hello world\r\n'
598 '0\r\n'
599 )
600 resp = client.HTTPResponse(FakeSocket(body))
601 resp.begin()
602 self.assertRaises(client.LineTooLong, resp.read)
603
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800604 def test_early_eof(self):
605 # Test httpresponse with no \r\n termination,
606 body = "HTTP/1.1 200 Ok"
607 sock = FakeSocket(body)
608 resp = client.HTTPResponse(sock)
609 resp.begin()
610 self.assertEqual(resp.read(), b'')
611 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200612 self.assertFalse(resp.closed)
613 resp.close()
614 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800615
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
706 return make_https_server(self, 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()