blob: d8172c1851097f29416f4586d6385c0dee447b56 [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')
Georg Brandl89644d02014-11-05 20:37:40 +010018# Self-signed cert file for self-signed.pythontest.net
19CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
Antoine Pitrou803e6d62010-10-13 10:36:15 +000020
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
Serhiy Storchaka50254c52013-08-29 11:35:43 +030054class NoEOFBytesIO(io.BytesIO):
55 """Like BytesIO, but raises AssertionError on EOF.
Jeremy Hylton121d34a2003-07-08 12:36:58 +000056
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)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200135 self.assertIn(b'Content-length: 42', conn._buffer)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000136
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()
Serhiy Storchaka1c84ac12013-12-17 21:50:02 +0200165 self.assertEqual(resp.read(0), b'') # Issue #20007
166 self.assertFalse(resp.isclosed())
167 self.assertFalse(resp.closed)
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000168 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000169 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200170 self.assertFalse(resp.closed)
171 resp.close()
172 self.assertTrue(resp.closed)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000173
Thomas Wouters89f507f2006-12-13 04:49:30 +0000174 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
175 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000176 resp = client.HTTPResponse(sock)
177 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000178
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000179 def test_bad_status_repr(self):
180 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000181 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000182
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000183 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100184 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000185 # same behaviour than when we read the whole thing with read()
186 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
187 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000188 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000189 resp.begin()
190 self.assertEqual(resp.read(2), b'Te')
191 self.assertFalse(resp.isclosed())
192 self.assertEqual(resp.read(2), b'xt')
193 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200194 self.assertFalse(resp.closed)
195 resp.close()
196 self.assertTrue(resp.closed)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000197
Antoine Pitrou38d96432011-12-06 22:33:57 +0100198 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100199 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100200 # same behaviour than when we read the whole thing with read()
201 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
202 sock = FakeSocket(body)
203 resp = client.HTTPResponse(sock)
204 resp.begin()
205 b = bytearray(2)
206 n = resp.readinto(b)
207 self.assertEqual(n, 2)
208 self.assertEqual(bytes(b), b'Te')
209 self.assertFalse(resp.isclosed())
210 n = resp.readinto(b)
211 self.assertEqual(n, 2)
212 self.assertEqual(bytes(b), b'xt')
213 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200214 self.assertFalse(resp.closed)
215 resp.close()
216 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100217
Antoine Pitrou084daa22012-12-15 19:11:54 +0100218 def test_partial_reads_no_content_length(self):
219 # when no length is present, the socket should be gracefully closed when
220 # all data was read
221 body = "HTTP/1.1 200 Ok\r\n\r\nText"
222 sock = FakeSocket(body)
223 resp = client.HTTPResponse(sock)
224 resp.begin()
225 self.assertEqual(resp.read(2), b'Te')
226 self.assertFalse(resp.isclosed())
227 self.assertEqual(resp.read(2), b'xt')
228 self.assertEqual(resp.read(1), b'')
229 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200230 self.assertFalse(resp.closed)
231 resp.close()
232 self.assertTrue(resp.closed)
Antoine Pitrou084daa22012-12-15 19:11:54 +0100233
Antoine Pitroud20e7742012-12-15 19:22:30 +0100234 def test_partial_readintos_no_content_length(self):
235 # when no length is present, the socket should be gracefully closed when
236 # all data was read
237 body = "HTTP/1.1 200 Ok\r\n\r\nText"
238 sock = FakeSocket(body)
239 resp = client.HTTPResponse(sock)
240 resp.begin()
241 b = bytearray(2)
242 n = resp.readinto(b)
243 self.assertEqual(n, 2)
244 self.assertEqual(bytes(b), b'Te')
245 self.assertFalse(resp.isclosed())
246 n = resp.readinto(b)
247 self.assertEqual(n, 2)
248 self.assertEqual(bytes(b), b'xt')
249 n = resp.readinto(b)
250 self.assertEqual(n, 0)
251 self.assertTrue(resp.isclosed())
252
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100253 def test_partial_reads_incomplete_body(self):
254 # if the server shuts down the connection before the whole
255 # content-length is delivered, the socket is gracefully closed
256 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
257 sock = FakeSocket(body)
258 resp = client.HTTPResponse(sock)
259 resp.begin()
260 self.assertEqual(resp.read(2), b'Te')
261 self.assertFalse(resp.isclosed())
262 self.assertEqual(resp.read(2), b'xt')
263 self.assertEqual(resp.read(1), b'')
264 self.assertTrue(resp.isclosed())
265
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100266 def test_partial_readintos_incomplete_body(self):
267 # if the server shuts down the connection before the whole
268 # content-length is delivered, the socket is gracefully closed
269 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
270 sock = FakeSocket(body)
271 resp = client.HTTPResponse(sock)
272 resp.begin()
273 b = bytearray(2)
274 n = resp.readinto(b)
275 self.assertEqual(n, 2)
276 self.assertEqual(bytes(b), b'Te')
277 self.assertFalse(resp.isclosed())
278 n = resp.readinto(b)
279 self.assertEqual(n, 2)
280 self.assertEqual(bytes(b), b'xt')
281 n = resp.readinto(b)
282 self.assertEqual(n, 0)
283 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200284 self.assertFalse(resp.closed)
285 resp.close()
286 self.assertTrue(resp.closed)
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100287
Thomas Wouters89f507f2006-12-13 04:49:30 +0000288 def test_host_port(self):
289 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000290
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200291 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000292 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000293
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000294 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
295 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000296 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200297 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000298 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200299 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
300 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000301 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000302 self.assertEqual(h, c.host)
303 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000304
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305 def test_response_headers(self):
306 # test response with multiple message headers with the same field name.
307 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000308 'Set-Cookie: Customer="WILE_E_COYOTE"; '
309 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000310 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
311 ' Path="/acme"\r\n'
312 '\r\n'
313 'No body\r\n')
314 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
315 ', '
316 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
317 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000318 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000319 r.begin()
320 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000321 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000322
Thomas Wouters89f507f2006-12-13 04:49:30 +0000323 def test_read_head(self):
324 # Test that the library doesn't attempt to read any data
325 # from a HEAD request. (Tickles SF bug #622042.)
326 sock = FakeSocket(
327 'HTTP/1.1 200 OK\r\n'
328 'Content-Length: 14432\r\n'
329 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300330 NoEOFBytesIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000331 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000332 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000333 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000334 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000335
Antoine Pitrou38d96432011-12-06 22:33:57 +0100336 def test_readinto_head(self):
337 # Test that the library doesn't attempt to read any data
338 # from a HEAD request. (Tickles SF bug #622042.)
339 sock = FakeSocket(
340 'HTTP/1.1 200 OK\r\n'
341 'Content-Length: 14432\r\n'
342 '\r\n',
Serhiy Storchaka50254c52013-08-29 11:35:43 +0300343 NoEOFBytesIO)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100344 resp = client.HTTPResponse(sock, method="HEAD")
345 resp.begin()
346 b = bytearray(5)
347 if resp.readinto(b) != 0:
348 self.fail("Did not expect response from HEAD request")
349 self.assertEqual(bytes(b), b'\x00'*5)
350
Georg Brandlbf3f8eb2013-10-27 07:34:48 +0100351 def test_too_many_headers(self):
352 headers = '\r\n'.join('Header%d: foo' % i
353 for i in range(client._MAXHEADERS + 1)) + '\r\n'
354 text = ('HTTP/1.1 200 OK\r\n' + headers)
355 s = FakeSocket(text)
356 r = client.HTTPResponse(s)
357 self.assertRaisesRegex(client.HTTPException,
358 r"got more than \d+ headers", r.begin)
359
Thomas Wouters89f507f2006-12-13 04:49:30 +0000360 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000361 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
362 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000363
Brett Cannon77b7de62010-10-29 23:31:11 +0000364 with open(__file__, 'rb') as body:
365 conn = client.HTTPConnection('example.com')
366 sock = FakeSocket(body)
367 conn.sock = sock
368 conn.request('GET', '/foo', body)
369 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
370 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000371
Antoine Pitrouead1d622009-09-29 18:44:53 +0000372 def test_send(self):
373 expected = b'this is a test this is only a test'
374 conn = client.HTTPConnection('example.com')
375 sock = FakeSocket(None)
376 conn.sock = sock
377 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000378 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000379 sock.data = b''
380 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000381 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000382 sock.data = b''
383 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000384 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000385
Andrew Svetlov7b2c8bb2013-04-12 22:49:19 +0300386 def test_send_updating_file(self):
387 def data():
388 yield 'data'
389 yield None
390 yield 'data_two'
391
392 class UpdatingFile():
393 mode = 'r'
394 d = data()
395 def read(self, blocksize=-1):
396 return self.d.__next__()
397
398 expected = b'data'
399
400 conn = client.HTTPConnection('example.com')
401 sock = FakeSocket("")
402 conn.sock = sock
403 conn.send(UpdatingFile())
404 self.assertEqual(sock.data, expected)
405
406
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000407 def test_send_iter(self):
408 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
409 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
410 b'\r\nonetwothree'
411
412 def body():
413 yield b"one"
414 yield b"two"
415 yield b"three"
416
417 conn = client.HTTPConnection('example.com')
418 sock = FakeSocket("")
419 conn.sock = sock
420 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000421 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000422
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800423 def test_send_type_error(self):
424 # See: Issue #12676
425 conn = client.HTTPConnection('example.com')
426 conn.sock = FakeSocket('')
427 with self.assertRaises(TypeError):
428 conn.request('POST', 'test', conn)
429
Christian Heimesa612dc02008-02-24 13:08:18 +0000430 def test_chunked(self):
431 chunked_start = (
432 'HTTP/1.1 200 OK\r\n'
433 'Transfer-Encoding: chunked\r\n\r\n'
434 'a\r\n'
435 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100436 '3\r\n'
437 'd! \r\n'
438 '8\r\n'
439 'and now \r\n'
440 '22\r\n'
441 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000442 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100443 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000444 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000445 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000446 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100447 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000448 resp.close()
449
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100450 # Various read sizes
451 for n in range(1, 12):
452 sock = FakeSocket(chunked_start + '0\r\n')
453 resp = client.HTTPResponse(sock, method="GET")
454 resp.begin()
455 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
456 resp.close()
457
Christian Heimesa612dc02008-02-24 13:08:18 +0000458 for x in ('', 'foo\r\n'):
459 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000460 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000461 resp.begin()
462 try:
463 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000464 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100465 self.assertEqual(i.partial, expected)
466 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
467 self.assertEqual(repr(i), expected_message)
468 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000469 else:
470 self.fail('IncompleteRead expected')
471 finally:
472 resp.close()
473
Antoine Pitrou38d96432011-12-06 22:33:57 +0100474 def test_readinto_chunked(self):
475 chunked_start = (
476 'HTTP/1.1 200 OK\r\n'
477 'Transfer-Encoding: chunked\r\n\r\n'
478 'a\r\n'
479 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100480 '3\r\n'
481 'd! \r\n'
482 '8\r\n'
483 'and now \r\n'
484 '22\r\n'
485 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100486 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100487 expected = b'hello world! and now for something completely different'
488 nexpected = len(expected)
489 b = bytearray(128)
490
Antoine Pitrou38d96432011-12-06 22:33:57 +0100491 sock = FakeSocket(chunked_start + '0\r\n')
492 resp = client.HTTPResponse(sock, method="GET")
493 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100494 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100495 self.assertEqual(b[:nexpected], expected)
496 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100497 resp.close()
498
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100499 # Various read sizes
500 for n in range(1, 12):
501 sock = FakeSocket(chunked_start + '0\r\n')
502 resp = client.HTTPResponse(sock, method="GET")
503 resp.begin()
504 m = memoryview(b)
505 i = resp.readinto(m[0:n])
506 i += resp.readinto(m[i:n + i])
507 i += resp.readinto(m[i:])
508 self.assertEqual(b[:nexpected], expected)
509 self.assertEqual(i, nexpected)
510 resp.close()
511
Antoine Pitrou38d96432011-12-06 22:33:57 +0100512 for x in ('', 'foo\r\n'):
513 sock = FakeSocket(chunked_start + x)
514 resp = client.HTTPResponse(sock, method="GET")
515 resp.begin()
516 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100517 n = resp.readinto(b)
518 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100519 self.assertEqual(i.partial, expected)
520 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
521 self.assertEqual(repr(i), expected_message)
522 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100523 else:
524 self.fail('IncompleteRead expected')
525 finally:
526 resp.close()
527
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000528 def test_chunked_head(self):
529 chunked_start = (
530 'HTTP/1.1 200 OK\r\n'
531 'Transfer-Encoding: chunked\r\n\r\n'
532 'a\r\n'
533 'hello world\r\n'
534 '1\r\n'
535 'd\r\n'
536 )
537 sock = FakeSocket(chunked_start + '0\r\n')
538 resp = client.HTTPResponse(sock, method="HEAD")
539 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000540 self.assertEqual(resp.read(), b'')
541 self.assertEqual(resp.status, 200)
542 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000543 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200544 self.assertFalse(resp.closed)
545 resp.close()
546 self.assertTrue(resp.closed)
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000547
Antoine Pitrou38d96432011-12-06 22:33:57 +0100548 def test_readinto_chunked_head(self):
549 chunked_start = (
550 'HTTP/1.1 200 OK\r\n'
551 'Transfer-Encoding: chunked\r\n\r\n'
552 'a\r\n'
553 'hello world\r\n'
554 '1\r\n'
555 'd\r\n'
556 )
557 sock = FakeSocket(chunked_start + '0\r\n')
558 resp = client.HTTPResponse(sock, method="HEAD")
559 resp.begin()
560 b = bytearray(5)
561 n = resp.readinto(b)
562 self.assertEqual(n, 0)
563 self.assertEqual(bytes(b), b'\x00'*5)
564 self.assertEqual(resp.status, 200)
565 self.assertEqual(resp.reason, 'OK')
566 self.assertTrue(resp.isclosed())
Serhiy Storchakab6c86fd2013-02-06 10:35:40 +0200567 self.assertFalse(resp.closed)
568 resp.close()
569 self.assertTrue(resp.closed)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100570
Christian Heimesa612dc02008-02-24 13:08:18 +0000571 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000572 sock = FakeSocket(
573 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000574 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000575 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000576 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100577 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000578
Benjamin Peterson6accb982009-03-02 22:50:25 +0000579 def test_incomplete_read(self):
580 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000581 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000582 resp.begin()
583 try:
584 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000585 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000586 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000587 self.assertEqual(repr(i),
588 "IncompleteRead(7 bytes read, 3 more expected)")
589 self.assertEqual(str(i),
590 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100591 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000592 else:
593 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000594
Jeremy Hylton636950f2009-03-28 04:34:21 +0000595 def test_epipe(self):
596 sock = EPipeSocket(
597 "HTTP/1.0 401 Authorization Required\r\n"
598 "Content-type: text/html\r\n"
599 "WWW-Authenticate: Basic realm=\"example\"\r\n",
600 b"Content-Length")
601 conn = client.HTTPConnection("example.com")
602 conn.sock = sock
603 self.assertRaises(socket.error,
604 lambda: conn.request("PUT", "/url", "body"))
605 resp = conn.getresponse()
606 self.assertEqual(401, resp.status)
607 self.assertEqual("Basic realm=\"example\"",
608 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000609
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000610 # Test lines overflowing the max line size (_MAXLINE in http.client)
611
612 def test_overflowing_status_line(self):
613 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
614 resp = client.HTTPResponse(FakeSocket(body))
615 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
616
617 def test_overflowing_header_line(self):
618 body = (
619 'HTTP/1.1 200 OK\r\n'
620 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
621 )
622 resp = client.HTTPResponse(FakeSocket(body))
623 self.assertRaises(client.LineTooLong, resp.begin)
624
625 def test_overflowing_chunked_line(self):
626 body = (
627 'HTTP/1.1 200 OK\r\n'
628 'Transfer-Encoding: chunked\r\n\r\n'
629 + '0' * 65536 + 'a\r\n'
630 'hello world\r\n'
631 '0\r\n'
632 )
633 resp = client.HTTPResponse(FakeSocket(body))
634 resp.begin()
635 self.assertRaises(client.LineTooLong, resp.read)
636
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800637 def test_early_eof(self):
638 # Test httpresponse with no \r\n termination,
639 body = "HTTP/1.1 200 Ok"
640 sock = FakeSocket(body)
641 resp = client.HTTPResponse(sock)
642 resp.begin()
643 self.assertEqual(resp.read(), b'')
644 self.assertTrue(resp.isclosed())
Serhiy Storchakab5b9c8c2013-02-06 10:31:57 +0200645 self.assertFalse(resp.closed)
646 resp.close()
647 self.assertTrue(resp.closed)
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800648
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000649class OfflineTest(TestCase):
650 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000651 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000652
Gregory P. Smithb4066372010-01-03 03:28:29 +0000653
654class SourceAddressTest(TestCase):
655 def setUp(self):
656 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
657 self.port = support.bind_port(self.serv)
658 self.source_port = support.find_unused_port()
659 self.serv.listen(5)
660 self.conn = None
661
662 def tearDown(self):
663 if self.conn:
664 self.conn.close()
665 self.conn = None
666 self.serv.close()
667 self.serv = None
668
669 def testHTTPConnectionSourceAddress(self):
670 self.conn = client.HTTPConnection(HOST, self.port,
671 source_address=('', self.source_port))
672 self.conn.connect()
673 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
674
675 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
676 'http.client.HTTPSConnection not defined')
677 def testHTTPSConnectionSourceAddress(self):
678 self.conn = client.HTTPSConnection(HOST, self.port,
679 source_address=('', self.source_port))
680 # We don't test anything here other the constructor not barfing as
681 # this code doesn't deal with setting up an active running SSL server
682 # for an ssl_wrapped connect() to actually return from.
683
684
Guido van Rossumd8faa362007-04-27 19:54:29 +0000685class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000686 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000687
688 def setUp(self):
689 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000690 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000691 self.serv.listen(5)
692
693 def tearDown(self):
694 self.serv.close()
695 self.serv = None
696
697 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000698 # This will prove that the timeout gets through HTTPConnection
699 # and into the socket.
700
Georg Brandlf78e02b2008-06-10 17:40:04 +0000701 # default -- use global socket timeout
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200702 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandlf78e02b2008-06-10 17:40:04 +0000703 socket.setdefaulttimeout(30)
704 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000705 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000706 httpConn.connect()
707 finally:
708 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000709 self.assertEqual(httpConn.sock.gettimeout(), 30)
710 httpConn.close()
711
Georg Brandlf78e02b2008-06-10 17:40:04 +0000712 # no timeout -- do not use global socket default
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200713 self.assertIsNone(socket.getdefaulttimeout())
Guido van Rossumd8faa362007-04-27 19:54:29 +0000714 socket.setdefaulttimeout(30)
715 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000716 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000717 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000718 httpConn.connect()
719 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000720 socket.setdefaulttimeout(None)
721 self.assertEqual(httpConn.sock.gettimeout(), None)
722 httpConn.close()
723
724 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000725 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000726 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000727 self.assertEqual(httpConn.sock.gettimeout(), 30)
728 httpConn.close()
729
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000730
731class HTTPSTest(TestCase):
732
733 def setUp(self):
734 if not hasattr(client, 'HTTPSConnection'):
735 self.skipTest('ssl support required')
736
737 def make_server(self, certfile):
738 from test.ssl_servers import make_https_server
739 return make_https_server(self, certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000740
741 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000742 # simple test to check it's storing the timeout
743 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
744 self.assertEqual(h.timeout, 30)
745
746 def _check_svn_python_org(self, resp):
747 # Just a simple check that everything went fine
748 server_string = resp.getheader('server')
749 self.assertIn('Apache', server_string)
750
751 def test_networked(self):
752 # Default settings: no cert verification is done
753 support.requires('network')
754 with support.transient_internet('svn.python.org'):
755 h = client.HTTPSConnection('svn.python.org', 443)
756 h.request('GET', '/')
757 resp = h.getresponse()
758 self._check_svn_python_org(resp)
759
760 def test_networked_good_cert(self):
Georg Brandl89644d02014-11-05 20:37:40 +0100761 # We feed the server's cert as a validating cert
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000762 import ssl
763 support.requires('network')
Georg Brandl89644d02014-11-05 20:37:40 +0100764 with support.transient_internet('self-signed.pythontest.net'):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000765 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
766 context.verify_mode = ssl.CERT_REQUIRED
Georg Brandl89644d02014-11-05 20:37:40 +0100767 context.load_verify_locations(CERT_selfsigned_pythontestdotnet)
768 h = client.HTTPSConnection('self-signed.pythontest.net', 443, context=context)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000769 h.request('GET', '/')
770 resp = h.getresponse()
Georg Brandl89644d02014-11-05 20:37:40 +0100771 server_string = resp.getheader('server')
772 self.assertIn('nginx', server_string)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000773
774 def test_networked_bad_cert(self):
775 # We feed a "CA" cert that is unrelated to the server's cert
776 import ssl
777 support.requires('network')
778 with support.transient_internet('svn.python.org'):
779 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
780 context.verify_mode = ssl.CERT_REQUIRED
781 context.load_verify_locations(CERT_localhost)
782 h = client.HTTPSConnection('svn.python.org', 443, context=context)
783 with self.assertRaises(ssl.SSLError):
784 h.request('GET', '/')
785
786 def test_local_good_hostname(self):
787 # The (valid) cert validates the HTTP hostname
788 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700789 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000790 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
791 context.verify_mode = ssl.CERT_REQUIRED
792 context.load_verify_locations(CERT_localhost)
793 h = client.HTTPSConnection('localhost', server.port, context=context)
794 h.request('GET', '/nonexistent')
795 resp = h.getresponse()
796 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700797 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000798
799 def test_local_bad_hostname(self):
800 # The (valid) cert doesn't validate the HTTP hostname
801 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700802 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000803 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
804 context.verify_mode = ssl.CERT_REQUIRED
805 context.load_verify_locations(CERT_fakehostname)
806 h = client.HTTPSConnection('localhost', server.port, context=context)
807 with self.assertRaises(ssl.CertificateError):
808 h.request('GET', '/')
809 # Same with explicit check_hostname=True
810 h = client.HTTPSConnection('localhost', server.port, context=context,
811 check_hostname=True)
812 with self.assertRaises(ssl.CertificateError):
813 h.request('GET', '/')
814 # With check_hostname=False, the mismatching is ignored
815 h = client.HTTPSConnection('localhost', server.port, context=context,
816 check_hostname=False)
817 h.request('GET', '/nonexistent')
818 resp = h.getresponse()
819 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700820 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000821
Petri Lehtinene119c402011-10-26 21:29:15 +0300822 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
823 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200824 def test_host_port(self):
825 # Check invalid host_port
826
827 for hp in ("www.python.org:abc", "user:password@www.python.org"):
828 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
829
830 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
831 "fe80::207:e9ff:fe9b", 8000),
832 ("www.python.org:443", "www.python.org", 443),
833 ("www.python.org:", "www.python.org", 443),
834 ("www.python.org", "www.python.org", 443),
835 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
836 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
837 443)):
838 c = client.HTTPSConnection(hp)
839 self.assertEqual(h, c.host)
840 self.assertEqual(p, c.port)
841
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000842
Jeremy Hylton236654b2009-03-27 20:24:34 +0000843class RequestBodyTest(TestCase):
844 """Test cases where a request includes a message body."""
845
846 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000847 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000848 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000849 self.conn.sock = self.sock
850
851 def get_headers_and_fp(self):
852 f = io.BytesIO(self.sock.data)
853 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000854 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000855 return message, f
856
857 def test_manual_content_length(self):
858 # Set an incorrect content-length so that we can verify that
859 # it will not be over-ridden by the library.
860 self.conn.request("PUT", "/url", "body",
861 {"Content-Length": "42"})
862 message, f = self.get_headers_and_fp()
863 self.assertEqual("42", message.get("content-length"))
864 self.assertEqual(4, len(f.read()))
865
866 def test_ascii_body(self):
867 self.conn.request("PUT", "/url", "body")
868 message, f = self.get_headers_and_fp()
869 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000870 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000871 self.assertEqual("4", message.get("content-length"))
872 self.assertEqual(b'body', f.read())
873
874 def test_latin1_body(self):
875 self.conn.request("PUT", "/url", "body\xc1")
876 message, f = self.get_headers_and_fp()
877 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000878 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000879 self.assertEqual("5", message.get("content-length"))
880 self.assertEqual(b'body\xc1', f.read())
881
882 def test_bytes_body(self):
883 self.conn.request("PUT", "/url", b"body\xc1")
884 message, f = self.get_headers_and_fp()
885 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000886 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000887 self.assertEqual("5", message.get("content-length"))
888 self.assertEqual(b'body\xc1', f.read())
889
890 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200891 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000892 with open(support.TESTFN, "w") as f:
893 f.write("body")
894 with open(support.TESTFN) as f:
895 self.conn.request("PUT", "/url", f)
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())
Brett Cannon77b7de62010-10-29 23:31:11 +0000899 self.assertEqual("4", message.get("content-length"))
900 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000901
902 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200903 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000904 with open(support.TESTFN, "wb") as f:
905 f.write(b"body\xc1")
906 with open(support.TESTFN, "rb") as f:
907 self.conn.request("PUT", "/url", f)
908 message, f = self.get_headers_and_fp()
909 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000910 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000911 self.assertEqual("5", message.get("content-length"))
912 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000913
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000914
915class HTTPResponseTest(TestCase):
916
917 def setUp(self):
918 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
919 second-value\r\n\r\nText"
920 sock = FakeSocket(body)
921 self.resp = client.HTTPResponse(sock)
922 self.resp.begin()
923
924 def test_getting_header(self):
925 header = self.resp.getheader('My-Header')
926 self.assertEqual(header, 'first-value, second-value')
927
928 header = self.resp.getheader('My-Header', 'some default')
929 self.assertEqual(header, 'first-value, second-value')
930
931 def test_getting_nonexistent_header_with_string_default(self):
932 header = self.resp.getheader('No-Such-Header', 'default-value')
933 self.assertEqual(header, 'default-value')
934
935 def test_getting_nonexistent_header_with_iterable_default(self):
936 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
937 self.assertEqual(header, 'default, values')
938
939 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
940 self.assertEqual(header, 'default, values')
941
942 def test_getting_nonexistent_header_without_default(self):
943 header = self.resp.getheader('No-Such-Header')
944 self.assertEqual(header, None)
945
946 def test_getting_header_defaultint(self):
947 header = self.resp.getheader('No-Such-Header',default=42)
948 self.assertEqual(header, 42)
949
Jeremy Hylton2c178252004-08-07 16:28:14 +0000950def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000951 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000952 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000953 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000954
Thomas Wouters89f507f2006-12-13 04:49:30 +0000955if __name__ == '__main__':
956 test_main()