blob: 56e952d1478228e5e84561991a7d479f187537dd [file] [log] [blame]
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00001#!/usr/bin/env python
2
3import unittest
4from test import test_support
Georg Brandl1b06a1d2006-05-03 05:15:10 +00005from test.test_urllib2 import sanepathname2url
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00006
7import socket
8import urllib2
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00009import os
Senthil Kumaran281b5512010-04-20 06:54:59 +000010import sys
11
12TIMEOUT = 60 # seconds
Jeremy Hylton5d9c3032004-08-07 17:40:50 +000013
Neal Norwitz769d0ee2008-01-25 06:37:23 +000014
Facundo Batista6a5a1772008-06-07 13:36:36 +000015def _retry_thrice(func, exc, *args, **kwargs):
Neal Norwitz769d0ee2008-01-25 06:37:23 +000016 for i in range(3):
17 try:
Facundo Batista6a5a1772008-06-07 13:36:36 +000018 return func(*args, **kwargs)
19 except exc, last_exc:
Neal Norwitz769d0ee2008-01-25 06:37:23 +000020 continue
21 except:
22 raise
23 raise last_exc
24
Facundo Batista6a5a1772008-06-07 13:36:36 +000025def _wrap_with_retry_thrice(func, exc):
26 def wrapped(*args, **kwargs):
27 return _retry_thrice(func, exc, *args, **kwargs)
28 return wrapped
29
30# Connecting to remote hosts is flaky. Make it more robust by retrying
31# the connection several times.
32_urlopen_with_retry = _wrap_with_retry_thrice(urllib2.urlopen, urllib2.URLError)
Neal Norwitz769d0ee2008-01-25 06:37:23 +000033
Georg Brandlfa42bd72006-04-30 07:06:11 +000034
35class AuthTests(unittest.TestCase):
36 """Tests urllib2 authentication features."""
37
38## Disabled at the moment since there is no page under python.org which
39## could be used to HTTP authentication.
40#
41# def test_basic_auth(self):
42# import httplib
43#
44# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
45# test_hostport = "www.python.org"
46# test_realm = 'Test Realm'
47# test_user = 'test.test_urllib2net'
48# test_password = 'blah'
49#
50# # failure
51# try:
Neal Norwitz769d0ee2008-01-25 06:37:23 +000052# _urlopen_with_retry(test_url)
Georg Brandlfa42bd72006-04-30 07:06:11 +000053# except urllib2.HTTPError, exc:
54# self.assertEqual(exc.code, 401)
55# else:
56# self.fail("urlopen() should have failed with 401")
57#
58# # success
59# auth_handler = urllib2.HTTPBasicAuthHandler()
60# auth_handler.add_password(test_realm, test_hostport,
61# test_user, test_password)
62# opener = urllib2.build_opener(auth_handler)
63# f = opener.open('http://localhost/')
Neal Norwitz769d0ee2008-01-25 06:37:23 +000064# response = _urlopen_with_retry("http://www.python.org/")
Georg Brandlfa42bd72006-04-30 07:06:11 +000065#
66# # The 'userinfo' URL component is deprecated by RFC 3986 for security
67# # reasons, let's not implement it! (it's already implemented for proxy
68# # specification strings (that is, URLs or authorities specifying a
69# # proxy), so we must keep that)
70# self.assertRaises(httplib.InvalidURL,
71# urllib2.urlopen, "http://evil:thing@example.com")
72
73
Georg Brandldd7b0522007-01-21 10:35:10 +000074class CloseSocketTest(unittest.TestCase):
75
76 def test_close(self):
Georg Brandla4f46e12010-02-07 17:03:15 +000077 import httplib
Georg Brandldd7b0522007-01-21 10:35:10 +000078
79 # calling .close() on urllib2's response objects should close the
80 # underlying socket
81
82 # delve deep into response to fetch socket._socketobject
Neal Norwitz769d0ee2008-01-25 06:37:23 +000083 response = _urlopen_with_retry("http://www.python.org/")
Georg Brandldd7b0522007-01-21 10:35:10 +000084 abused_fileobject = response.fp
Benjamin Peterson5c8da862009-06-30 22:57:08 +000085 self.assertTrue(abused_fileobject.__class__ is socket._fileobject)
Georg Brandldd7b0522007-01-21 10:35:10 +000086 httpresponse = abused_fileobject._sock
Benjamin Peterson5c8da862009-06-30 22:57:08 +000087 self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse)
Georg Brandldd7b0522007-01-21 10:35:10 +000088 fileobject = httpresponse.fp
Benjamin Peterson5c8da862009-06-30 22:57:08 +000089 self.assertTrue(fileobject.__class__ is socket._fileobject)
Georg Brandldd7b0522007-01-21 10:35:10 +000090
Benjamin Peterson5c8da862009-06-30 22:57:08 +000091 self.assertTrue(not fileobject.closed)
Georg Brandldd7b0522007-01-21 10:35:10 +000092 response.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000093 self.assertTrue(fileobject.closed)
Georg Brandldd7b0522007-01-21 10:35:10 +000094
Georg Brandl1b06a1d2006-05-03 05:15:10 +000095class OtherNetworkTests(unittest.TestCase):
96 def setUp(self):
97 if 0: # for debugging
98 import logging
99 logger = logging.getLogger("test_urllib2net")
100 logger.addHandler(logging.StreamHandler())
101
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000102 # XXX The rest of these tests aren't very good -- they don't check much.
103 # They do sometimes catch some major disasters, though.
104
105 def test_ftp(self):
106 urls = [
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000107 'ftp://ftp.kernel.org/pub/linux/kernel/README',
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000108 'ftp://ftp.kernel.org/pub/linux/kernel/non-existent-file',
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000109 #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000110 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
111 '/research-reports/00README-Legal-Rules-Regs',
112 ]
113 self._test_urls(urls, self._extra_handlers())
114
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000115 def test_file(self):
116 TESTFN = test_support.TESTFN
117 f = open(TESTFN, 'w')
118 try:
119 f.write('hi there\n')
120 f.close()
121 urls = [
122 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000123 ('file:///nonsensename/etc/passwd', None, urllib2.URLError),
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000124 ]
Facundo Batista6a5a1772008-06-07 13:36:36 +0000125 self._test_urls(urls, self._extra_handlers(), retry=True)
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000126 finally:
127 os.remove(TESTFN)
128
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000129 # XXX Following test depends on machine configurations that are internal
130 # to CNRI. Need to set up a public server with the right authentication
131 # configuration for test purposes.
132
133## def test_cnri(self):
134## if socket.gethostname() == 'bitdiddle':
135## localhost = 'bitdiddle.cnri.reston.va.us'
136## elif socket.gethostname() == 'bitdiddle.concentric.net':
137## localhost = 'localhost'
138## else:
139## localhost = None
140## if localhost is not None:
141## urls = [
142## 'file://%s/etc/passwd' % localhost,
143## 'http://%s/simple/' % localhost,
144## 'http://%s/digest/' % localhost,
145## 'http://%s/not/found.h' % localhost,
146## ]
147
148## bauth = HTTPBasicAuthHandler()
149## bauth.add_password('basic_test_realm', localhost, 'jhylton',
150## 'password')
151## dauth = HTTPDigestAuthHandler()
152## dauth.add_password('digest_test_realm', localhost, 'jhylton',
153## 'password')
154
155## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
156
Senthil Kumaranb4ec7ee2010-08-08 11:43:45 +0000157 def test_urlwithfrag(self):
158 urlwith_frag = "http://docs.python.org/glossary.html#glossary"
159 req = urllib2.Request(urlwith_frag)
160 res = urllib2.urlopen(req)
161 self.assertEqual(res.geturl(),
162 "http://docs.python.org/glossary.html")
163
Senthil Kumarand389cb52010-09-21 01:38:15 +0000164 def test_fileno(self):
165 req = urllib2.Request("http://www.python.org")
166 opener = urllib2.build_opener()
167 res = opener.open(req)
168 try:
169 res.fileno()
170 except AttributeError:
171 self.fail("HTTPResponse object should return a valid fileno")
172 finally:
173 res.close()
174
Facundo Batista6a5a1772008-06-07 13:36:36 +0000175 def _test_urls(self, urls, handlers, retry=True):
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000176 import time
177 import logging
178 debug = logging.getLogger("test_urllib2").debug
179
Facundo Batista6a5a1772008-06-07 13:36:36 +0000180 urlopen = urllib2.build_opener(*handlers).open
181 if retry:
182 urlopen = _wrap_with_retry_thrice(urlopen, urllib2.URLError)
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000183
184 for url in urls:
185 if isinstance(url, tuple):
186 url, req, expected_err = url
187 else:
188 req = expected_err = None
189 debug(url)
190 try:
Senthil Kumaran281b5512010-04-20 06:54:59 +0000191 f = urlopen(url, req, TIMEOUT)
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000192 except EnvironmentError, err:
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000193 debug(err)
194 if expected_err:
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000195 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
196 (expected_err, url, req, type(err), err))
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000197 self.assertIsInstance(err, expected_err, msg)
Senthil Kumaran281b5512010-04-20 06:54:59 +0000198 except urllib2.URLError as err:
199 if isinstance(err[0], socket.timeout):
200 print >>sys.stderr, "<timeout: %s>" % url
201 continue
202 else:
203 raise
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000204 else:
Senthil Kumaran281b5512010-04-20 06:54:59 +0000205 try:
Antoine Pitrouc818ed42010-09-07 21:40:25 +0000206 with test_support.transient_internet(url):
Senthil Kumaran281b5512010-04-20 06:54:59 +0000207 buf = f.read()
208 debug("read %d bytes" % len(buf))
209 except socket.timeout:
210 print >>sys.stderr, "<timeout: %s>" % url
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000211 f.close()
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000212 debug("******** next url coming up...")
213 time.sleep(0.1)
214
215 def _extra_handlers(self):
216 handlers = []
217
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000218 cfh = urllib2.CacheFTPHandler()
219 cfh.setTimeout(1)
220 handlers.append(cfh)
221
222 return handlers
223
Gregory P. Smith0001c2e2008-03-28 08:00:44 +0000224
Facundo Batista10951d52007-06-06 17:15:23 +0000225class TimeoutTest(unittest.TestCase):
226 def test_http_basic(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000227 self.assertTrue(socket.getdefaulttimeout() is None)
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000228 u = _urlopen_with_retry("http://www.python.org")
Facundo Batista10951d52007-06-06 17:15:23 +0000229 self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
230
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000231 def test_http_default_timeout(self):
232 self.assertTrue(socket.getdefaulttimeout() is None)
233 socket.setdefaulttimeout(60)
234 try:
235 u = _urlopen_with_retry("http://www.python.org")
236 finally:
237 socket.setdefaulttimeout(None)
238 self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60)
239
240 def test_http_no_timeout(self):
241 self.assertTrue(socket.getdefaulttimeout() is None)
Facundo Batista10951d52007-06-06 17:15:23 +0000242 socket.setdefaulttimeout(60)
243 try:
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000244 u = _urlopen_with_retry("http://www.python.org", timeout=None)
Facundo Batista10951d52007-06-06 17:15:23 +0000245 finally:
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000246 socket.setdefaulttimeout(None)
247 self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
Facundo Batista10951d52007-06-06 17:15:23 +0000248
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000249 def test_http_timeout(self):
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000250 u = _urlopen_with_retry("http://www.python.org", timeout=120)
Facundo Batista10951d52007-06-06 17:15:23 +0000251 self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120)
252
Martin v. Löwis7bc26b92010-04-08 17:40:54 +0000253 FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/"
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000254
Facundo Batista10951d52007-06-06 17:15:23 +0000255 def test_ftp_basic(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000256 self.assertTrue(socket.getdefaulttimeout() is None)
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000257 u = _urlopen_with_retry(self.FTP_HOST)
Facundo Batista10951d52007-06-06 17:15:23 +0000258 self.assertTrue(u.fp.fp._sock.gettimeout() is None)
259
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000260 def test_ftp_default_timeout(self):
261 self.assertTrue(socket.getdefaulttimeout() is None)
262 socket.setdefaulttimeout(60)
263 try:
264 u = _urlopen_with_retry(self.FTP_HOST)
265 finally:
266 socket.setdefaulttimeout(None)
267 self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
268
269 def test_ftp_no_timeout(self):
270 self.assertTrue(socket.getdefaulttimeout() is None)
Facundo Batista10951d52007-06-06 17:15:23 +0000271 socket.setdefaulttimeout(60)
272 try:
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000273 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Facundo Batista10951d52007-06-06 17:15:23 +0000274 finally:
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000275 socket.setdefaulttimeout(None)
Facundo Batista10951d52007-06-06 17:15:23 +0000276 self.assertTrue(u.fp.fp._sock.gettimeout() is None)
277
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000278 def test_ftp_timeout(self):
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000279 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Facundo Batista10951d52007-06-06 17:15:23 +0000280 self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
281
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000282
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000283def test_main():
284 test_support.requires("network")
Gregory P. Smith0001c2e2008-03-28 08:00:44 +0000285 test_support.run_unittest(AuthTests,
Georg Brandldd7b0522007-01-21 10:35:10 +0000286 OtherNetworkTests,
287 CloseSocketTest,
Facundo Batista10951d52007-06-06 17:15:23 +0000288 TimeoutTest,
Georg Brandldd7b0522007-01-21 10:35:10 +0000289 )
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000290
291if __name__ == "__main__":
292 test_main()