blob: 4f81c2823824da378b557c6dfe4f5712646d813b [file] [log] [blame]
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00001import unittest
2from test import test_support
Georg Brandl1b06a1d2006-05-03 05:15:10 +00003from test.test_urllib2 import sanepathname2url
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00004
5import socket
6import urllib2
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00007import os
Senthil Kumaran281b5512010-04-20 06:54:59 +00008import sys
9
10TIMEOUT = 60 # seconds
Jeremy Hylton5d9c3032004-08-07 17:40:50 +000011
Neal Norwitz769d0ee2008-01-25 06:37:23 +000012
Facundo Batista6a5a1772008-06-07 13:36:36 +000013def _retry_thrice(func, exc, *args, **kwargs):
Neal Norwitz769d0ee2008-01-25 06:37:23 +000014 for i in range(3):
15 try:
Facundo Batista6a5a1772008-06-07 13:36:36 +000016 return func(*args, **kwargs)
17 except exc, last_exc:
Neal Norwitz769d0ee2008-01-25 06:37:23 +000018 continue
19 except:
20 raise
21 raise last_exc
22
Facundo Batista6a5a1772008-06-07 13:36:36 +000023def _wrap_with_retry_thrice(func, exc):
24 def wrapped(*args, **kwargs):
25 return _retry_thrice(func, exc, *args, **kwargs)
26 return wrapped
27
28# Connecting to remote hosts is flaky. Make it more robust by retrying
29# the connection several times.
30_urlopen_with_retry = _wrap_with_retry_thrice(urllib2.urlopen, urllib2.URLError)
Neal Norwitz769d0ee2008-01-25 06:37:23 +000031
Georg Brandlfa42bd72006-04-30 07:06:11 +000032
33class AuthTests(unittest.TestCase):
34 """Tests urllib2 authentication features."""
35
36## Disabled at the moment since there is no page under python.org which
37## could be used to HTTP authentication.
38#
39# def test_basic_auth(self):
40# import httplib
41#
42# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
43# test_hostport = "www.python.org"
44# test_realm = 'Test Realm'
45# test_user = 'test.test_urllib2net'
46# test_password = 'blah'
47#
48# # failure
49# try:
Neal Norwitz769d0ee2008-01-25 06:37:23 +000050# _urlopen_with_retry(test_url)
Georg Brandlfa42bd72006-04-30 07:06:11 +000051# except urllib2.HTTPError, exc:
52# self.assertEqual(exc.code, 401)
53# else:
54# self.fail("urlopen() should have failed with 401")
55#
56# # success
57# auth_handler = urllib2.HTTPBasicAuthHandler()
58# auth_handler.add_password(test_realm, test_hostport,
59# test_user, test_password)
60# opener = urllib2.build_opener(auth_handler)
61# f = opener.open('http://localhost/')
Neal Norwitz769d0ee2008-01-25 06:37:23 +000062# response = _urlopen_with_retry("http://www.python.org/")
Georg Brandlfa42bd72006-04-30 07:06:11 +000063#
64# # The 'userinfo' URL component is deprecated by RFC 3986 for security
65# # reasons, let's not implement it! (it's already implemented for proxy
66# # specification strings (that is, URLs or authorities specifying a
67# # proxy), so we must keep that)
68# self.assertRaises(httplib.InvalidURL,
69# urllib2.urlopen, "http://evil:thing@example.com")
70
71
Georg Brandldd7b0522007-01-21 10:35:10 +000072class CloseSocketTest(unittest.TestCase):
73
74 def test_close(self):
Georg Brandla4f46e12010-02-07 17:03:15 +000075 import httplib
Georg Brandldd7b0522007-01-21 10:35:10 +000076
77 # calling .close() on urllib2's response objects should close the
78 # underlying socket
79
80 # delve deep into response to fetch socket._socketobject
Neal Norwitz769d0ee2008-01-25 06:37:23 +000081 response = _urlopen_with_retry("http://www.python.org/")
Georg Brandldd7b0522007-01-21 10:35:10 +000082 abused_fileobject = response.fp
Serhiy Storchaka528bed82014-02-08 14:49:55 +020083 self.assertIs(abused_fileobject.__class__, socket._fileobject)
Georg Brandldd7b0522007-01-21 10:35:10 +000084 httpresponse = abused_fileobject._sock
Serhiy Storchaka528bed82014-02-08 14:49:55 +020085 self.assertIs(httpresponse.__class__, httplib.HTTPResponse)
Georg Brandldd7b0522007-01-21 10:35:10 +000086 fileobject = httpresponse.fp
Serhiy Storchaka528bed82014-02-08 14:49:55 +020087 self.assertIs(fileobject.__class__, socket._fileobject)
Georg Brandldd7b0522007-01-21 10:35:10 +000088
Benjamin Peterson5c8da862009-06-30 22:57:08 +000089 self.assertTrue(not fileobject.closed)
Georg Brandldd7b0522007-01-21 10:35:10 +000090 response.close()
Benjamin Peterson5c8da862009-06-30 22:57:08 +000091 self.assertTrue(fileobject.closed)
Georg Brandldd7b0522007-01-21 10:35:10 +000092
Georg Brandl1b06a1d2006-05-03 05:15:10 +000093class OtherNetworkTests(unittest.TestCase):
94 def setUp(self):
95 if 0: # for debugging
96 import logging
97 logger = logging.getLogger("test_urllib2net")
98 logger.addHandler(logging.StreamHandler())
99
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000100 # XXX The rest of these tests aren't very good -- they don't check much.
101 # They do sometimes catch some major disasters, though.
102
103 def test_ftp(self):
104 urls = [
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000105 'ftp://ftp.kernel.org/pub/linux/kernel/README',
Mark Dickinson3e4caeb2009-02-21 20:27:01 +0000106 'ftp://ftp.kernel.org/pub/linux/kernel/non-existent-file',
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000107 #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000108 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
109 '/research-reports/00README-Legal-Rules-Regs',
110 ]
111 self._test_urls(urls, self._extra_handlers())
112
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000113 def test_file(self):
114 TESTFN = test_support.TESTFN
115 f = open(TESTFN, 'w')
116 try:
117 f.write('hi there\n')
118 f.close()
119 urls = [
120 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
Gregory P. Smithe9fef692007-09-09 23:36:46 +0000121 ('file:///nonsensename/etc/passwd', None, urllib2.URLError),
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000122 ]
Facundo Batista6a5a1772008-06-07 13:36:36 +0000123 self._test_urls(urls, self._extra_handlers(), retry=True)
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000124 finally:
125 os.remove(TESTFN)
126
Senthil Kumaran58c60622012-01-21 11:43:02 +0800127 self.assertRaises(ValueError, urllib2.urlopen,'./relative_path/to/file')
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):
Georg Brandl08114d42012-10-28 10:51:35 +0100158 urlwith_frag = "http://docs.python.org/2/glossary.html#glossary"
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000159 with test_support.transient_internet(urlwith_frag):
160 req = urllib2.Request(urlwith_frag)
161 res = urllib2.urlopen(req)
162 self.assertEqual(res.geturl(),
Georg Brandl08114d42012-10-28 10:51:35 +0100163 "http://docs.python.org/2/glossary.html#glossary")
Senthil Kumaranb4ec7ee2010-08-08 11:43:45 +0000164
Senthil Kumarand389cb52010-09-21 01:38:15 +0000165 def test_fileno(self):
166 req = urllib2.Request("http://www.python.org")
167 opener = urllib2.build_opener()
168 res = opener.open(req)
169 try:
170 res.fileno()
171 except AttributeError:
172 self.fail("HTTPResponse object should return a valid fileno")
173 finally:
174 res.close()
175
Senthil Kumaran176c73d2010-09-27 01:40:59 +0000176 def test_custom_headers(self):
177 url = "http://www.example.com"
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000178 with test_support.transient_internet(url):
179 opener = urllib2.build_opener()
180 request = urllib2.Request(url)
181 self.assertFalse(request.header_items())
182 opener.open(request)
183 self.assertTrue(request.header_items())
184 self.assertTrue(request.has_header('User-agent'))
185 request.add_header('User-Agent','Test-Agent')
186 opener.open(request)
187 self.assertEqual(request.get_header('User-agent'),'Test-Agent')
Senthil Kumaran176c73d2010-09-27 01:40:59 +0000188
Senthil Kumaran7d7702b2011-07-27 09:37:17 +0800189 def test_sites_no_connection_close(self):
190 # Some sites do not send Connection: close header.
191 # Verify that those work properly. (#issue12576)
192
Senthil Kumaran23c21042011-07-31 11:48:54 +0800193 URL = 'http://www.imdb.com' # No Connection:close
Benjamin Peterson3facb8c2011-07-30 23:39:39 -0500194 with test_support.transient_internet(URL):
Senthil Kumaran23c21042011-07-31 11:48:54 +0800195 req = urllib2.urlopen(URL)
196 res = req.read()
197 self.assertTrue(res)
Senthil Kumaran7d7702b2011-07-27 09:37:17 +0800198
Facundo Batista6a5a1772008-06-07 13:36:36 +0000199 def _test_urls(self, urls, handlers, retry=True):
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000200 import time
201 import logging
202 debug = logging.getLogger("test_urllib2").debug
203
Facundo Batista6a5a1772008-06-07 13:36:36 +0000204 urlopen = urllib2.build_opener(*handlers).open
205 if retry:
206 urlopen = _wrap_with_retry_thrice(urlopen, urllib2.URLError)
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000207
208 for url in urls:
209 if isinstance(url, tuple):
210 url, req, expected_err = url
211 else:
212 req = expected_err = None
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000213 with test_support.transient_internet(url):
214 debug(url)
Senthil Kumaran281b5512010-04-20 06:54:59 +0000215 try:
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000216 f = urlopen(url, req, TIMEOUT)
217 except EnvironmentError as err:
218 debug(err)
219 if expected_err:
220 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
221 (expected_err, url, req, type(err), err))
222 self.assertIsInstance(err, expected_err, msg)
223 except urllib2.URLError as err:
224 if isinstance(err[0], socket.timeout):
225 print >>sys.stderr, "<timeout: %s>" % url
226 continue
227 else:
228 raise
229 else:
230 try:
231 with test_support.transient_internet(url):
232 buf = f.read()
233 debug("read %d bytes" % len(buf))
234 except socket.timeout:
235 print >>sys.stderr, "<timeout: %s>" % url
236 f.close()
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000237 debug("******** next url coming up...")
238 time.sleep(0.1)
239
240 def _extra_handlers(self):
241 handlers = []
242
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000243 cfh = urllib2.CacheFTPHandler()
Nadeem Vawdab42c53e2011-07-23 15:51:16 +0200244 self.addCleanup(cfh.clear_cache)
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000245 cfh.setTimeout(1)
246 handlers.append(cfh)
247
248 return handlers
249
Gregory P. Smith0001c2e2008-03-28 08:00:44 +0000250
Facundo Batista10951d52007-06-06 17:15:23 +0000251class TimeoutTest(unittest.TestCase):
252 def test_http_basic(self):
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200253 self.assertIsNone(socket.getdefaulttimeout())
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000254 url = "http://www.python.org"
255 with test_support.transient_internet(url, timeout=None):
256 u = _urlopen_with_retry(url)
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200257 self.assertIsNone(u.fp._sock.fp._sock.gettimeout())
Facundo Batista10951d52007-06-06 17:15:23 +0000258
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000259 def test_http_default_timeout(self):
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200260 self.assertIsNone(socket.getdefaulttimeout())
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000261 url = "http://www.python.org"
262 with test_support.transient_internet(url):
263 socket.setdefaulttimeout(60)
264 try:
265 u = _urlopen_with_retry(url)
266 finally:
267 socket.setdefaulttimeout(None)
268 self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000269
270 def test_http_no_timeout(self):
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200271 self.assertIsNone(socket.getdefaulttimeout())
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000272 url = "http://www.python.org"
273 with test_support.transient_internet(url):
274 socket.setdefaulttimeout(60)
275 try:
276 u = _urlopen_with_retry(url, timeout=None)
277 finally:
278 socket.setdefaulttimeout(None)
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200279 self.assertIsNone(u.fp._sock.fp._sock.gettimeout())
Facundo Batista10951d52007-06-06 17:15:23 +0000280
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000281 def test_http_timeout(self):
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000282 url = "http://www.python.org"
283 with test_support.transient_internet(url):
284 u = _urlopen_with_retry(url, timeout=120)
285 self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120)
Facundo Batista10951d52007-06-06 17:15:23 +0000286
Martin v. Löwis7bc26b92010-04-08 17:40:54 +0000287 FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/"
Neal Norwitz769d0ee2008-01-25 06:37:23 +0000288
Facundo Batista10951d52007-06-06 17:15:23 +0000289 def test_ftp_basic(self):
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200290 self.assertIsNone(socket.getdefaulttimeout())
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000291 with test_support.transient_internet(self.FTP_HOST, timeout=None):
292 u = _urlopen_with_retry(self.FTP_HOST)
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200293 self.assertIsNone(u.fp.fp._sock.gettimeout())
Facundo Batista10951d52007-06-06 17:15:23 +0000294
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000295 def test_ftp_default_timeout(self):
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200296 self.assertIsNone(socket.getdefaulttimeout())
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000297 with test_support.transient_internet(self.FTP_HOST):
298 socket.setdefaulttimeout(60)
299 try:
300 u = _urlopen_with_retry(self.FTP_HOST)
301 finally:
302 socket.setdefaulttimeout(None)
303 self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000304
305 def test_ftp_no_timeout(self):
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200306 self.assertIsNone(socket.getdefaulttimeout(),)
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000307 with test_support.transient_internet(self.FTP_HOST):
308 socket.setdefaulttimeout(60)
309 try:
310 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
311 finally:
312 socket.setdefaulttimeout(None)
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200313 self.assertIsNone(u.fp.fp._sock.gettimeout())
Facundo Batista10951d52007-06-06 17:15:23 +0000314
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000315 def test_ftp_timeout(self):
Antoine Pitrou9f3f9c52010-10-31 13:58:00 +0000316 with test_support.transient_internet(self.FTP_HOST):
317 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
318 self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
Facundo Batista10951d52007-06-06 17:15:23 +0000319
Georg Brandl1b06a1d2006-05-03 05:15:10 +0000320
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000321def test_main():
322 test_support.requires("network")
Gregory P. Smith0001c2e2008-03-28 08:00:44 +0000323 test_support.run_unittest(AuthTests,
Georg Brandldd7b0522007-01-21 10:35:10 +0000324 OtherNetworkTests,
325 CloseSocketTest,
Facundo Batista10951d52007-06-06 17:15:23 +0000326 TimeoutTest,
Georg Brandldd7b0522007-01-21 10:35:10 +0000327 )
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000328
329if __name__ == "__main__":
330 test_main()