blob: a58a59247645efd383d0ad09c6bc0b4125294301 [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())
Jeremy Hyltonba603192003-01-23 18:02:20 +0000167
Thomas Wouters89f507f2006-12-13 04:49:30 +0000168 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
169 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000170 resp = client.HTTPResponse(sock)
171 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000172
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000173 def test_bad_status_repr(self):
174 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000175 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000176
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000177 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100178 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000179 # same behaviour than when we read the whole thing with read()
180 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
181 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000182 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000183 resp.begin()
184 self.assertEqual(resp.read(2), b'Te')
185 self.assertFalse(resp.isclosed())
186 self.assertEqual(resp.read(2), b'xt')
187 self.assertTrue(resp.isclosed())
188
Antoine Pitrou38d96432011-12-06 22:33:57 +0100189 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100190 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100191 # same behaviour than when we read the whole thing with read()
192 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
193 sock = FakeSocket(body)
194 resp = client.HTTPResponse(sock)
195 resp.begin()
196 b = bytearray(2)
197 n = resp.readinto(b)
198 self.assertEqual(n, 2)
199 self.assertEqual(bytes(b), b'Te')
200 self.assertFalse(resp.isclosed())
201 n = resp.readinto(b)
202 self.assertEqual(n, 2)
203 self.assertEqual(bytes(b), b'xt')
204 self.assertTrue(resp.isclosed())
205
Antoine Pitrou084daa22012-12-15 19:11:54 +0100206 def test_partial_reads_no_content_length(self):
207 # when no length is present, the socket should be gracefully closed when
208 # all data was read
209 body = "HTTP/1.1 200 Ok\r\n\r\nText"
210 sock = FakeSocket(body)
211 resp = client.HTTPResponse(sock)
212 resp.begin()
213 self.assertEqual(resp.read(2), b'Te')
214 self.assertFalse(resp.isclosed())
215 self.assertEqual(resp.read(2), b'xt')
216 self.assertEqual(resp.read(1), b'')
217 self.assertTrue(resp.isclosed())
218
Antoine Pitroud20e7742012-12-15 19:22:30 +0100219 def test_partial_readintos_no_content_length(self):
220 # when no length is present, the socket should be gracefully closed when
221 # all data was read
222 body = "HTTP/1.1 200 Ok\r\n\r\nText"
223 sock = FakeSocket(body)
224 resp = client.HTTPResponse(sock)
225 resp.begin()
226 b = bytearray(2)
227 n = resp.readinto(b)
228 self.assertEqual(n, 2)
229 self.assertEqual(bytes(b), b'Te')
230 self.assertFalse(resp.isclosed())
231 n = resp.readinto(b)
232 self.assertEqual(n, 2)
233 self.assertEqual(bytes(b), b'xt')
234 n = resp.readinto(b)
235 self.assertEqual(n, 0)
236 self.assertTrue(resp.isclosed())
237
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100238 def test_partial_reads_incomplete_body(self):
239 # if the server shuts down the connection before the whole
240 # content-length is delivered, the socket is gracefully closed
241 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
242 sock = FakeSocket(body)
243 resp = client.HTTPResponse(sock)
244 resp.begin()
245 self.assertEqual(resp.read(2), b'Te')
246 self.assertFalse(resp.isclosed())
247 self.assertEqual(resp.read(2), b'xt')
248 self.assertEqual(resp.read(1), b'')
249 self.assertTrue(resp.isclosed())
250
Antoine Pitrou6a35e182013-02-02 23:04:56 +0100251 def test_partial_readintos_incomplete_body(self):
252 # if the server shuts down the connection before the whole
253 # content-length is delivered, the socket is gracefully closed
254 body = "HTTP/1.1 200 Ok\r\nContent-Length: 10\r\n\r\nText"
255 sock = FakeSocket(body)
256 resp = client.HTTPResponse(sock)
257 resp.begin()
258 b = bytearray(2)
259 n = resp.readinto(b)
260 self.assertEqual(n, 2)
261 self.assertEqual(bytes(b), b'Te')
262 self.assertFalse(resp.isclosed())
263 n = resp.readinto(b)
264 self.assertEqual(n, 2)
265 self.assertEqual(bytes(b), b'xt')
266 n = resp.readinto(b)
267 self.assertEqual(n, 0)
268 self.assertTrue(resp.isclosed())
269
Thomas Wouters89f507f2006-12-13 04:49:30 +0000270 def test_host_port(self):
271 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000272
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200273 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000274 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000275
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000276 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
277 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000278 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200279 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000280 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200281 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
282 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000283 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000284 self.assertEqual(h, c.host)
285 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000286
Thomas Wouters89f507f2006-12-13 04:49:30 +0000287 def test_response_headers(self):
288 # test response with multiple message headers with the same field name.
289 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000290 'Set-Cookie: Customer="WILE_E_COYOTE"; '
291 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000292 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
293 ' Path="/acme"\r\n'
294 '\r\n'
295 'No body\r\n')
296 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
297 ', '
298 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
299 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000300 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000301 r.begin()
302 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000303 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000304
Thomas Wouters89f507f2006-12-13 04:49:30 +0000305 def test_read_head(self):
306 # Test that the library doesn't attempt to read any data
307 # from a HEAD request. (Tickles SF bug #622042.)
308 sock = FakeSocket(
309 'HTTP/1.1 200 OK\r\n'
310 'Content-Length: 14432\r\n'
311 '\r\n',
312 NoEOFStringIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000313 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000315 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000316 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000317
Antoine Pitrou38d96432011-12-06 22:33:57 +0100318 def test_readinto_head(self):
319 # Test that the library doesn't attempt to read any data
320 # from a HEAD request. (Tickles SF bug #622042.)
321 sock = FakeSocket(
322 'HTTP/1.1 200 OK\r\n'
323 'Content-Length: 14432\r\n'
324 '\r\n',
325 NoEOFStringIO)
326 resp = client.HTTPResponse(sock, method="HEAD")
327 resp.begin()
328 b = bytearray(5)
329 if resp.readinto(b) != 0:
330 self.fail("Did not expect response from HEAD request")
331 self.assertEqual(bytes(b), b'\x00'*5)
332
Thomas Wouters89f507f2006-12-13 04:49:30 +0000333 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000334 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
335 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000336
Brett Cannon77b7de62010-10-29 23:31:11 +0000337 with open(__file__, 'rb') as body:
338 conn = client.HTTPConnection('example.com')
339 sock = FakeSocket(body)
340 conn.sock = sock
341 conn.request('GET', '/foo', body)
342 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
343 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000344
Antoine Pitrouead1d622009-09-29 18:44:53 +0000345 def test_send(self):
346 expected = b'this is a test this is only a test'
347 conn = client.HTTPConnection('example.com')
348 sock = FakeSocket(None)
349 conn.sock = sock
350 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000351 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000352 sock.data = b''
353 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000354 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000355 sock.data = b''
356 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000357 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000358
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000359 def test_send_iter(self):
360 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
361 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
362 b'\r\nonetwothree'
363
364 def body():
365 yield b"one"
366 yield b"two"
367 yield b"three"
368
369 conn = client.HTTPConnection('example.com')
370 sock = FakeSocket("")
371 conn.sock = sock
372 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000373 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000374
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800375 def test_send_type_error(self):
376 # See: Issue #12676
377 conn = client.HTTPConnection('example.com')
378 conn.sock = FakeSocket('')
379 with self.assertRaises(TypeError):
380 conn.request('POST', 'test', conn)
381
Christian Heimesa612dc02008-02-24 13:08:18 +0000382 def test_chunked(self):
383 chunked_start = (
384 'HTTP/1.1 200 OK\r\n'
385 'Transfer-Encoding: chunked\r\n\r\n'
386 'a\r\n'
387 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100388 '3\r\n'
389 'd! \r\n'
390 '8\r\n'
391 'and now \r\n'
392 '22\r\n'
393 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000394 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100395 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000396 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000397 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000398 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100399 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000400 resp.close()
401
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100402 # Various read sizes
403 for n in range(1, 12):
404 sock = FakeSocket(chunked_start + '0\r\n')
405 resp = client.HTTPResponse(sock, method="GET")
406 resp.begin()
407 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
408 resp.close()
409
Christian Heimesa612dc02008-02-24 13:08:18 +0000410 for x in ('', 'foo\r\n'):
411 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000412 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000413 resp.begin()
414 try:
415 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000416 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100417 self.assertEqual(i.partial, expected)
418 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
419 self.assertEqual(repr(i), expected_message)
420 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000421 else:
422 self.fail('IncompleteRead expected')
423 finally:
424 resp.close()
425
Antoine Pitrou38d96432011-12-06 22:33:57 +0100426 def test_readinto_chunked(self):
427 chunked_start = (
428 'HTTP/1.1 200 OK\r\n'
429 'Transfer-Encoding: chunked\r\n\r\n'
430 'a\r\n'
431 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100432 '3\r\n'
433 'd! \r\n'
434 '8\r\n'
435 'and now \r\n'
436 '22\r\n'
437 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100438 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100439 expected = b'hello world! and now for something completely different'
440 nexpected = len(expected)
441 b = bytearray(128)
442
Antoine Pitrou38d96432011-12-06 22:33:57 +0100443 sock = FakeSocket(chunked_start + '0\r\n')
444 resp = client.HTTPResponse(sock, method="GET")
445 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100446 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100447 self.assertEqual(b[:nexpected], expected)
448 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100449 resp.close()
450
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100451 # Various read sizes
452 for n in range(1, 12):
453 sock = FakeSocket(chunked_start + '0\r\n')
454 resp = client.HTTPResponse(sock, method="GET")
455 resp.begin()
456 m = memoryview(b)
457 i = resp.readinto(m[0:n])
458 i += resp.readinto(m[i:n + i])
459 i += resp.readinto(m[i:])
460 self.assertEqual(b[:nexpected], expected)
461 self.assertEqual(i, nexpected)
462 resp.close()
463
Antoine Pitrou38d96432011-12-06 22:33:57 +0100464 for x in ('', 'foo\r\n'):
465 sock = FakeSocket(chunked_start + x)
466 resp = client.HTTPResponse(sock, method="GET")
467 resp.begin()
468 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100469 n = resp.readinto(b)
470 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100471 self.assertEqual(i.partial, expected)
472 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
473 self.assertEqual(repr(i), expected_message)
474 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100475 else:
476 self.fail('IncompleteRead expected')
477 finally:
478 resp.close()
479
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000480 def test_chunked_head(self):
481 chunked_start = (
482 'HTTP/1.1 200 OK\r\n'
483 'Transfer-Encoding: chunked\r\n\r\n'
484 'a\r\n'
485 'hello world\r\n'
486 '1\r\n'
487 'd\r\n'
488 )
489 sock = FakeSocket(chunked_start + '0\r\n')
490 resp = client.HTTPResponse(sock, method="HEAD")
491 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000492 self.assertEqual(resp.read(), b'')
493 self.assertEqual(resp.status, 200)
494 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000495 self.assertTrue(resp.isclosed())
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000496
Antoine Pitrou38d96432011-12-06 22:33:57 +0100497 def test_readinto_chunked_head(self):
498 chunked_start = (
499 'HTTP/1.1 200 OK\r\n'
500 'Transfer-Encoding: chunked\r\n\r\n'
501 'a\r\n'
502 'hello world\r\n'
503 '1\r\n'
504 'd\r\n'
505 )
506 sock = FakeSocket(chunked_start + '0\r\n')
507 resp = client.HTTPResponse(sock, method="HEAD")
508 resp.begin()
509 b = bytearray(5)
510 n = resp.readinto(b)
511 self.assertEqual(n, 0)
512 self.assertEqual(bytes(b), b'\x00'*5)
513 self.assertEqual(resp.status, 200)
514 self.assertEqual(resp.reason, 'OK')
515 self.assertTrue(resp.isclosed())
516
Christian Heimesa612dc02008-02-24 13:08:18 +0000517 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000518 sock = FakeSocket(
519 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000520 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000521 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000522 self.assertEqual(resp.read(), b'Hello\r\n')
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100523 self.assertTrue(resp.isclosed())
Christian Heimesa612dc02008-02-24 13:08:18 +0000524
Benjamin Peterson6accb982009-03-02 22:50:25 +0000525 def test_incomplete_read(self):
526 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000527 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000528 resp.begin()
529 try:
530 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000531 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000532 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000533 self.assertEqual(repr(i),
534 "IncompleteRead(7 bytes read, 3 more expected)")
535 self.assertEqual(str(i),
536 "IncompleteRead(7 bytes read, 3 more expected)")
Antoine Pitroubeec61a2013-02-02 22:49:34 +0100537 self.assertTrue(resp.isclosed())
Benjamin Peterson6accb982009-03-02 22:50:25 +0000538 else:
539 self.fail('IncompleteRead expected')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000540
Jeremy Hylton636950f2009-03-28 04:34:21 +0000541 def test_epipe(self):
542 sock = EPipeSocket(
543 "HTTP/1.0 401 Authorization Required\r\n"
544 "Content-type: text/html\r\n"
545 "WWW-Authenticate: Basic realm=\"example\"\r\n",
546 b"Content-Length")
547 conn = client.HTTPConnection("example.com")
548 conn.sock = sock
549 self.assertRaises(socket.error,
550 lambda: conn.request("PUT", "/url", "body"))
551 resp = conn.getresponse()
552 self.assertEqual(401, resp.status)
553 self.assertEqual("Basic realm=\"example\"",
554 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000555
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000556 # Test lines overflowing the max line size (_MAXLINE in http.client)
557
558 def test_overflowing_status_line(self):
559 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
560 resp = client.HTTPResponse(FakeSocket(body))
561 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
562
563 def test_overflowing_header_line(self):
564 body = (
565 'HTTP/1.1 200 OK\r\n'
566 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
567 )
568 resp = client.HTTPResponse(FakeSocket(body))
569 self.assertRaises(client.LineTooLong, resp.begin)
570
571 def test_overflowing_chunked_line(self):
572 body = (
573 'HTTP/1.1 200 OK\r\n'
574 'Transfer-Encoding: chunked\r\n\r\n'
575 + '0' * 65536 + 'a\r\n'
576 'hello world\r\n'
577 '0\r\n'
578 )
579 resp = client.HTTPResponse(FakeSocket(body))
580 resp.begin()
581 self.assertRaises(client.LineTooLong, resp.read)
582
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800583 def test_early_eof(self):
584 # Test httpresponse with no \r\n termination,
585 body = "HTTP/1.1 200 Ok"
586 sock = FakeSocket(body)
587 resp = client.HTTPResponse(sock)
588 resp.begin()
589 self.assertEqual(resp.read(), b'')
590 self.assertTrue(resp.isclosed())
591
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000592class OfflineTest(TestCase):
593 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000594 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000595
Gregory P. Smithb4066372010-01-03 03:28:29 +0000596
597class SourceAddressTest(TestCase):
598 def setUp(self):
599 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
600 self.port = support.bind_port(self.serv)
601 self.source_port = support.find_unused_port()
602 self.serv.listen(5)
603 self.conn = None
604
605 def tearDown(self):
606 if self.conn:
607 self.conn.close()
608 self.conn = None
609 self.serv.close()
610 self.serv = None
611
612 def testHTTPConnectionSourceAddress(self):
613 self.conn = client.HTTPConnection(HOST, self.port,
614 source_address=('', self.source_port))
615 self.conn.connect()
616 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
617
618 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
619 'http.client.HTTPSConnection not defined')
620 def testHTTPSConnectionSourceAddress(self):
621 self.conn = client.HTTPSConnection(HOST, self.port,
622 source_address=('', self.source_port))
623 # We don't test anything here other the constructor not barfing as
624 # this code doesn't deal with setting up an active running SSL server
625 # for an ssl_wrapped connect() to actually return from.
626
627
Guido van Rossumd8faa362007-04-27 19:54:29 +0000628class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000629 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000630
631 def setUp(self):
632 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000633 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000634 self.serv.listen(5)
635
636 def tearDown(self):
637 self.serv.close()
638 self.serv = None
639
640 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000641 # This will prove that the timeout gets through HTTPConnection
642 # and into the socket.
643
Georg Brandlf78e02b2008-06-10 17:40:04 +0000644 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000645 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000646 socket.setdefaulttimeout(30)
647 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000648 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000649 httpConn.connect()
650 finally:
651 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652 self.assertEqual(httpConn.sock.gettimeout(), 30)
653 httpConn.close()
654
Georg Brandlf78e02b2008-06-10 17:40:04 +0000655 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000656 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000657 socket.setdefaulttimeout(30)
658 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000659 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000660 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000661 httpConn.connect()
662 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000663 socket.setdefaulttimeout(None)
664 self.assertEqual(httpConn.sock.gettimeout(), None)
665 httpConn.close()
666
667 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000668 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000669 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000670 self.assertEqual(httpConn.sock.gettimeout(), 30)
671 httpConn.close()
672
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000673
674class HTTPSTest(TestCase):
675
676 def setUp(self):
677 if not hasattr(client, 'HTTPSConnection'):
678 self.skipTest('ssl support required')
679
680 def make_server(self, certfile):
681 from test.ssl_servers import make_https_server
682 return make_https_server(self, certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000683
684 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000685 # simple test to check it's storing the timeout
686 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
687 self.assertEqual(h.timeout, 30)
688
689 def _check_svn_python_org(self, resp):
690 # Just a simple check that everything went fine
691 server_string = resp.getheader('server')
692 self.assertIn('Apache', server_string)
693
694 def test_networked(self):
695 # Default settings: no cert verification is done
696 support.requires('network')
697 with support.transient_internet('svn.python.org'):
698 h = client.HTTPSConnection('svn.python.org', 443)
699 h.request('GET', '/')
700 resp = h.getresponse()
701 self._check_svn_python_org(resp)
702
703 def test_networked_good_cert(self):
704 # We feed a CA cert that validates the server's cert
705 import ssl
706 support.requires('network')
707 with support.transient_internet('svn.python.org'):
708 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
709 context.verify_mode = ssl.CERT_REQUIRED
710 context.load_verify_locations(CACERT_svn_python_org)
711 h = client.HTTPSConnection('svn.python.org', 443, context=context)
712 h.request('GET', '/')
713 resp = h.getresponse()
714 self._check_svn_python_org(resp)
715
716 def test_networked_bad_cert(self):
717 # We feed a "CA" cert that is unrelated to the server's cert
718 import ssl
719 support.requires('network')
720 with support.transient_internet('svn.python.org'):
721 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
722 context.verify_mode = ssl.CERT_REQUIRED
723 context.load_verify_locations(CERT_localhost)
724 h = client.HTTPSConnection('svn.python.org', 443, context=context)
725 with self.assertRaises(ssl.SSLError):
726 h.request('GET', '/')
727
728 def test_local_good_hostname(self):
729 # The (valid) cert validates the HTTP hostname
730 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700731 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000732 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
733 context.verify_mode = ssl.CERT_REQUIRED
734 context.load_verify_locations(CERT_localhost)
735 h = client.HTTPSConnection('localhost', server.port, context=context)
736 h.request('GET', '/nonexistent')
737 resp = h.getresponse()
738 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700739 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000740
741 def test_local_bad_hostname(self):
742 # The (valid) cert doesn't validate the HTTP hostname
743 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700744 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000745 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
746 context.verify_mode = ssl.CERT_REQUIRED
747 context.load_verify_locations(CERT_fakehostname)
748 h = client.HTTPSConnection('localhost', server.port, context=context)
749 with self.assertRaises(ssl.CertificateError):
750 h.request('GET', '/')
751 # Same with explicit check_hostname=True
752 h = client.HTTPSConnection('localhost', server.port, context=context,
753 check_hostname=True)
754 with self.assertRaises(ssl.CertificateError):
755 h.request('GET', '/')
756 # With check_hostname=False, the mismatching is ignored
757 h = client.HTTPSConnection('localhost', server.port, context=context,
758 check_hostname=False)
759 h.request('GET', '/nonexistent')
760 resp = h.getresponse()
761 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700762 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000763
Petri Lehtinene119c402011-10-26 21:29:15 +0300764 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
765 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200766 def test_host_port(self):
767 # Check invalid host_port
768
769 for hp in ("www.python.org:abc", "user:password@www.python.org"):
770 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
771
772 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
773 "fe80::207:e9ff:fe9b", 8000),
774 ("www.python.org:443", "www.python.org", 443),
775 ("www.python.org:", "www.python.org", 443),
776 ("www.python.org", "www.python.org", 443),
777 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
778 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
779 443)):
780 c = client.HTTPSConnection(hp)
781 self.assertEqual(h, c.host)
782 self.assertEqual(p, c.port)
783
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000784
Jeremy Hylton236654b2009-03-27 20:24:34 +0000785class RequestBodyTest(TestCase):
786 """Test cases where a request includes a message body."""
787
788 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000789 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000790 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000791 self.conn.sock = self.sock
792
793 def get_headers_and_fp(self):
794 f = io.BytesIO(self.sock.data)
795 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000796 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000797 return message, f
798
799 def test_manual_content_length(self):
800 # Set an incorrect content-length so that we can verify that
801 # it will not be over-ridden by the library.
802 self.conn.request("PUT", "/url", "body",
803 {"Content-Length": "42"})
804 message, f = self.get_headers_and_fp()
805 self.assertEqual("42", message.get("content-length"))
806 self.assertEqual(4, len(f.read()))
807
808 def test_ascii_body(self):
809 self.conn.request("PUT", "/url", "body")
810 message, f = self.get_headers_and_fp()
811 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000812 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000813 self.assertEqual("4", message.get("content-length"))
814 self.assertEqual(b'body', f.read())
815
816 def test_latin1_body(self):
817 self.conn.request("PUT", "/url", "body\xc1")
818 message, f = self.get_headers_and_fp()
819 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000820 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000821 self.assertEqual("5", message.get("content-length"))
822 self.assertEqual(b'body\xc1', f.read())
823
824 def test_bytes_body(self):
825 self.conn.request("PUT", "/url", b"body\xc1")
826 message, f = self.get_headers_and_fp()
827 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000828 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000829 self.assertEqual("5", message.get("content-length"))
830 self.assertEqual(b'body\xc1', f.read())
831
832 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200833 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000834 with open(support.TESTFN, "w") as f:
835 f.write("body")
836 with open(support.TESTFN) as f:
837 self.conn.request("PUT", "/url", f)
838 message, f = self.get_headers_and_fp()
839 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000840 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000841 self.assertEqual("4", message.get("content-length"))
842 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000843
844 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200845 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000846 with open(support.TESTFN, "wb") as f:
847 f.write(b"body\xc1")
848 with open(support.TESTFN, "rb") as f:
849 self.conn.request("PUT", "/url", f)
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())
Brett Cannon77b7de62010-10-29 23:31:11 +0000853 self.assertEqual("5", message.get("content-length"))
854 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000855
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000856
857class HTTPResponseTest(TestCase):
858
859 def setUp(self):
860 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
861 second-value\r\n\r\nText"
862 sock = FakeSocket(body)
863 self.resp = client.HTTPResponse(sock)
864 self.resp.begin()
865
866 def test_getting_header(self):
867 header = self.resp.getheader('My-Header')
868 self.assertEqual(header, 'first-value, second-value')
869
870 header = self.resp.getheader('My-Header', 'some default')
871 self.assertEqual(header, 'first-value, second-value')
872
873 def test_getting_nonexistent_header_with_string_default(self):
874 header = self.resp.getheader('No-Such-Header', 'default-value')
875 self.assertEqual(header, 'default-value')
876
877 def test_getting_nonexistent_header_with_iterable_default(self):
878 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
879 self.assertEqual(header, 'default, values')
880
881 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
882 self.assertEqual(header, 'default, values')
883
884 def test_getting_nonexistent_header_without_default(self):
885 header = self.resp.getheader('No-Such-Header')
886 self.assertEqual(header, None)
887
888 def test_getting_header_defaultint(self):
889 header = self.resp.getheader('No-Such-Header',default=42)
890 self.assertEqual(header, 42)
891
Jeremy Hylton2c178252004-08-07 16:28:14 +0000892def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000893 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000894 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000895 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000896
Thomas Wouters89f507f2006-12-13 04:49:30 +0000897if __name__ == '__main__':
898 test_main()