blob: e2d644d98c053881e974cd0c781f9bc9a59c9fc7 [file] [log] [blame]
Jeremy Hylton636950f2009-03-28 04:34:21 +00001import errno
Jeremy Hylton7c1692d2009-03-27 21:31:03 +00002from http import client
Jeremy Hylton8fff7922007-08-03 20:56:14 +00003import io
Antoine Pitrou803e6d62010-10-13 10:36:15 +00004import os
Antoine Pitrouead1d622009-09-29 18:44:53 +00005import array
Guido van Rossumd8faa362007-04-27 19:54:29 +00006import socket
Jeremy Hylton121d34a2003-07-08 12:36:58 +00007
Gregory P. Smithb4066372010-01-03 03:28:29 +00008import unittest
9TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000010
Benjamin Petersonee8712c2008-05-20 21:35:26 +000011from test import support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000012
Antoine Pitrou803e6d62010-10-13 10:36:15 +000013here = os.path.dirname(__file__)
14# Self-signed cert file for 'localhost'
15CERT_localhost = os.path.join(here, 'keycert.pem')
16# Self-signed cert file for 'fakehostname'
17CERT_fakehostname = os.path.join(here, 'keycert2.pem')
18# Root cert file (CA) for svn.python.org's cert
19CACERT_svn_python_org = os.path.join(here, 'https_svn_python_org_root.pem')
20
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021HOST = support.HOST
Christian Heimes5e696852008-04-09 08:37:03 +000022
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000023class FakeSocket:
Jeremy Hylton8fff7922007-08-03 20:56:14 +000024 def __init__(self, text, fileclass=io.BytesIO):
25 if isinstance(text, str):
Guido van Rossum39478e82007-08-27 17:23:59 +000026 text = text.encode("ascii")
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000027 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000028 self.fileclass = fileclass
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000029 self.data = b''
Antoine Pitrou90e47742013-01-02 22:10:47 +010030 self.sendall_calls = 0
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000031
Jeremy Hylton2c178252004-08-07 16:28:14 +000032 def sendall(self, data):
Antoine Pitrou90e47742013-01-02 22:10:47 +010033 self.sendall_calls += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +000034 self.data += data
Jeremy Hylton2c178252004-08-07 16:28:14 +000035
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000036 def makefile(self, mode, bufsize=None):
37 if mode != 'r' and mode != 'rb':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000038 raise client.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000039 return self.fileclass(self.text)
40
Jeremy Hylton636950f2009-03-28 04:34:21 +000041class EPipeSocket(FakeSocket):
42
43 def __init__(self, text, pipe_trigger):
44 # When sendall() is called with pipe_trigger, raise EPIPE.
45 FakeSocket.__init__(self, text)
46 self.pipe_trigger = pipe_trigger
47
48 def sendall(self, data):
49 if self.pipe_trigger in data:
Andrew Svetlov0832af62012-12-18 23:10:48 +020050 raise OSError(errno.EPIPE, "gotcha")
Jeremy Hylton636950f2009-03-28 04:34:21 +000051 self.data += data
52
53 def close(self):
54 pass
55
Jeremy Hylton8fff7922007-08-03 20:56:14 +000056class NoEOFStringIO(io.BytesIO):
Jeremy Hylton121d34a2003-07-08 12:36:58 +000057 """Like StringIO, but raises AssertionError on EOF.
58
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000059 This is used below to test that http.client doesn't try to read
Jeremy Hylton121d34a2003-07-08 12:36:58 +000060 more from the underlying file than it should.
61 """
62 def read(self, n=-1):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000063 data = io.BytesIO.read(self, n)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000064 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000065 raise AssertionError('caller tried to read past EOF')
66 return data
67
68 def readline(self, length=None):
Jeremy Hylton8fff7922007-08-03 20:56:14 +000069 data = io.BytesIO.readline(self, length)
Jeremy Hyltonda3f2282007-08-29 17:26:34 +000070 if data == b'':
Jeremy Hylton121d34a2003-07-08 12:36:58 +000071 raise AssertionError('caller tried to read past EOF')
72 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000073
Jeremy Hylton2c178252004-08-07 16:28:14 +000074class HeaderTests(TestCase):
75 def test_auto_headers(self):
76 # Some headers are added automatically, but should not be added by
77 # .request() if they are explicitly set.
78
Jeremy Hylton2c178252004-08-07 16:28:14 +000079 class HeaderCountingBuffer(list):
80 def __init__(self):
81 self.count = {}
82 def append(self, item):
Guido van Rossum022c4742007-08-29 02:00:20 +000083 kv = item.split(b':')
Jeremy Hylton2c178252004-08-07 16:28:14 +000084 if len(kv) > 1:
85 # item is a 'Key: Value' header string
Martin v. Löwisdd5a8602007-06-30 09:22:09 +000086 lcKey = kv[0].decode('ascii').lower()
Jeremy Hylton2c178252004-08-07 16:28:14 +000087 self.count.setdefault(lcKey, 0)
88 self.count[lcKey] += 1
89 list.append(self, item)
90
91 for explicit_header in True, False:
92 for header in 'Content-length', 'Host', 'Accept-encoding':
Jeremy Hylton7c1692d2009-03-27 21:31:03 +000093 conn = client.HTTPConnection('example.com')
Jeremy Hylton2c178252004-08-07 16:28:14 +000094 conn.sock = FakeSocket('blahblahblah')
95 conn._buffer = HeaderCountingBuffer()
96
97 body = 'spamspamspam'
98 headers = {}
99 if explicit_header:
100 headers[header] = str(len(body))
101 conn.request('POST', '/', body, headers)
102 self.assertEqual(conn._buffer.count[header.lower()], 1)
103
Senthil Kumaran5fa4a892012-05-19 16:58:09 +0800104 def test_content_length_0(self):
105
106 class ContentLengthChecker(list):
107 def __init__(self):
108 list.__init__(self)
109 self.content_length = None
110 def append(self, item):
111 kv = item.split(b':', 1)
112 if len(kv) > 1 and kv[0].lower() == b'content-length':
113 self.content_length = kv[1].strip()
114 list.append(self, item)
115
116 # POST with empty body
117 conn = client.HTTPConnection('example.com')
118 conn.sock = FakeSocket(None)
119 conn._buffer = ContentLengthChecker()
120 conn.request('POST', '/', '')
121 self.assertEqual(conn._buffer.content_length, b'0',
122 'Header Content-Length not set')
123
124 # PUT request with empty body
125 conn = client.HTTPConnection('example.com')
126 conn.sock = FakeSocket(None)
127 conn._buffer = ContentLengthChecker()
128 conn.request('PUT', '/', '')
129 self.assertEqual(conn._buffer.content_length, b'0',
130 'Header Content-Length not set')
131
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000132 def test_putheader(self):
133 conn = client.HTTPConnection('example.com')
134 conn.sock = FakeSocket(None)
135 conn.putrequest('GET','/')
136 conn.putheader('Content-length', 42)
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000137 self.assertTrue(b'Content-length: 42' in conn._buffer)
138
Senthil Kumaran74ebd9e2010-11-13 12:27:49 +0000139 def test_ipv6host_header(self):
140 # Default host header on IPv6 transaction should wrapped by [] if
141 # its actual IPv6 address
142 expected = b'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
143 b'Accept-Encoding: identity\r\n\r\n'
144 conn = client.HTTPConnection('[2001::]:81')
145 sock = FakeSocket('')
146 conn.sock = sock
147 conn.request('GET', '/foo')
148 self.assertTrue(sock.data.startswith(expected))
149
150 expected = b'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
151 b'Accept-Encoding: identity\r\n\r\n'
152 conn = client.HTTPConnection('[2001:102A::]')
153 sock = FakeSocket('')
154 conn.sock = sock
155 conn.request('GET', '/foo')
156 self.assertTrue(sock.data.startswith(expected))
157
Senthil Kumaran58d5dbf2010-10-03 18:22:42 +0000158
Thomas Wouters89f507f2006-12-13 04:49:30 +0000159class BasicTest(TestCase):
160 def test_status_lines(self):
161 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000162
Thomas Wouters89f507f2006-12-13 04:49:30 +0000163 body = "HTTP/1.1 200 Ok\r\n\r\nText"
164 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000165 resp = client.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000166 resp.begin()
Jeremy Hylton8fff7922007-08-03 20:56:14 +0000167 self.assertEqual(resp.read(), b"Text")
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000168 self.assertTrue(resp.isclosed())
Jeremy Hyltonba603192003-01-23 18:02:20 +0000169
Thomas Wouters89f507f2006-12-13 04:49:30 +0000170 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
171 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000172 resp = client.HTTPResponse(sock)
173 self.assertRaises(client.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000174
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000175 def test_bad_status_repr(self):
176 exc = client.BadStatusLine('')
Ezio Melottib3aedd42010-11-20 19:04:17 +0000177 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Benjamin Peterson11dbfd42010-03-21 22:50:04 +0000178
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000179 def test_partial_reads(self):
Antoine Pitrou084daa22012-12-15 19:11:54 +0100180 # if we have a length, the system knows when to close itself
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000181 # same behaviour than when we read the whole thing with read()
182 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
183 sock = FakeSocket(body)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000184 resp = client.HTTPResponse(sock)
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000185 resp.begin()
186 self.assertEqual(resp.read(2), b'Te')
187 self.assertFalse(resp.isclosed())
188 self.assertEqual(resp.read(2), b'xt')
189 self.assertTrue(resp.isclosed())
190
Antoine Pitrou38d96432011-12-06 22:33:57 +0100191 def test_partial_readintos(self):
Antoine Pitroud20e7742012-12-15 19:22:30 +0100192 # if we have a length, the system knows when to close itself
Antoine Pitrou38d96432011-12-06 22:33:57 +0100193 # same behaviour than when we read the whole thing with read()
194 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
195 sock = FakeSocket(body)
196 resp = client.HTTPResponse(sock)
197 resp.begin()
198 b = bytearray(2)
199 n = resp.readinto(b)
200 self.assertEqual(n, 2)
201 self.assertEqual(bytes(b), b'Te')
202 self.assertFalse(resp.isclosed())
203 n = resp.readinto(b)
204 self.assertEqual(n, 2)
205 self.assertEqual(bytes(b), b'xt')
206 self.assertTrue(resp.isclosed())
207
Antoine Pitrou084daa22012-12-15 19:11:54 +0100208 def test_partial_reads_no_content_length(self):
209 # when no length is present, the socket should be gracefully closed when
210 # all data was read
211 body = "HTTP/1.1 200 Ok\r\n\r\nText"
212 sock = FakeSocket(body)
213 resp = client.HTTPResponse(sock)
214 resp.begin()
215 self.assertEqual(resp.read(2), b'Te')
216 self.assertFalse(resp.isclosed())
217 self.assertEqual(resp.read(2), b'xt')
218 self.assertEqual(resp.read(1), b'')
219 self.assertTrue(resp.isclosed())
220
Antoine Pitroud20e7742012-12-15 19:22:30 +0100221 def test_partial_readintos_no_content_length(self):
222 # when no length is present, the socket should be gracefully closed when
223 # all data was read
224 body = "HTTP/1.1 200 Ok\r\n\r\nText"
225 sock = FakeSocket(body)
226 resp = client.HTTPResponse(sock)
227 resp.begin()
228 b = bytearray(2)
229 n = resp.readinto(b)
230 self.assertEqual(n, 2)
231 self.assertEqual(bytes(b), b'Te')
232 self.assertFalse(resp.isclosed())
233 n = resp.readinto(b)
234 self.assertEqual(n, 2)
235 self.assertEqual(bytes(b), b'xt')
236 n = resp.readinto(b)
237 self.assertEqual(n, 0)
238 self.assertTrue(resp.isclosed())
239
Thomas Wouters89f507f2006-12-13 04:49:30 +0000240 def test_host_port(self):
241 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000242
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200243 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000244 self.assertRaises(client.InvalidURL, client.HTTPConnection, hp)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000245
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000246 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
247 "fe80::207:e9ff:fe9b", 8000),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000248 ("www.python.org:80", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200249 ("www.python.org:", "www.python.org", 80),
Thomas Wouters89f507f2006-12-13 04:49:30 +0000250 ("www.python.org", "www.python.org", 80),
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200251 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80),
252 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b", 80)):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000253 c = client.HTTPConnection(hp)
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000254 self.assertEqual(h, c.host)
255 self.assertEqual(p, c.port)
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000256
Thomas Wouters89f507f2006-12-13 04:49:30 +0000257 def test_response_headers(self):
258 # test response with multiple message headers with the same field name.
259 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000260 'Set-Cookie: Customer="WILE_E_COYOTE"; '
261 'Version="1"; Path="/acme"\r\n'
Thomas Wouters89f507f2006-12-13 04:49:30 +0000262 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
263 ' Path="/acme"\r\n'
264 '\r\n'
265 'No body\r\n')
266 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
267 ', '
268 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
269 s = FakeSocket(text)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000270 r = client.HTTPResponse(s)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000271 r.begin()
272 cookies = r.getheader("Set-Cookie")
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000273 self.assertEqual(cookies, hdr)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000274
Thomas Wouters89f507f2006-12-13 04:49:30 +0000275 def test_read_head(self):
276 # Test that the library doesn't attempt to read any data
277 # from a HEAD request. (Tickles SF bug #622042.)
278 sock = FakeSocket(
279 'HTTP/1.1 200 OK\r\n'
280 'Content-Length: 14432\r\n'
281 '\r\n',
282 NoEOFStringIO)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000283 resp = client.HTTPResponse(sock, method="HEAD")
Thomas Wouters89f507f2006-12-13 04:49:30 +0000284 resp.begin()
Guido van Rossuma00f1232007-09-12 19:43:09 +0000285 if resp.read():
Thomas Wouters89f507f2006-12-13 04:49:30 +0000286 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000287
Antoine Pitrou38d96432011-12-06 22:33:57 +0100288 def test_readinto_head(self):
289 # Test that the library doesn't attempt to read any data
290 # from a HEAD request. (Tickles SF bug #622042.)
291 sock = FakeSocket(
292 'HTTP/1.1 200 OK\r\n'
293 'Content-Length: 14432\r\n'
294 '\r\n',
295 NoEOFStringIO)
296 resp = client.HTTPResponse(sock, method="HEAD")
297 resp.begin()
298 b = bytearray(5)
299 if resp.readinto(b) != 0:
300 self.fail("Did not expect response from HEAD request")
301 self.assertEqual(bytes(b), b'\x00'*5)
302
Thomas Wouters89f507f2006-12-13 04:49:30 +0000303 def test_send_file(self):
Guido van Rossum022c4742007-08-29 02:00:20 +0000304 expected = (b'GET /foo HTTP/1.1\r\nHost: example.com\r\n'
305 b'Accept-Encoding: identity\r\nContent-Length:')
Thomas Wouters89f507f2006-12-13 04:49:30 +0000306
Brett Cannon77b7de62010-10-29 23:31:11 +0000307 with open(__file__, 'rb') as body:
308 conn = client.HTTPConnection('example.com')
309 sock = FakeSocket(body)
310 conn.sock = sock
311 conn.request('GET', '/foo', body)
312 self.assertTrue(sock.data.startswith(expected), '%r != %r' %
313 (sock.data[:len(expected)], expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000314
Antoine Pitrouead1d622009-09-29 18:44:53 +0000315 def test_send(self):
316 expected = b'this is a test this is only a test'
317 conn = client.HTTPConnection('example.com')
318 sock = FakeSocket(None)
319 conn.sock = sock
320 conn.send(expected)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000321 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000322 sock.data = b''
323 conn.send(array.array('b', expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000324 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000325 sock.data = b''
326 conn.send(io.BytesIO(expected))
Ezio Melottib3aedd42010-11-20 19:04:17 +0000327 self.assertEqual(expected, sock.data)
Antoine Pitrouead1d622009-09-29 18:44:53 +0000328
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000329 def test_send_iter(self):
330 expected = b'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
331 b'Accept-Encoding: identity\r\nContent-Length: 11\r\n' \
332 b'\r\nonetwothree'
333
334 def body():
335 yield b"one"
336 yield b"two"
337 yield b"three"
338
339 conn = client.HTTPConnection('example.com')
340 sock = FakeSocket("")
341 conn.sock = sock
342 conn.request('GET', '/foo', body(), {'Content-Length': '11'})
Victor Stinner04ba9662011-01-04 00:04:46 +0000343 self.assertEqual(sock.data, expected)
Senthil Kumaran7bc0d872010-12-19 10:49:52 +0000344
Senthil Kumaraneb71ad42011-08-02 18:33:41 +0800345 def test_send_type_error(self):
346 # See: Issue #12676
347 conn = client.HTTPConnection('example.com')
348 conn.sock = FakeSocket('')
349 with self.assertRaises(TypeError):
350 conn.request('POST', 'test', conn)
351
Christian Heimesa612dc02008-02-24 13:08:18 +0000352 def test_chunked(self):
353 chunked_start = (
354 'HTTP/1.1 200 OK\r\n'
355 'Transfer-Encoding: chunked\r\n\r\n'
356 'a\r\n'
357 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100358 '3\r\n'
359 'd! \r\n'
360 '8\r\n'
361 'and now \r\n'
362 '22\r\n'
363 'for something completely different\r\n'
Christian Heimesa612dc02008-02-24 13:08:18 +0000364 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100365 expected = b'hello world! and now for something completely different'
Christian Heimesa612dc02008-02-24 13:08:18 +0000366 sock = FakeSocket(chunked_start + '0\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000367 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000368 resp.begin()
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100369 self.assertEqual(resp.read(), expected)
Christian Heimesa612dc02008-02-24 13:08:18 +0000370 resp.close()
371
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100372 # Various read sizes
373 for n in range(1, 12):
374 sock = FakeSocket(chunked_start + '0\r\n')
375 resp = client.HTTPResponse(sock, method="GET")
376 resp.begin()
377 self.assertEqual(resp.read(n) + resp.read(n) + resp.read(), expected)
378 resp.close()
379
Christian Heimesa612dc02008-02-24 13:08:18 +0000380 for x in ('', 'foo\r\n'):
381 sock = FakeSocket(chunked_start + x)
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000382 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000383 resp.begin()
384 try:
385 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000386 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100387 self.assertEqual(i.partial, expected)
388 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
389 self.assertEqual(repr(i), expected_message)
390 self.assertEqual(str(i), expected_message)
Christian Heimesa612dc02008-02-24 13:08:18 +0000391 else:
392 self.fail('IncompleteRead expected')
393 finally:
394 resp.close()
395
Antoine Pitrou38d96432011-12-06 22:33:57 +0100396 def test_readinto_chunked(self):
397 chunked_start = (
398 'HTTP/1.1 200 OK\r\n'
399 'Transfer-Encoding: chunked\r\n\r\n'
400 'a\r\n'
401 'hello worl\r\n'
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100402 '3\r\n'
403 'd! \r\n'
404 '8\r\n'
405 'and now \r\n'
406 '22\r\n'
407 'for something completely different\r\n'
Antoine Pitrou38d96432011-12-06 22:33:57 +0100408 )
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100409 expected = b'hello world! and now for something completely different'
410 nexpected = len(expected)
411 b = bytearray(128)
412
Antoine Pitrou38d96432011-12-06 22:33:57 +0100413 sock = FakeSocket(chunked_start + '0\r\n')
414 resp = client.HTTPResponse(sock, method="GET")
415 resp.begin()
Antoine Pitrou38d96432011-12-06 22:33:57 +0100416 n = resp.readinto(b)
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100417 self.assertEqual(b[:nexpected], expected)
418 self.assertEqual(n, nexpected)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100419 resp.close()
420
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100421 # Various read sizes
422 for n in range(1, 12):
423 sock = FakeSocket(chunked_start + '0\r\n')
424 resp = client.HTTPResponse(sock, method="GET")
425 resp.begin()
426 m = memoryview(b)
427 i = resp.readinto(m[0:n])
428 i += resp.readinto(m[i:n + i])
429 i += resp.readinto(m[i:])
430 self.assertEqual(b[:nexpected], expected)
431 self.assertEqual(i, nexpected)
432 resp.close()
433
Antoine Pitrou38d96432011-12-06 22:33:57 +0100434 for x in ('', 'foo\r\n'):
435 sock = FakeSocket(chunked_start + x)
436 resp = client.HTTPResponse(sock, method="GET")
437 resp.begin()
438 try:
Antoine Pitrou38d96432011-12-06 22:33:57 +0100439 n = resp.readinto(b)
440 except client.IncompleteRead as i:
Antoine Pitrouf7e78182012-01-04 18:57:22 +0100441 self.assertEqual(i.partial, expected)
442 expected_message = 'IncompleteRead(%d bytes read)' % len(expected)
443 self.assertEqual(repr(i), expected_message)
444 self.assertEqual(str(i), expected_message)
Antoine Pitrou38d96432011-12-06 22:33:57 +0100445 else:
446 self.fail('IncompleteRead expected')
447 finally:
448 resp.close()
449
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000450 def test_chunked_head(self):
451 chunked_start = (
452 'HTTP/1.1 200 OK\r\n'
453 'Transfer-Encoding: chunked\r\n\r\n'
454 'a\r\n'
455 'hello world\r\n'
456 '1\r\n'
457 'd\r\n'
458 )
459 sock = FakeSocket(chunked_start + '0\r\n')
460 resp = client.HTTPResponse(sock, method="HEAD")
461 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000462 self.assertEqual(resp.read(), b'')
463 self.assertEqual(resp.status, 200)
464 self.assertEqual(resp.reason, 'OK')
Senthil Kumaran0b998832010-06-04 17:27:11 +0000465 self.assertTrue(resp.isclosed())
Senthil Kumaran71fb6c82010-04-28 17:39:48 +0000466
Antoine Pitrou38d96432011-12-06 22:33:57 +0100467 def test_readinto_chunked_head(self):
468 chunked_start = (
469 'HTTP/1.1 200 OK\r\n'
470 'Transfer-Encoding: chunked\r\n\r\n'
471 'a\r\n'
472 'hello world\r\n'
473 '1\r\n'
474 'd\r\n'
475 )
476 sock = FakeSocket(chunked_start + '0\r\n')
477 resp = client.HTTPResponse(sock, method="HEAD")
478 resp.begin()
479 b = bytearray(5)
480 n = resp.readinto(b)
481 self.assertEqual(n, 0)
482 self.assertEqual(bytes(b), b'\x00'*5)
483 self.assertEqual(resp.status, 200)
484 self.assertEqual(resp.reason, 'OK')
485 self.assertTrue(resp.isclosed())
486
Christian Heimesa612dc02008-02-24 13:08:18 +0000487 def test_negative_content_length(self):
Jeremy Hylton82066952008-12-15 03:08:30 +0000488 sock = FakeSocket(
489 'HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000490 resp = client.HTTPResponse(sock, method="GET")
Christian Heimesa612dc02008-02-24 13:08:18 +0000491 resp.begin()
Ezio Melottib3aedd42010-11-20 19:04:17 +0000492 self.assertEqual(resp.read(), b'Hello\r\n')
Christian Heimesa612dc02008-02-24 13:08:18 +0000493 resp.close()
494
Benjamin Peterson6accb982009-03-02 22:50:25 +0000495 def test_incomplete_read(self):
496 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000497 resp = client.HTTPResponse(sock, method="GET")
Benjamin Peterson6accb982009-03-02 22:50:25 +0000498 resp.begin()
499 try:
500 resp.read()
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000501 except client.IncompleteRead as i:
Ezio Melottib3aedd42010-11-20 19:04:17 +0000502 self.assertEqual(i.partial, b'Hello\r\n')
Benjamin Peterson6accb982009-03-02 22:50:25 +0000503 self.assertEqual(repr(i),
504 "IncompleteRead(7 bytes read, 3 more expected)")
505 self.assertEqual(str(i),
506 "IncompleteRead(7 bytes read, 3 more expected)")
507 else:
508 self.fail('IncompleteRead expected')
509 finally:
510 resp.close()
511
Jeremy Hylton636950f2009-03-28 04:34:21 +0000512 def test_epipe(self):
513 sock = EPipeSocket(
514 "HTTP/1.0 401 Authorization Required\r\n"
515 "Content-type: text/html\r\n"
516 "WWW-Authenticate: Basic realm=\"example\"\r\n",
517 b"Content-Length")
518 conn = client.HTTPConnection("example.com")
519 conn.sock = sock
Andrew Svetlov0832af62012-12-18 23:10:48 +0200520 self.assertRaises(OSError,
Jeremy Hylton636950f2009-03-28 04:34:21 +0000521 lambda: conn.request("PUT", "/url", "body"))
522 resp = conn.getresponse()
523 self.assertEqual(401, resp.status)
524 self.assertEqual("Basic realm=\"example\"",
525 resp.getheader("www-authenticate"))
Christian Heimesa612dc02008-02-24 13:08:18 +0000526
Senthil Kumaran5466bf12010-12-18 16:55:23 +0000527 # Test lines overflowing the max line size (_MAXLINE in http.client)
528
529 def test_overflowing_status_line(self):
530 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
531 resp = client.HTTPResponse(FakeSocket(body))
532 self.assertRaises((client.LineTooLong, client.BadStatusLine), resp.begin)
533
534 def test_overflowing_header_line(self):
535 body = (
536 'HTTP/1.1 200 OK\r\n'
537 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
538 )
539 resp = client.HTTPResponse(FakeSocket(body))
540 self.assertRaises(client.LineTooLong, resp.begin)
541
542 def test_overflowing_chunked_line(self):
543 body = (
544 'HTTP/1.1 200 OK\r\n'
545 'Transfer-Encoding: chunked\r\n\r\n'
546 + '0' * 65536 + 'a\r\n'
547 'hello world\r\n'
548 '0\r\n'
549 )
550 resp = client.HTTPResponse(FakeSocket(body))
551 resp.begin()
552 self.assertRaises(client.LineTooLong, resp.read)
553
Senthil Kumaran9c29f862012-04-29 10:20:46 +0800554 def test_early_eof(self):
555 # Test httpresponse with no \r\n termination,
556 body = "HTTP/1.1 200 Ok"
557 sock = FakeSocket(body)
558 resp = client.HTTPResponse(sock)
559 resp.begin()
560 self.assertEqual(resp.read(), b'')
561 self.assertTrue(resp.isclosed())
562
Antoine Pitrou90e47742013-01-02 22:10:47 +0100563 def test_delayed_ack_opt(self):
564 # Test that Nagle/delayed_ack optimistaion works correctly.
565
566 # For small payloads, it should coalesce the body with
567 # headers, resulting in a single sendall() call
568 conn = client.HTTPConnection('example.com')
569 sock = FakeSocket(None)
570 conn.sock = sock
571 body = b'x' * (conn.mss - 1)
572 conn.request('POST', '/', body)
573 self.assertEqual(sock.sendall_calls, 1)
574
575 # For large payloads, it should send the headers and
576 # then the body, resulting in more than one sendall()
577 # call
578 conn = client.HTTPConnection('example.com')
579 sock = FakeSocket(None)
580 conn.sock = sock
581 body = b'x' * conn.mss
582 conn.request('POST', '/', body)
583 self.assertGreater(sock.sendall_calls, 1)
584
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000585class OfflineTest(TestCase):
586 def test_responses(self):
Ezio Melottib3aedd42010-11-20 19:04:17 +0000587 self.assertEqual(client.responses[client.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000588
Gregory P. Smithb4066372010-01-03 03:28:29 +0000589
590class SourceAddressTest(TestCase):
591 def setUp(self):
592 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
593 self.port = support.bind_port(self.serv)
594 self.source_port = support.find_unused_port()
595 self.serv.listen(5)
596 self.conn = None
597
598 def tearDown(self):
599 if self.conn:
600 self.conn.close()
601 self.conn = None
602 self.serv.close()
603 self.serv = None
604
605 def testHTTPConnectionSourceAddress(self):
606 self.conn = client.HTTPConnection(HOST, self.port,
607 source_address=('', self.source_port))
608 self.conn.connect()
609 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
610
611 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
612 'http.client.HTTPSConnection not defined')
613 def testHTTPSConnectionSourceAddress(self):
614 self.conn = client.HTTPSConnection(HOST, self.port,
615 source_address=('', self.source_port))
616 # We don't test anything here other the constructor not barfing as
617 # this code doesn't deal with setting up an active running SSL server
618 # for an ssl_wrapped connect() to actually return from.
619
620
Guido van Rossumd8faa362007-04-27 19:54:29 +0000621class TimeoutTest(TestCase):
Christian Heimes5e696852008-04-09 08:37:03 +0000622 PORT = None
Guido van Rossumd8faa362007-04-27 19:54:29 +0000623
624 def setUp(self):
625 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000626 TimeoutTest.PORT = support.bind_port(self.serv)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000627 self.serv.listen(5)
628
629 def tearDown(self):
630 self.serv.close()
631 self.serv = None
632
633 def testTimeoutAttribute(self):
Jeremy Hylton3a38c912007-08-14 17:08:07 +0000634 # This will prove that the timeout gets through HTTPConnection
635 # and into the socket.
636
Georg Brandlf78e02b2008-06-10 17:40:04 +0000637 # default -- use global socket timeout
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000638 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000639 socket.setdefaulttimeout(30)
640 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000641 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000642 httpConn.connect()
643 finally:
644 socket.setdefaulttimeout(None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000645 self.assertEqual(httpConn.sock.gettimeout(), 30)
646 httpConn.close()
647
Georg Brandlf78e02b2008-06-10 17:40:04 +0000648 # no timeout -- do not use global socket default
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000649 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000650 socket.setdefaulttimeout(30)
651 try:
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000652 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
Christian Heimes5e696852008-04-09 08:37:03 +0000653 timeout=None)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000654 httpConn.connect()
655 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000656 socket.setdefaulttimeout(None)
657 self.assertEqual(httpConn.sock.gettimeout(), None)
658 httpConn.close()
659
660 # a value
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000661 httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000662 httpConn.connect()
Guido van Rossumd8faa362007-04-27 19:54:29 +0000663 self.assertEqual(httpConn.sock.gettimeout(), 30)
664 httpConn.close()
665
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000666
667class HTTPSTest(TestCase):
668
669 def setUp(self):
670 if not hasattr(client, 'HTTPSConnection'):
671 self.skipTest('ssl support required')
672
673 def make_server(self, certfile):
674 from test.ssl_servers import make_https_server
675 return make_https_server(self, certfile)
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000676
677 def test_attributes(self):
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000678 # simple test to check it's storing the timeout
679 h = client.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
680 self.assertEqual(h.timeout, 30)
681
682 def _check_svn_python_org(self, resp):
683 # Just a simple check that everything went fine
684 server_string = resp.getheader('server')
685 self.assertIn('Apache', server_string)
686
687 def test_networked(self):
688 # Default settings: no cert verification is done
689 support.requires('network')
690 with support.transient_internet('svn.python.org'):
691 h = client.HTTPSConnection('svn.python.org', 443)
692 h.request('GET', '/')
693 resp = h.getresponse()
694 self._check_svn_python_org(resp)
695
696 def test_networked_good_cert(self):
697 # We feed a CA cert that validates the server's cert
698 import ssl
699 support.requires('network')
700 with support.transient_internet('svn.python.org'):
701 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
702 context.verify_mode = ssl.CERT_REQUIRED
703 context.load_verify_locations(CACERT_svn_python_org)
704 h = client.HTTPSConnection('svn.python.org', 443, context=context)
705 h.request('GET', '/')
706 resp = h.getresponse()
707 self._check_svn_python_org(resp)
708
709 def test_networked_bad_cert(self):
710 # We feed a "CA" cert that is unrelated to the server's cert
711 import ssl
712 support.requires('network')
713 with support.transient_internet('svn.python.org'):
714 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
715 context.verify_mode = ssl.CERT_REQUIRED
716 context.load_verify_locations(CERT_localhost)
717 h = client.HTTPSConnection('svn.python.org', 443, context=context)
718 with self.assertRaises(ssl.SSLError):
719 h.request('GET', '/')
720
721 def test_local_good_hostname(self):
722 # The (valid) cert validates the HTTP hostname
723 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700724 server = self.make_server(CERT_localhost)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000725 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
726 context.verify_mode = ssl.CERT_REQUIRED
727 context.load_verify_locations(CERT_localhost)
728 h = client.HTTPSConnection('localhost', server.port, context=context)
729 h.request('GET', '/nonexistent')
730 resp = h.getresponse()
731 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700732 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000733
734 def test_local_bad_hostname(self):
735 # The (valid) cert doesn't validate the HTTP hostname
736 import ssl
Brett Cannon252365b2011-08-04 22:43:11 -0700737 server = self.make_server(CERT_fakehostname)
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000738 context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
739 context.verify_mode = ssl.CERT_REQUIRED
740 context.load_verify_locations(CERT_fakehostname)
741 h = client.HTTPSConnection('localhost', server.port, context=context)
742 with self.assertRaises(ssl.CertificateError):
743 h.request('GET', '/')
744 # Same with explicit check_hostname=True
745 h = client.HTTPSConnection('localhost', server.port, context=context,
746 check_hostname=True)
747 with self.assertRaises(ssl.CertificateError):
748 h.request('GET', '/')
749 # With check_hostname=False, the mismatching is ignored
750 h = client.HTTPSConnection('localhost', server.port, context=context,
751 check_hostname=False)
752 h.request('GET', '/nonexistent')
753 resp = h.getresponse()
754 self.assertEqual(resp.status, 404)
Brett Cannon252365b2011-08-04 22:43:11 -0700755 del server
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000756
Petri Lehtinene119c402011-10-26 21:29:15 +0300757 @unittest.skipIf(not hasattr(client, 'HTTPSConnection'),
758 'http.client.HTTPSConnection not available')
Łukasz Langaa5a9a9c2011-10-18 21:17:39 +0200759 def test_host_port(self):
760 # Check invalid host_port
761
762 for hp in ("www.python.org:abc", "user:password@www.python.org"):
763 self.assertRaises(client.InvalidURL, client.HTTPSConnection, hp)
764
765 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000",
766 "fe80::207:e9ff:fe9b", 8000),
767 ("www.python.org:443", "www.python.org", 443),
768 ("www.python.org:", "www.python.org", 443),
769 ("www.python.org", "www.python.org", 443),
770 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443),
771 ("[fe80::207:e9ff:fe9b]:", "fe80::207:e9ff:fe9b",
772 443)):
773 c = client.HTTPSConnection(hp)
774 self.assertEqual(h, c.host)
775 self.assertEqual(p, c.port)
776
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000777
Jeremy Hylton236654b2009-03-27 20:24:34 +0000778class RequestBodyTest(TestCase):
779 """Test cases where a request includes a message body."""
780
781 def setUp(self):
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000782 self.conn = client.HTTPConnection('example.com')
Jeremy Hylton636950f2009-03-28 04:34:21 +0000783 self.conn.sock = self.sock = FakeSocket("")
Jeremy Hylton236654b2009-03-27 20:24:34 +0000784 self.conn.sock = self.sock
785
786 def get_headers_and_fp(self):
787 f = io.BytesIO(self.sock.data)
788 f.readline() # read the request line
Jeremy Hylton7c1692d2009-03-27 21:31:03 +0000789 message = client.parse_headers(f)
Jeremy Hylton236654b2009-03-27 20:24:34 +0000790 return message, f
791
792 def test_manual_content_length(self):
793 # Set an incorrect content-length so that we can verify that
794 # it will not be over-ridden by the library.
795 self.conn.request("PUT", "/url", "body",
796 {"Content-Length": "42"})
797 message, f = self.get_headers_and_fp()
798 self.assertEqual("42", message.get("content-length"))
799 self.assertEqual(4, len(f.read()))
800
801 def test_ascii_body(self):
802 self.conn.request("PUT", "/url", "body")
803 message, f = self.get_headers_and_fp()
804 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000805 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000806 self.assertEqual("4", message.get("content-length"))
807 self.assertEqual(b'body', f.read())
808
809 def test_latin1_body(self):
810 self.conn.request("PUT", "/url", "body\xc1")
811 message, f = self.get_headers_and_fp()
812 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000813 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000814 self.assertEqual("5", message.get("content-length"))
815 self.assertEqual(b'body\xc1', f.read())
816
817 def test_bytes_body(self):
818 self.conn.request("PUT", "/url", b"body\xc1")
819 message, f = self.get_headers_and_fp()
820 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000821 self.assertIsNone(message.get_charset())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000822 self.assertEqual("5", message.get("content-length"))
823 self.assertEqual(b'body\xc1', f.read())
824
825 def test_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200826 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000827 with open(support.TESTFN, "w") as f:
828 f.write("body")
829 with open(support.TESTFN) as f:
830 self.conn.request("PUT", "/url", f)
831 message, f = self.get_headers_and_fp()
832 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000833 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000834 self.assertEqual("4", message.get("content-length"))
835 self.assertEqual(b'body', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000836
837 def test_binary_file_body(self):
Victor Stinner18d15cb2011-09-21 01:09:04 +0200838 self.addCleanup(support.unlink, support.TESTFN)
Brett Cannon77b7de62010-10-29 23:31:11 +0000839 with open(support.TESTFN, "wb") as f:
840 f.write(b"body\xc1")
841 with open(support.TESTFN, "rb") as f:
842 self.conn.request("PUT", "/url", f)
843 message, f = self.get_headers_and_fp()
844 self.assertEqual("text/plain", message.get_content_type())
Raymond Hettinger7beae8a2011-01-06 05:34:17 +0000845 self.assertIsNone(message.get_charset())
Brett Cannon77b7de62010-10-29 23:31:11 +0000846 self.assertEqual("5", message.get("content-length"))
847 self.assertEqual(b'body\xc1', f.read())
Jeremy Hylton236654b2009-03-27 20:24:34 +0000848
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000849
850class HTTPResponseTest(TestCase):
851
852 def setUp(self):
853 body = "HTTP/1.1 200 Ok\r\nMy-Header: first-value\r\nMy-Header: \
854 second-value\r\n\r\nText"
855 sock = FakeSocket(body)
856 self.resp = client.HTTPResponse(sock)
857 self.resp.begin()
858
859 def test_getting_header(self):
860 header = self.resp.getheader('My-Header')
861 self.assertEqual(header, 'first-value, second-value')
862
863 header = self.resp.getheader('My-Header', 'some default')
864 self.assertEqual(header, 'first-value, second-value')
865
866 def test_getting_nonexistent_header_with_string_default(self):
867 header = self.resp.getheader('No-Such-Header', 'default-value')
868 self.assertEqual(header, 'default-value')
869
870 def test_getting_nonexistent_header_with_iterable_default(self):
871 header = self.resp.getheader('No-Such-Header', ['default', 'values'])
872 self.assertEqual(header, 'default, values')
873
874 header = self.resp.getheader('No-Such-Header', ('default', 'values'))
875 self.assertEqual(header, 'default, values')
876
877 def test_getting_nonexistent_header_without_default(self):
878 header = self.resp.getheader('No-Such-Header')
879 self.assertEqual(header, None)
880
881 def test_getting_header_defaultint(self):
882 header = self.resp.getheader('No-Such-Header',default=42)
883 self.assertEqual(header, 42)
884
Jeremy Hylton2c178252004-08-07 16:28:14 +0000885def test_main(verbose=None):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000886 support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Antoine Pitrou803e6d62010-10-13 10:36:15 +0000887 HTTPSTest, RequestBodyTest, SourceAddressTest,
Senthil Kumaran9f8dc442010-08-02 11:04:58 +0000888 HTTPResponseTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000889
Thomas Wouters89f507f2006-12-13 04:49:30 +0000890if __name__ == '__main__':
891 test_main()