blob: bd48fea24123fa390aa50272adf8baaa707a859b [file] [log] [blame]
Senthil Kumaranaa5f49e2010-10-03 18:26:07 +00001import httplib
Antoine Pitrou72481782009-09-29 17:48:18 +00002import array
Jeremy Hylton79fa2b62001-04-13 14:57:44 +00003import httplib
4import StringIO
Facundo Batista07c78be2007-03-23 18:54:07 +00005import socket
Victor Stinner2c6aee92010-07-24 02:46:16 +00006import errno
Jeremy Hylton121d34a2003-07-08 12:36:58 +00007
Gregory P. Smith9d325212010-01-03 02:06:07 +00008import unittest
9TestCase = unittest.TestCase
Jeremy Hylton2c178252004-08-07 16:28:14 +000010
11from test import test_support
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000012
Trent Nelsone41b0062008-04-08 23:47:30 +000013HOST = test_support.HOST
14
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000015class FakeSocket:
Jeremy Hylton121d34a2003-07-08 12:36:58 +000016 def __init__(self, text, fileclass=StringIO.StringIO):
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000017 self.text = text
Jeremy Hylton121d34a2003-07-08 12:36:58 +000018 self.fileclass = fileclass
Martin v. Löwis040a9272006-11-12 10:32:47 +000019 self.data = ''
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000020
Jeremy Hylton2c178252004-08-07 16:28:14 +000021 def sendall(self, data):
Antoine Pitrou72481782009-09-29 17:48:18 +000022 self.data += ''.join(data)
Jeremy Hylton2c178252004-08-07 16:28:14 +000023
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000024 def makefile(self, mode, bufsize=None):
25 if mode != 'r' and mode != 'rb':
Neal Norwitz28bb5722002-04-01 19:00:50 +000026 raise httplib.UnimplementedFileMode()
Jeremy Hylton121d34a2003-07-08 12:36:58 +000027 return self.fileclass(self.text)
28
Victor Stinner2c6aee92010-07-24 02:46:16 +000029class EPipeSocket(FakeSocket):
30
31 def __init__(self, text, pipe_trigger):
32 # When sendall() is called with pipe_trigger, raise EPIPE.
33 FakeSocket.__init__(self, text)
34 self.pipe_trigger = pipe_trigger
35
36 def sendall(self, data):
37 if self.pipe_trigger in data:
38 raise socket.error(errno.EPIPE, "gotcha")
39 self.data += data
40
41 def close(self):
42 pass
43
Jeremy Hylton121d34a2003-07-08 12:36:58 +000044class NoEOFStringIO(StringIO.StringIO):
45 """Like StringIO, but raises AssertionError on EOF.
46
47 This is used below to test that httplib doesn't try to read
48 more from the underlying file than it should.
49 """
50 def read(self, n=-1):
51 data = StringIO.StringIO.read(self, n)
52 if data == '':
53 raise AssertionError('caller tried to read past EOF')
54 return data
55
56 def readline(self, length=None):
57 data = StringIO.StringIO.readline(self, length)
58 if data == '':
59 raise AssertionError('caller tried to read past EOF')
60 return data
Jeremy Hylton79fa2b62001-04-13 14:57:44 +000061
Jeremy Hylton2c178252004-08-07 16:28:14 +000062
63class HeaderTests(TestCase):
64 def test_auto_headers(self):
65 # Some headers are added automatically, but should not be added by
66 # .request() if they are explicitly set.
67
Jeremy Hylton2c178252004-08-07 16:28:14 +000068 class HeaderCountingBuffer(list):
69 def __init__(self):
70 self.count = {}
71 def append(self, item):
72 kv = item.split(':')
73 if len(kv) > 1:
74 # item is a 'Key: Value' header string
75 lcKey = kv[0].lower()
76 self.count.setdefault(lcKey, 0)
77 self.count[lcKey] += 1
78 list.append(self, item)
79
80 for explicit_header in True, False:
81 for header in 'Content-length', 'Host', 'Accept-encoding':
82 conn = httplib.HTTPConnection('example.com')
83 conn.sock = FakeSocket('blahblahblah')
84 conn._buffer = HeaderCountingBuffer()
85
86 body = 'spamspamspam'
87 headers = {}
88 if explicit_header:
89 headers[header] = str(len(body))
90 conn.request('POST', '/', body, headers)
91 self.assertEqual(conn._buffer.count[header.lower()], 1)
92
Senthil Kumaran618802d2012-05-19 16:52:21 +080093 def test_content_length_0(self):
94
95 class ContentLengthChecker(list):
96 def __init__(self):
97 list.__init__(self)
98 self.content_length = None
99 def append(self, item):
100 kv = item.split(':', 1)
101 if len(kv) > 1 and kv[0].lower() == 'content-length':
102 self.content_length = kv[1].strip()
103 list.append(self, item)
104
105 # POST with empty body
106 conn = httplib.HTTPConnection('example.com')
107 conn.sock = FakeSocket(None)
108 conn._buffer = ContentLengthChecker()
109 conn.request('POST', '/', '')
110 self.assertEqual(conn._buffer.content_length, '0',
111 'Header Content-Length not set')
112
113 # PUT request with empty body
114 conn = httplib.HTTPConnection('example.com')
115 conn.sock = FakeSocket(None)
116 conn._buffer = ContentLengthChecker()
117 conn.request('PUT', '/', '')
118 self.assertEqual(conn._buffer.content_length, '0',
119 'Header Content-Length not set')
120
Senthil Kumaranaa5f49e2010-10-03 18:26:07 +0000121 def test_putheader(self):
122 conn = httplib.HTTPConnection('example.com')
123 conn.sock = FakeSocket(None)
124 conn.putrequest('GET','/')
125 conn.putheader('Content-length',42)
126 self.assertTrue('Content-length: 42' in conn._buffer)
127
Senthil Kumaran501bfd82010-11-14 03:31:52 +0000128 def test_ipv6host_header(self):
129 # Default host header on IPv6 transaction should wrapped by [] if
130 # its actual IPv6 address
131 expected = 'GET /foo HTTP/1.1\r\nHost: [2001::]:81\r\n' \
132 'Accept-Encoding: identity\r\n\r\n'
133 conn = httplib.HTTPConnection('[2001::]:81')
134 sock = FakeSocket('')
135 conn.sock = sock
136 conn.request('GET', '/foo')
137 self.assertTrue(sock.data.startswith(expected))
138
139 expected = 'GET /foo HTTP/1.1\r\nHost: [2001:102A::]\r\n' \
140 'Accept-Encoding: identity\r\n\r\n'
141 conn = httplib.HTTPConnection('[2001:102A::]')
142 sock = FakeSocket('')
143 conn.sock = sock
144 conn.request('GET', '/foo')
145 self.assertTrue(sock.data.startswith(expected))
146
147
Georg Brandl71a20892006-10-29 20:24:01 +0000148class BasicTest(TestCase):
149 def test_status_lines(self):
150 # Test HTTP status lines
Jeremy Hylton79fa2b62001-04-13 14:57:44 +0000151
Georg Brandl71a20892006-10-29 20:24:01 +0000152 body = "HTTP/1.1 200 Ok\r\n\r\nText"
153 sock = FakeSocket(body)
154 resp = httplib.HTTPResponse(sock)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000155 resp.begin()
Georg Brandl71a20892006-10-29 20:24:01 +0000156 self.assertEqual(resp.read(), 'Text')
Facundo Batista70665902007-10-18 03:16:03 +0000157 self.assertTrue(resp.isclosed())
Jeremy Hyltonba603192003-01-23 18:02:20 +0000158
Georg Brandl71a20892006-10-29 20:24:01 +0000159 body = "HTTP/1.1 400.100 Not Ok\r\n\r\nText"
160 sock = FakeSocket(body)
161 resp = httplib.HTTPResponse(sock)
162 self.assertRaises(httplib.BadStatusLine, resp.begin)
Jeremy Hyltonba603192003-01-23 18:02:20 +0000163
Dirkjan Ochtmanebc73dc2010-02-24 04:49:00 +0000164 def test_bad_status_repr(self):
165 exc = httplib.BadStatusLine('')
Ezio Melotti2623a372010-11-21 13:34:58 +0000166 self.assertEqual(repr(exc), '''BadStatusLine("\'\'",)''')
Dirkjan Ochtmanebc73dc2010-02-24 04:49:00 +0000167
Facundo Batista70665902007-10-18 03:16:03 +0000168 def test_partial_reads(self):
Antoine Pitrou4113d2b2012-12-15 19:11:54 +0100169 # if we have a length, the system knows when to close itself
Facundo Batista70665902007-10-18 03:16:03 +0000170 # same behaviour than when we read the whole thing with read()
171 body = "HTTP/1.1 200 Ok\r\nContent-Length: 4\r\n\r\nText"
172 sock = FakeSocket(body)
173 resp = httplib.HTTPResponse(sock)
174 resp.begin()
175 self.assertEqual(resp.read(2), 'Te')
176 self.assertFalse(resp.isclosed())
177 self.assertEqual(resp.read(2), 'xt')
178 self.assertTrue(resp.isclosed())
179
Antoine Pitrou4113d2b2012-12-15 19:11:54 +0100180 def test_partial_reads_no_content_length(self):
181 # when no length is present, the socket should be gracefully closed when
182 # all data was read
183 body = "HTTP/1.1 200 Ok\r\n\r\nText"
184 sock = FakeSocket(body)
185 resp = httplib.HTTPResponse(sock)
186 resp.begin()
187 self.assertEqual(resp.read(2), 'Te')
188 self.assertFalse(resp.isclosed())
189 self.assertEqual(resp.read(2), 'xt')
190 self.assertEqual(resp.read(1), '')
191 self.assertTrue(resp.isclosed())
192
Georg Brandl71a20892006-10-29 20:24:01 +0000193 def test_host_port(self):
194 # Check invalid host_port
Jeremy Hyltonba603192003-01-23 18:02:20 +0000195
Łukasz Langa7a153902011-10-18 17:16:00 +0200196 # Note that httplib does not accept user:password@ in the host-port.
197 for hp in ("www.python.org:abc", "user:password@www.python.org"):
Georg Brandl71a20892006-10-29 20:24:01 +0000198 self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
199
Jeremy Hylton21d2e592008-11-29 00:09:16 +0000200 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
201 8000),
Georg Brandl71a20892006-10-29 20:24:01 +0000202 ("www.python.org:80", "www.python.org", 80),
203 ("www.python.org", "www.python.org", 80),
Łukasz Langa7a153902011-10-18 17:16:00 +0200204 ("www.python.org:", "www.python.org", 80),
Georg Brandl71a20892006-10-29 20:24:01 +0000205 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 80)):
Martin v. Löwis74a249e2004-09-14 21:45:36 +0000206 http = httplib.HTTP(hp)
Georg Brandl71a20892006-10-29 20:24:01 +0000207 c = http._conn
Jeremy Hylton21d2e592008-11-29 00:09:16 +0000208 if h != c.host:
209 self.fail("Host incorrectly parsed: %s != %s" % (h, c.host))
210 if p != c.port:
211 self.fail("Port incorrectly parsed: %s != %s" % (p, c.host))
Skip Montanaro10e6e0e2004-09-14 16:32:02 +0000212
Georg Brandl71a20892006-10-29 20:24:01 +0000213 def test_response_headers(self):
214 # test response with multiple message headers with the same field name.
215 text = ('HTTP/1.1 200 OK\r\n'
Jeremy Hylton21d2e592008-11-29 00:09:16 +0000216 'Set-Cookie: Customer="WILE_E_COYOTE";'
217 ' Version="1"; Path="/acme"\r\n'
Georg Brandl71a20892006-10-29 20:24:01 +0000218 'Set-Cookie: Part_Number="Rocket_Launcher_0001"; Version="1";'
219 ' Path="/acme"\r\n'
220 '\r\n'
221 'No body\r\n')
222 hdr = ('Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"'
223 ', '
224 'Part_Number="Rocket_Launcher_0001"; Version="1"; Path="/acme"')
225 s = FakeSocket(text)
226 r = httplib.HTTPResponse(s)
227 r.begin()
228 cookies = r.getheader("Set-Cookie")
229 if cookies != hdr:
230 self.fail("multiple headers not combined properly")
Jeremy Hyltonba603192003-01-23 18:02:20 +0000231
Georg Brandl71a20892006-10-29 20:24:01 +0000232 def test_read_head(self):
233 # Test that the library doesn't attempt to read any data
234 # from a HEAD request. (Tickles SF bug #622042.)
235 sock = FakeSocket(
236 'HTTP/1.1 200 OK\r\n'
237 'Content-Length: 14432\r\n'
238 '\r\n',
239 NoEOFStringIO)
240 resp = httplib.HTTPResponse(sock, method="HEAD")
241 resp.begin()
242 if resp.read() != "":
243 self.fail("Did not expect response from HEAD request")
Jeremy Hyltonc1b2cb92003-05-05 16:13:58 +0000244
Martin v. Löwis040a9272006-11-12 10:32:47 +0000245 def test_send_file(self):
246 expected = 'GET /foo HTTP/1.1\r\nHost: example.com\r\n' \
247 'Accept-Encoding: identity\r\nContent-Length:'
248
249 body = open(__file__, 'rb')
250 conn = httplib.HTTPConnection('example.com')
251 sock = FakeSocket(body)
252 conn.sock = sock
253 conn.request('GET', '/foo', body)
254 self.assertTrue(sock.data.startswith(expected))
Jeremy Hylton2c178252004-08-07 16:28:14 +0000255
Antoine Pitrou72481782009-09-29 17:48:18 +0000256 def test_send(self):
257 expected = 'this is a test this is only a test'
258 conn = httplib.HTTPConnection('example.com')
259 sock = FakeSocket(None)
260 conn.sock = sock
261 conn.send(expected)
Ezio Melotti2623a372010-11-21 13:34:58 +0000262 self.assertEqual(expected, sock.data)
Antoine Pitrou72481782009-09-29 17:48:18 +0000263 sock.data = ''
264 conn.send(array.array('c', expected))
Ezio Melotti2623a372010-11-21 13:34:58 +0000265 self.assertEqual(expected, sock.data)
Antoine Pitrou72481782009-09-29 17:48:18 +0000266 sock.data = ''
267 conn.send(StringIO.StringIO(expected))
Ezio Melotti2623a372010-11-21 13:34:58 +0000268 self.assertEqual(expected, sock.data)
Antoine Pitrou72481782009-09-29 17:48:18 +0000269
Georg Brandl23635032008-02-24 00:03:22 +0000270 def test_chunked(self):
271 chunked_start = (
272 'HTTP/1.1 200 OK\r\n'
273 'Transfer-Encoding: chunked\r\n\r\n'
274 'a\r\n'
275 'hello worl\r\n'
276 '1\r\n'
277 'd\r\n'
278 )
279 sock = FakeSocket(chunked_start + '0\r\n')
280 resp = httplib.HTTPResponse(sock, method="GET")
281 resp.begin()
Ezio Melotti2623a372010-11-21 13:34:58 +0000282 self.assertEqual(resp.read(), 'hello world')
Georg Brandl23635032008-02-24 00:03:22 +0000283 resp.close()
284
285 for x in ('', 'foo\r\n'):
286 sock = FakeSocket(chunked_start + x)
287 resp = httplib.HTTPResponse(sock, method="GET")
288 resp.begin()
289 try:
290 resp.read()
291 except httplib.IncompleteRead, i:
Ezio Melotti2623a372010-11-21 13:34:58 +0000292 self.assertEqual(i.partial, 'hello world')
Benjamin Peterson7d49bba2009-03-02 22:41:42 +0000293 self.assertEqual(repr(i),'IncompleteRead(11 bytes read)')
294 self.assertEqual(str(i),'IncompleteRead(11 bytes read)')
Georg Brandl23635032008-02-24 00:03:22 +0000295 else:
296 self.fail('IncompleteRead expected')
297 finally:
298 resp.close()
299
Senthil Kumaraned9204342010-04-28 17:20:43 +0000300 def test_chunked_head(self):
301 chunked_start = (
302 'HTTP/1.1 200 OK\r\n'
303 'Transfer-Encoding: chunked\r\n\r\n'
304 'a\r\n'
305 'hello world\r\n'
306 '1\r\n'
307 'd\r\n'
308 )
309 sock = FakeSocket(chunked_start + '0\r\n')
310 resp = httplib.HTTPResponse(sock, method="HEAD")
311 resp.begin()
Ezio Melotti2623a372010-11-21 13:34:58 +0000312 self.assertEqual(resp.read(), '')
313 self.assertEqual(resp.status, 200)
314 self.assertEqual(resp.reason, 'OK')
Senthil Kumaranfb695012010-06-04 17:17:09 +0000315 self.assertTrue(resp.isclosed())
Senthil Kumaraned9204342010-04-28 17:20:43 +0000316
Georg Brandl8c460d52008-02-24 00:14:24 +0000317 def test_negative_content_length(self):
Jeremy Hylton21d2e592008-11-29 00:09:16 +0000318 sock = FakeSocket('HTTP/1.1 200 OK\r\n'
319 'Content-Length: -1\r\n\r\nHello\r\n')
Georg Brandl8c460d52008-02-24 00:14:24 +0000320 resp = httplib.HTTPResponse(sock, method="GET")
321 resp.begin()
Ezio Melotti2623a372010-11-21 13:34:58 +0000322 self.assertEqual(resp.read(), 'Hello\r\n')
Georg Brandl8c460d52008-02-24 00:14:24 +0000323 resp.close()
324
Benjamin Peterson7d49bba2009-03-02 22:41:42 +0000325 def test_incomplete_read(self):
326 sock = FakeSocket('HTTP/1.1 200 OK\r\nContent-Length: 10\r\n\r\nHello\r\n')
327 resp = httplib.HTTPResponse(sock, method="GET")
328 resp.begin()
329 try:
330 resp.read()
331 except httplib.IncompleteRead as i:
Ezio Melotti2623a372010-11-21 13:34:58 +0000332 self.assertEqual(i.partial, 'Hello\r\n')
Benjamin Peterson7d49bba2009-03-02 22:41:42 +0000333 self.assertEqual(repr(i),
334 "IncompleteRead(7 bytes read, 3 more expected)")
335 self.assertEqual(str(i),
336 "IncompleteRead(7 bytes read, 3 more expected)")
337 else:
338 self.fail('IncompleteRead expected')
339 finally:
340 resp.close()
341
Victor Stinner2c6aee92010-07-24 02:46:16 +0000342 def test_epipe(self):
343 sock = EPipeSocket(
344 "HTTP/1.0 401 Authorization Required\r\n"
345 "Content-type: text/html\r\n"
346 "WWW-Authenticate: Basic realm=\"example\"\r\n",
347 b"Content-Length")
348 conn = httplib.HTTPConnection("example.com")
349 conn.sock = sock
350 self.assertRaises(socket.error,
351 lambda: conn.request("PUT", "/url", "body"))
352 resp = conn.getresponse()
353 self.assertEqual(401, resp.status)
354 self.assertEqual("Basic realm=\"example\"",
355 resp.getheader("www-authenticate"))
356
Senthil Kumarand389cb52010-09-21 01:38:15 +0000357 def test_filenoattr(self):
358 # Just test the fileno attribute in the HTTPResponse Object.
359 body = "HTTP/1.1 200 Ok\r\n\r\nText"
360 sock = FakeSocket(body)
361 resp = httplib.HTTPResponse(sock)
362 self.assertTrue(hasattr(resp,'fileno'),
363 'HTTPResponse should expose a fileno attribute')
Georg Brandl23635032008-02-24 00:03:22 +0000364
Antoine Pitroud7b6ac62010-12-18 18:18:21 +0000365 # Test lines overflowing the max line size (_MAXLINE in http.client)
366
367 def test_overflowing_status_line(self):
368 self.skipTest("disabled for HTTP 0.9 support")
369 body = "HTTP/1.1 200 Ok" + "k" * 65536 + "\r\n"
370 resp = httplib.HTTPResponse(FakeSocket(body))
371 self.assertRaises((httplib.LineTooLong, httplib.BadStatusLine), resp.begin)
372
373 def test_overflowing_header_line(self):
374 body = (
375 'HTTP/1.1 200 OK\r\n'
376 'X-Foo: bar' + 'r' * 65536 + '\r\n\r\n'
377 )
378 resp = httplib.HTTPResponse(FakeSocket(body))
379 self.assertRaises(httplib.LineTooLong, resp.begin)
380
381 def test_overflowing_chunked_line(self):
382 body = (
383 'HTTP/1.1 200 OK\r\n'
384 'Transfer-Encoding: chunked\r\n\r\n'
385 + '0' * 65536 + 'a\r\n'
386 'hello world\r\n'
387 '0\r\n'
388 )
389 resp = httplib.HTTPResponse(FakeSocket(body))
390 resp.begin()
391 self.assertRaises(httplib.LineTooLong, resp.read)
392
Senthil Kumaranf5aaf6f2012-04-29 10:15:31 +0800393 def test_early_eof(self):
394 # Test httpresponse with no \r\n termination,
395 body = "HTTP/1.1 200 Ok"
396 sock = FakeSocket(body)
397 resp = httplib.HTTPResponse(sock)
398 resp.begin()
399 self.assertEqual(resp.read(), '')
400 self.assertTrue(resp.isclosed())
Antoine Pitroud7b6ac62010-12-18 18:18:21 +0000401
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000402class OfflineTest(TestCase):
403 def test_responses(self):
Ezio Melotti2623a372010-11-21 13:34:58 +0000404 self.assertEqual(httplib.responses[httplib.NOT_FOUND], "Not Found")
Georg Brandl4cbd1e32006-02-17 22:01:08 +0000405
Gregory P. Smith9d325212010-01-03 02:06:07 +0000406
407class SourceAddressTest(TestCase):
408 def setUp(self):
409 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
410 self.port = test_support.bind_port(self.serv)
411 self.source_port = test_support.find_unused_port()
412 self.serv.listen(5)
413 self.conn = None
414
415 def tearDown(self):
416 if self.conn:
417 self.conn.close()
418 self.conn = None
419 self.serv.close()
420 self.serv = None
421
422 def testHTTPConnectionSourceAddress(self):
423 self.conn = httplib.HTTPConnection(HOST, self.port,
424 source_address=('', self.source_port))
425 self.conn.connect()
426 self.assertEqual(self.conn.sock.getsockname()[1], self.source_port)
427
428 @unittest.skipIf(not hasattr(httplib, 'HTTPSConnection'),
429 'httplib.HTTPSConnection not defined')
430 def testHTTPSConnectionSourceAddress(self):
431 self.conn = httplib.HTTPSConnection(HOST, self.port,
432 source_address=('', self.source_port))
433 # We don't test anything here other the constructor not barfing as
434 # this code doesn't deal with setting up an active running SSL server
435 # for an ssl_wrapped connect() to actually return from.
436
437
Facundo Batista07c78be2007-03-23 18:54:07 +0000438class TimeoutTest(TestCase):
Trent Nelsone41b0062008-04-08 23:47:30 +0000439 PORT = None
Neal Norwitz0d4c06e2007-04-25 06:30:05 +0000440
Facundo Batista07c78be2007-03-23 18:54:07 +0000441 def setUp(self):
442 self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Trent Nelson6c4a7c62008-04-09 00:34:53 +0000443 TimeoutTest.PORT = test_support.bind_port(self.serv)
Facundo Batistaf1966292007-03-25 03:20:05 +0000444 self.serv.listen(5)
Facundo Batista07c78be2007-03-23 18:54:07 +0000445
446 def tearDown(self):
447 self.serv.close()
448 self.serv = None
449
450 def testTimeoutAttribute(self):
451 '''This will prove that the timeout gets through
452 HTTPConnection and into the socket.
453 '''
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000454 # default -- use global socket timeout
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000455 self.assertTrue(socket.getdefaulttimeout() is None)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000456 socket.setdefaulttimeout(30)
457 try:
458 httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT)
459 httpConn.connect()
460 finally:
461 socket.setdefaulttimeout(None)
Facundo Batista14553b02007-03-23 20:23:08 +0000462 self.assertEqual(httpConn.sock.gettimeout(), 30)
Facundo Batistaf1966292007-03-25 03:20:05 +0000463 httpConn.close()
Facundo Batista07c78be2007-03-23 18:54:07 +0000464
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000465 # no timeout -- do not use global socket default
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000466 self.assertTrue(socket.getdefaulttimeout() is None)
Facundo Batista14553b02007-03-23 20:23:08 +0000467 socket.setdefaulttimeout(30)
468 try:
Trent Nelson6c4a7c62008-04-09 00:34:53 +0000469 httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT,
470 timeout=None)
Facundo Batista14553b02007-03-23 20:23:08 +0000471 httpConn.connect()
472 finally:
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000473 socket.setdefaulttimeout(None)
474 self.assertEqual(httpConn.sock.gettimeout(), None)
475 httpConn.close()
476
477 # a value
478 httpConn = httplib.HTTPConnection(HOST, TimeoutTest.PORT, timeout=30)
479 httpConn.connect()
Facundo Batista14553b02007-03-23 20:23:08 +0000480 self.assertEqual(httpConn.sock.gettimeout(), 30)
Facundo Batistaf1966292007-03-25 03:20:05 +0000481 httpConn.close()
Facundo Batista07c78be2007-03-23 18:54:07 +0000482
483
Facundo Batista70f996b2007-05-21 17:32:32 +0000484class HTTPSTimeoutTest(TestCase):
485# XXX Here should be tests for HTTPS, there isn't any right now!
486
487 def test_attributes(self):
488 # simple test to check it's storing it
Thomas Wouters628e3bb2007-08-30 22:35:31 +0000489 if hasattr(httplib, 'HTTPSConnection'):
Trent Nelsone41b0062008-04-08 23:47:30 +0000490 h = httplib.HTTPSConnection(HOST, TimeoutTest.PORT, timeout=30)
Thomas Wouters628e3bb2007-08-30 22:35:31 +0000491 self.assertEqual(h.timeout, 30)
Facundo Batista70f996b2007-05-21 17:32:32 +0000492
Petri Lehtinen6d089df2011-10-26 21:25:56 +0300493 @unittest.skipIf(not hasattr(httplib, 'HTTPS'), 'httplib.HTTPS not available')
Łukasz Langa7a153902011-10-18 17:16:00 +0200494 def test_host_port(self):
495 # Check invalid host_port
496
497 # Note that httplib does not accept user:password@ in the host-port.
498 for hp in ("www.python.org:abc", "user:password@www.python.org"):
499 self.assertRaises(httplib.InvalidURL, httplib.HTTP, hp)
500
501 for hp, h, p in (("[fe80::207:e9ff:fe9b]:8000", "fe80::207:e9ff:fe9b",
502 8000),
503 ("pypi.python.org:443", "pypi.python.org", 443),
504 ("pypi.python.org", "pypi.python.org", 443),
505 ("pypi.python.org:", "pypi.python.org", 443),
506 ("[fe80::207:e9ff:fe9b]", "fe80::207:e9ff:fe9b", 443)):
507 http = httplib.HTTPS(hp)
508 c = http._conn
509 if h != c.host:
510 self.fail("Host incorrectly parsed: %s != %s" % (h, c.host))
511 if p != c.port:
512 self.fail("Port incorrectly parsed: %s != %s" % (p, c.host))
513
514
Jeremy Hylton2c178252004-08-07 16:28:14 +0000515def test_main(verbose=None):
Trent Nelsone41b0062008-04-08 23:47:30 +0000516 test_support.run_unittest(HeaderTests, OfflineTest, BasicTest, TimeoutTest,
Gregory P. Smith9d325212010-01-03 02:06:07 +0000517 HTTPSTimeoutTest, SourceAddressTest)
Jeremy Hylton2c178252004-08-07 16:28:14 +0000518
Georg Brandl71a20892006-10-29 20:24:01 +0000519if __name__ == '__main__':
520 test_main()