blob: 31c0b6a6cae517742a16befa3d2d296349f26e52 [file] [log] [blame]
Jeremy Hylton636950f2009-03-28 04:34:21 +00001import errno
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002from http import client
Jeremy Hylton8fff7922007-08-03 20:56:14 +00003import io
Antoine Pitrou803e6d62010-10-13 10:36:15 +00004import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00005import array
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import socket
Jeremy Hylton121d34a2003-07-08 12:36:58 +00007
Gregory P. Smithb4066372010-01-03 03:28:29 +00008import unittest
9TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000010
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000012
Antoine Pitrou803e6d62010-10-13 10:36:15 +000013here = os.path.dirname(__file__)
14# Self-signed cert file for 'localhost'
15CERT_localhost = os.path.join(here, 'keycert.pem')
16# Self-signed cert file for 'fakehostname'
17CERT_fakehostname = os.path.join(here, 'keycert2.pem')
18# Root cert file (CA) for svn.python.org's cert
19CACERT_svn_python_org = os.path.join(here, 'https_svn_python_org_root.pem')
20
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000022
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000023class FakeSocket:
Jeremy Hylton8fff7922007-08-03 20:56:14 +000024 def __init__(self, text, fileclass=io.BytesIO):
25 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000026 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000027 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000028 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000029 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010030 self.sendall_calls = 0
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000031
Jeremy Hylton2c178252004-08-07 16:28:14 +000032 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010033 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000035
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000036 def makefile(self, mode, bufsize=None):
37 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000038 raise client.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000039 return self.fileclass(self.text)
40
Jeremy Hylton636950f2009-03-28 04:34:21 +000041class EPipeSocket(FakeSocket):
42
43 def __init__(self, text, pipe_trigger):
44 # When sendall() is called with pipe_trigger, raise EPIPE.
45 FakeSocket.__init__(self, text)
46 self.pipe_trigger = pipe_trigger
47
48 def sendall(self, data):
49 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020050 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000051 self.data += data
52
53 def close(self):
54 pass
55
Serhiy Storchaka50254c52013-08-29 11:35:43 +030056class NoEOFBytesIO(io.BytesIO):
57 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000058
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000059 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000060 more from the underlying file than it should.
61 """
62 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000063 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000064 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000065 raise AssertionError('caller tried to read past EOF')
66 return data
67
68 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000069 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000070 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000071 raise AssertionError('caller tried to read past EOF')
72 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000073
Jeremy Hylton2c178252004-08-07 16:28:14 +000074class HeaderTests(TestCase):
75 def test_auto_headers(self):
76 # Some headers are added automatically, but should not be added by
77 # .request() if they are explicitly set.
78
Jeremy Hylton2c178252004-08-07 16:28:14 +000079 class HeaderCountingBuffer(list):
80 def __init__(self):
81 self.count = {}
82 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000083 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000084 if len(kv) > 1:
85 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000086 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000087 self.count.setdefault(lcKey, 0)
88 self.count[lcKey] += 1
89 list.append(self, item)
90
91 for explicit_header in True, False:
92 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000093 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +000094 conn.sock = FakeSocket('blahblahblah')
95 conn._buffer = HeaderCountingBuffer()
96
97 body = 'spamspamspam'
98 headers = {}
99 if explicit_header:
100 headers[header] = str(len(body))
101 conn.request('POST', '/', body, headers)
102 self.assertEqual(conn._buffer.count[header.lower()], 1)
103
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800104 def test_content_length_0(self):
105
106 class ContentLengthChecker(list):
107 def __init__(self):
108 list.__init__(self)
109 self.content_length = None
110 def append(self, item):
111 kv = item.split(b':', 1)
112 if len(kv) > 1 and kv[0].lower() == b'content-length':
113 self.content_length = kv[1].strip()
114 list.append(self, item)
115
116 # POST with empty body
117 conn = client.HTTPConnection('example.com')
118 conn.sock = FakeSocket(None)
119 conn._buffer = ContentLengthChecker()
120 conn.request('POST', '/', '')
121 self.assertEqual(conn._buffer.content_length, b'0',
122 'Header Content-Length not set')
123
124 # PUT request with empty body
125 conn = client.HTTPConnection('example.com')
126 conn.sock = FakeSocket(None)
127 conn._buffer = ContentLengthChecker()
128 conn.request('PUT', '/', '')
129 self.assertEqual(conn._buffer.content_length, b'0',
130 'Header Content-Length not set')
131
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000132 def test_putheader(self):
133 conn = client.HTTPConnection('example.com')
134 conn.sock = FakeSocket(None)
135 conn.putrequest('GET','/')
136 conn.putheader('Content-length', 42)
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',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300329 NoEOFBytesIO)
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',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300342 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100343 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
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100350 def test_too_many_headers(self):
351 headers = '\r\n'.join('Header%d: foo' % i
352 for i in range(client._MAXHEADERS + 1)) + '\r\n'
353 text = ('HTTP/1.1 200 OK\r\n' + headers)
354 s = FakeSocket(text)
355 r = client.HTTPResponse(s)
356 self.assertRaisesRegex(client.HTTPException,
357 r"got more than \d+ headers", r.begin)
358
Thomas Wouters89f507f2006-12-13 04:49:30 +0000359 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000360 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
361 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000362
Brett Cannon77b7de62010-10-29 23:31:11 +0000363 with open(__file__, 'rb') as body:
364 conn = client.HTTPConnection('example.com')
365 sock = FakeSocket(body)
366 conn.sock = sock
367 conn.request('GET', '/foo', body)
368 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
369 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000370
Antoine Pitrouead1d622009-09-29 18:44:53 +0000371 def test_send(self):
372 expected = b'this is a test this is only a test'
373 conn = client.HTTPConnection('example.com')
374 sock = FakeSocket(None)
375 conn.sock = sock
376 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000377 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000378 sock.data = b''
379 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000380 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000381 sock.data = b''
382 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000383 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000384
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300385 def test_send_updating_file(self):
386 def data():
387 yield 'data'
388 yield None
389 yield 'data_two'
390
391 class UpdatingFile():
392 mode = 'r'
393 d = data()
394 def read(self, blocksize=-1):
395 return self.d.__next__()
396
397 expected = b'data'
398
399 conn = client.HTTPConnection('example.com')
400 sock = FakeSocket("")
401 conn.sock = sock
402 conn.send(UpdatingFile())
403 self.assertEqual(sock.data, expected)
404
405
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000406 def test_send_iter(self):
407 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
408 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
409 b'\r\nonetwothree'
410
411 def body():
412 yield b"one"
413 yield b"two"
414 yield b"three"
415
416 conn = client.HTTPConnection('example.com')
417 sock = FakeSocket("")
418 conn.sock = sock
419 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000420 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000421
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800422 def test_send_type_error(self):
423 # See: Issue #12676
424 conn = client.HTTPConnection('example.com')
425 conn.sock = FakeSocket('')
426 with self.assertRaises(TypeError):
427 conn.request('POST', 'test', conn)
428
Christian Heimesa612dc02008-02-24 13:08:18 +0000429 def test_chunked(self):
430 chunked_start = (
431 'HTTP/1.1 200 OK\r\n'
432 'Transfer-Encoding: chunked\r\n\r\n'
433 'a\r\n'
434 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100435 '3\r\n'
436 'd! \r\n'
437 '8\r\n'
438 'and now \r\n'
439 '22\r\n'
440 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000441 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100442 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000443 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000444 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000445 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100446 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000447 resp.close()
448
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100449 # Various read sizes
450 for n in range(1, 12):
451 sock = FakeSocket(chunked_start + '0\r\n')
452 resp = client.HTTPResponse(sock, method="GET")
453 resp.begin()
454 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
455 resp.close()
456
Christian Heimesa612dc02008-02-24 13:08:18 +0000457 for x in ('', 'foo\r\n'):
458 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000459 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000460 resp.begin()
461 try:
462 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000463 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100464 self.assertEqual(i.partial, expected)
465 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
466 self.assertEqual(repr(i), expected_message)
467 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000468 else:
469 self.fail('IncompleteRead expected')
470 finally:
471 resp.close()
472
Antoine Pitrou38d96432011-12-06 22:33:57 +0100473 def test_readinto_chunked(self):
474 chunked_start = (
475 'HTTP/1.1 200 OK\r\n'
476 'Transfer-Encoding: chunked\r\n\r\n'
477 'a\r\n'
478 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100479 '3\r\n'
480 'd! \r\n'
481 '8\r\n'
482 'and now \r\n'
483 '22\r\n'
484 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100485 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100486 expected = b'hello world! and now for something completely different'
487 nexpected = len(expected)
488 b = bytearray(128)
489
Antoine Pitrou38d96432011-12-06 22:33:57 +0100490 sock = FakeSocket(chunked_start + '0\r\n')
491 resp = client.HTTPResponse(sock, method="GET")
492 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100493 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100494 self.assertEqual(b[:nexpected], expected)
495 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100496 resp.close()
497
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100498 # Various read sizes
499 for n in range(1, 12):
500 sock = FakeSocket(chunked_start + '0\r\n')
501 resp = client.HTTPResponse(sock, method="GET")
502 resp.begin()
503 m = memoryview(b)
504 i = resp.readinto(m[0:n])
505 i += resp.readinto(m[i:n + i])
506 i += resp.readinto(m[i:])
507 self.assertEqual(b[:nexpected], expected)
508 self.assertEqual(i, nexpected)
509 resp.close()
510
Antoine Pitrou38d96432011-12-06 22:33:57 +0100511 for x in ('', 'foo\r\n'):
512 sock = FakeSocket(chunked_start + x)
513 resp = client.HTTPResponse(sock, method="GET")
514 resp.begin()
515 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100516 n = resp.readinto(b)
517 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100518 self.assertEqual(i.partial, expected)
519 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
520 self.assertEqual(repr(i), expected_message)
521 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100522 else:
523 self.fail('IncompleteRead expected')
524 finally:
525 resp.close()
526
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000527 def test_chunked_head(self):
528 chunked_start = (
529 'HTTP/1.1 200 OK\r\n'
530 'Transfer-Encoding: chunked\r\n\r\n'
531 'a\r\n'
532 'hello world\r\n'
533 '1\r\n'
534 'd\r\n'
535 )
536 sock = FakeSocket(chunked_start + '0\r\n')
537 resp = client.HTTPResponse(sock, method="HEAD")
538 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000539 self.assertEqual(resp.read(), b'')
540 self.assertEqual(resp.status, 200)
541 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000542 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200543 self.assertFalse(resp.closed)
544 resp.close()
545 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000546
Antoine Pitrou38d96432011-12-06 22:33:57 +0100547 def test_readinto_chunked_head(self):
548 chunked_start = (
549 'HTTP/1.1 200 OK\r\n'
550 'Transfer-Encoding: chunked\r\n\r\n'
551 'a\r\n'
552 'hello world\r\n'
553 '1\r\n'
554 'd\r\n'
555 )
556 sock = FakeSocket(chunked_start + '0\r\n')
557 resp = client.HTTPResponse(sock, method="HEAD")
558 resp.begin()
559 b = bytearray(5)
560 n = resp.readinto(b)
561 self.assertEqual(n, 0)
562 self.assertEqual(bytes(b), b'\x00'*5)
563 self.assertEqual(resp.status, 200)
564 self.assertEqual(resp.reason, 'OK')
565 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200566 self.assertFalse(resp.closed)
567 resp.close()
568 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100569
Christian Heimesa612dc02008-02-24 13:08:18 +0000570 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000571 sock = FakeSocket(
572 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000573 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000574 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000575 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100576 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000577
Benjamin Peterson6accb982009-03-02 22:50:25 +0000578 def test_incomplete_read(self):
579 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000580 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000581 resp.begin()
582 try:
583 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000584 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000585 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000586 self.assertEqual(repr(i),
587 "IncompleteRead(7 bytes read, 3 more expected)")
588 self.assertEqual(str(i),
589 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100590 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000591 else:
592 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000593
Jeremy Hylton636950f2009-03-28 04:34:21 +0000594 def test_epipe(self):
595 sock = EPipeSocket(
596 "HTTP/1.0 401 Authorization Required\r\n"
597 "Content-type: text/html\r\n"
598 "WWW-Authenticate: Basic realm=\"example\"\r\n",
599 b"Content-Length")
600 conn = client.HTTPConnection("example.com")
601 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200602 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000603 lambda: conn.request("PUT", "/url", "body"))
604 resp = conn.getresponse()
605 self.assertEqual(401, resp.status)
606 self.assertEqual("Basic realm=\"example\"",
607 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000608
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000609 # Test lines overflowing the max line size (_MAXLINE in http.client)
610
611 def test_overflowing_status_line(self):
612 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
613 resp = client.HTTPResponse(FakeSocket(body))
614 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
615
616 def test_overflowing_header_line(self):
617 body = (
618 'HTTP/1.1 200 OK\r\n'
619 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
620 )
621 resp = client.HTTPResponse(FakeSocket(body))
622 self.assertRaises(client.LineTooLong, resp.begin)
623
624 def test_overflowing_chunked_line(self):
625 body = (
626 'HTTP/1.1 200 OK\r\n'
627 'Transfer-Encoding: chunked\r\n\r\n'
628 + '0' * 65536 + 'a\r\n'
629 'hello world\r\n'
630 '0\r\n'
631 )
632 resp = client.HTTPResponse(FakeSocket(body))
633 resp.begin()
634 self.assertRaises(client.LineTooLong, resp.read)
635
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800636 def test_early_eof(self):
637 # Test httpresponse with no \r\n termination,
638 body = "HTTP/1.1 200 Ok"
639 sock = FakeSocket(body)
640 resp = client.HTTPResponse(sock)
641 resp.begin()
642 self.assertEqual(resp.read(), b'')
643 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200644 self.assertFalse(resp.closed)
645 resp.close()
646 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800647
Antoine Pitrou90e47742013-01-02 22:10:47 +0100648 def test_delayed_ack_opt(self):
649 # Test that Nagle/delayed_ack optimistaion works correctly.
650
651 # For small payloads, it should coalesce the body with
652 # headers, resulting in a single sendall() call
653 conn = client.HTTPConnection('example.com')
654 sock = FakeSocket(None)
655 conn.sock = sock
656 body = b'x' * (conn.mss - 1)
657 conn.request('POST', '/', body)
658 self.assertEqual(sock.sendall_calls, 1)
659
660 # For large payloads, it should send the headers and
661 # then the body, resulting in more than one sendall()
662 # call
663 conn = client.HTTPConnection('example.com')
664 sock = FakeSocket(None)
665 conn.sock = sock
666 body = b'x' * conn.mss
667 conn.request('POST', '/', body)
668 self.assertGreater(sock.sendall_calls, 1)
669
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000670class OfflineTest(TestCase):
671 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000672 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000673
Gregory P. Smithb4066372010-01-03 03:28:29 +0000674
675class SourceAddressTest(TestCase):
676 def setUp(self):
677 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
678 self.port = support.bind_port(self.serv)
679 self.source_port = support.find_unused_port()
680 self.serv.listen(5)
681 self.conn = None
682
683 def tearDown(self):
684 if self.conn:
685 self.conn.close()
686 self.conn = None
687 self.serv.close()
688 self.serv = None
689
690 def testHTTPConnectionSourceAddress(self):
691 self.conn = client.HTTPConnection(HOST, self.port,
692 source_address=('', self.source_port))
693 self.conn.connect()
694 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
695
696 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
697 'http.client.HTTPSConnection not defined')
698 def testHTTPSConnectionSourceAddress(self):
699 self.conn = client.HTTPSConnection(HOST, self.port,
700 source_address=('', self.source_port))
701 # We don't test anything here other the constructor not barfing as
702 # this code doesn't deal with setting up an active running SSL server
703 # for an ssl_wrapped connect() to actually return from.
704
705
Guido van Rossumd8faa362007-04-27 19:54:29 +0000706class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000707 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000708
709 def setUp(self):
710 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000711 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000712 self.serv.listen(5)
713
714 def tearDown(self):
715 self.serv.close()
716 self.serv = None
717
718 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000719 # This will prove that the timeout gets through HTTPConnection
720 # and into the socket.
721
Georg Brandlf78e02b2008-06-10 17:40:04 +0000722 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000723 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000724 socket.setdefaulttimeout(30)
725 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000726 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000727 httpConn.connect()
728 finally:
729 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000730 self.assertEqual(httpConn.sock.gettimeout(), 30)
731 httpConn.close()
732
Georg Brandlf78e02b2008-06-10 17:40:04 +0000733 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000734 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000735 socket.setdefaulttimeout(30)
736 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000737 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000738 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000739 httpConn.connect()
740 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000741 socket.setdefaulttimeout(None)
742 self.assertEqual(httpConn.sock.gettimeout(), None)
743 httpConn.close()
744
745 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000746 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000747 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000748 self.assertEqual(httpConn.sock.gettimeout(), 30)
749 httpConn.close()
750
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000751
752class HTTPSTest(TestCase):
753
754 def setUp(self):
755 if not hasattr(client, 'HTTPSConnection'):
756 self.skipTest('ssl support required')
757
758 def make_server(self, certfile):
759 from test.ssl_servers import make_https_server
Antoine Pitrouda232592013-02-05 21:20:51 +0100760 return make_https_server(self, certfile=certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000761
762 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000763 # simple test to check it's storing the timeout
764 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
765 self.assertEqual(h.timeout, 30)
766
767 def _check_svn_python_org(self, resp):
768 # Just a simple check that everything went fine
769 server_string = resp.getheader('server')
770 self.assertIn('Apache', server_string)
771
772 def test_networked(self):
773 # Default settings: no cert verification is done
774 support.requires('network')
775 with support.transient_internet('svn.python.org'):
776 h = client.HTTPSConnection('svn.python.org', 443)
777 h.request('GET', '/')
778 resp = h.getresponse()
779 self._check_svn_python_org(resp)
780
781 def test_networked_good_cert(self):
782 # We feed a CA cert that validates the server's cert
783 import ssl
784 support.requires('network')
785 with support.transient_internet('svn.python.org'):
786 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
787 context.verify_mode = ssl.CERT_REQUIRED
788 context.load_verify_locations(CACERT_svn_python_org)
789 h = client.HTTPSConnection('svn.python.org', 443, context=context)
790 h.request('GET', '/')
791 resp = h.getresponse()
792 self._check_svn_python_org(resp)
793
794 def test_networked_bad_cert(self):
795 # We feed a "CA" cert that is unrelated to the server's cert
796 import ssl
797 support.requires('network')
798 with support.transient_internet('svn.python.org'):
799 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
800 context.verify_mode = ssl.CERT_REQUIRED
801 context.load_verify_locations(CERT_localhost)
802 h = client.HTTPSConnection('svn.python.org', 443, context=context)
803 with self.assertRaises(ssl.SSLError):
804 h.request('GET', '/')
805
806 def test_local_good_hostname(self):
807 # The (valid) cert validates the HTTP hostname
808 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700809 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000810 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
811 context.verify_mode = ssl.CERT_REQUIRED
812 context.load_verify_locations(CERT_localhost)
813 h = client.HTTPSConnection('localhost', server.port, context=context)
814 h.request('GET', '/nonexistent')
815 resp = h.getresponse()
816 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700817 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000818
819 def test_local_bad_hostname(self):
820 # The (valid) cert doesn't validate the HTTP hostname
821 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700822 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000823 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
824 context.verify_mode = ssl.CERT_REQUIRED
825 context.load_verify_locations(CERT_fakehostname)
826 h = client.HTTPSConnection('localhost', server.port, context=context)
827 with self.assertRaises(ssl.CertificateError):
828 h.request('GET', '/')
829 # Same with explicit check_hostname=True
830 h = client.HTTPSConnection('localhost', server.port, context=context,
831 check_hostname=True)
832 with self.assertRaises(ssl.CertificateError):
833 h.request('GET', '/')
834 # With check_hostname=False, the mismatching is ignored
835 h = client.HTTPSConnection('localhost', server.port, context=context,
836 check_hostname=False)
837 h.request('GET', '/nonexistent')
838 resp = h.getresponse()
839 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700840 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000841
Petri Lehtinene119c402011-10-26 21:29:15 +0300842 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
843 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200844 def test_host_port(self):
845 # Check invalid host_port
846
847 for hp in ("www.python.org:abc", "user:password@www.python.org"):
848 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
849
850 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
851 "fe80::207:e9ff:fe9b", 8000),
852 ("www.python.org:443", "www.python.org", 443),
853 ("www.python.org:", "www.python.org", 443),
854 ("www.python.org", "www.python.org", 443),
855 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
856 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
857 443)):
858 c = client.HTTPSConnection(hp)
859 self.assertEqual(h, c.host)
860 self.assertEqual(p, c.port)
861
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000862
Jeremy Hylton236654b2009-03-27 20:24:34 +0000863class RequestBodyTest(TestCase):
864 """Test cases where a request includes a message body."""
865
866 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000867 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000868 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000869 self.conn.sock = self.sock
870
871 def get_headers_and_fp(self):
872 f = io.BytesIO(self.sock.data)
873 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000874 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000875 return message, f
876
877 def test_manual_content_length(self):
878 # Set an incorrect content-length so that we can verify that
879 # it will not be over-ridden by the library.
880 self.conn.request("PUT", "/url", "body",
881 {"Content-Length": "42"})
882 message, f = self.get_headers_and_fp()
883 self.assertEqual("42", message.get("content-length"))
884 self.assertEqual(4, len(f.read()))
885
886 def test_ascii_body(self):
887 self.conn.request("PUT", "/url", "body")
888 message, f = self.get_headers_and_fp()
889 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000890 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000891 self.assertEqual("4", message.get("content-length"))
892 self.assertEqual(b'body', f.read())
893
894 def test_latin1_body(self):
895 self.conn.request("PUT", "/url", "body\xc1")
896 message, f = self.get_headers_and_fp()
897 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000898 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000899 self.assertEqual("5", message.get("content-length"))
900 self.assertEqual(b'body\xc1', f.read())
901
902 def test_bytes_body(self):
903 self.conn.request("PUT", "/url", b"body\xc1")
904 message, f = self.get_headers_and_fp()
905 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000906 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000907 self.assertEqual("5", message.get("content-length"))
908 self.assertEqual(b'body\xc1', f.read())
909
910 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200911 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000912 with open(support.TESTFN, "w") as f:
913 f.write("body")
914 with open(support.TESTFN) as f:
915 self.conn.request("PUT", "/url", f)
916 message, f = self.get_headers_and_fp()
917 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000918 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000919 self.assertEqual("4", message.get("content-length"))
920 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000921
922 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200923 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000924 with open(support.TESTFN, "wb") as f:
925 f.write(b"body\xc1")
926 with open(support.TESTFN, "rb") as f:
927 self.conn.request("PUT", "/url", f)
928 message, f = self.get_headers_and_fp()
929 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000930 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000931 self.assertEqual("5", message.get("content-length"))
932 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000933
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000934
935class HTTPResponseTest(TestCase):
936
937 def setUp(self):
938 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
939 second-value\r\n\r\nText"
940 sock = FakeSocket(body)
941 self.resp = client.HTTPResponse(sock)
942 self.resp.begin()
943
944 def test_getting_header(self):
945 header = self.resp.getheader('My-Header')
946 self.assertEqual(header, 'first-value, second-value')
947
948 header = self.resp.getheader('My-Header', 'some default')
949 self.assertEqual(header, 'first-value, second-value')
950
951 def test_getting_nonexistent_header_with_string_default(self):
952 header = self.resp.getheader('No-Such-Header', 'default-value')
953 self.assertEqual(header, 'default-value')
954
955 def test_getting_nonexistent_header_with_iterable_default(self):
956 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
957 self.assertEqual(header, 'default, values')
958
959 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
960 self.assertEqual(header, 'default, values')
961
962 def test_getting_nonexistent_header_without_default(self):
963 header = self.resp.getheader('No-Such-Header')
964 self.assertEqual(header, None)
965
966 def test_getting_header_defaultint(self):
967 header = self.resp.getheader('No-Such-Header',default=42)
968 self.assertEqual(header, 42)
969
Jeremy Hylton2c178252004-08-07 16:28:14 +0000970def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000971 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000972 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000973 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000974
Thomas Wouters89f507f2006-12-13 04:49:30 +0000975if __name__ == '__main__':
976 test_main()