blob: cad83fd5aa6a88407d0b1388f667dbbbcfe0c239 [file] [log] [blame]
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Thomas Wouters477c8d52006-05-27 19:21:47 +00003from test.test_urllib2 import sanepathname2url
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00004
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00005import os
Jeremy Hylton1afc1692008-06-18 20:49:58 +00006import socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +00007import urllib.error
8import urllib.request
Senthil Kumaranb8f7ea62010-04-20 10:35:49 +00009import sys
Berker Peksagb77983d2014-10-10 14:34:16 +030010
doko@ubuntu.come5751482013-12-26 17:37:11 +010011support.requires("network")
12
Senthil Kumaranb8f7ea62010-04-20 10:35:49 +000013TIMEOUT = 60 # seconds
Jeremy Hylton5d9c3032004-08-07 17:40:50 +000014
Christian Heimes969fe572008-01-25 11:23:10 +000015
Georg Brandlc28e1fa2008-06-10 19:20:26 +000016def _retry_thrice(func, exc, *args, **kwargs):
Christian Heimes969fe572008-01-25 11:23:10 +000017 for i in range(3):
18 try:
Georg Brandlc28e1fa2008-06-10 19:20:26 +000019 return func(*args, **kwargs)
20 except exc as e:
Neal Norwitz2f142582008-01-26 19:49:41 +000021 last_exc = e
Christian Heimes969fe572008-01-25 11:23:10 +000022 continue
Christian Heimes969fe572008-01-25 11:23:10 +000023 raise last_exc
24
Georg Brandlc28e1fa2008-06-10 19:20:26 +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.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000032_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
33 urllib.error.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000034
Thomas Wouters477c8d52006-05-27 19:21:47 +000035
36class AuthTests(unittest.TestCase):
37 """Tests urllib2 authentication features."""
38
39## Disabled at the moment since there is no page under python.org which
40## could be used to HTTP authentication.
41#
42# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000043# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000044#
45# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
46# test_hostport = "www.python.org"
47# test_realm = 'Test Realm'
48# test_user = 'test.test_urllib2net'
49# test_password = 'blah'
50#
51# # failure
52# try:
Christian Heimes969fe572008-01-25 11:23:10 +000053# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000054# except urllib2.HTTPError, exc:
55# self.assertEqual(exc.code, 401)
56# else:
57# self.fail("urlopen() should have failed with 401")
58#
59# # success
60# auth_handler = urllib2.HTTPBasicAuthHandler()
61# auth_handler.add_password(test_realm, test_hostport,
62# test_user, test_password)
63# opener = urllib2.build_opener(auth_handler)
64# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000065# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000066#
67# # The 'userinfo' URL component is deprecated by RFC 3986 for security
68# # reasons, let's not implement it! (it's already implemented for proxy
69# # specification strings (that is, URLs or authorities specifying a
70# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000071# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000072# urllib2.urlopen, "http://evil:thing@example.com")
73
74
Thomas Woutersb2137042007-02-01 18:02:27 +000075class CloseSocketTest(unittest.TestCase):
76
77 def test_close(self):
Thomas Woutersb2137042007-02-01 18:02:27 +000078 # calling .close() on urllib2's response objects should close the
79 # underlying socket
Ned Deily5a507f02014-03-26 23:31:39 -070080 url = "http://www.example.com/"
Nadeem Vawda61baebd2012-01-25 08:02:05 +020081 with support.transient_internet(url):
82 response = _urlopen_with_retry(url)
83 sock = response.fp
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +020084 self.assertFalse(sock.closed)
Nadeem Vawda61baebd2012-01-25 08:02:05 +020085 response.close()
86 self.assertTrue(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000087
Thomas Wouters477c8d52006-05-27 19:21:47 +000088class OtherNetworkTests(unittest.TestCase):
89 def setUp(self):
90 if 0: # for debugging
91 import logging
92 logger = logging.getLogger("test_urllib2net")
93 logger.addHandler(logging.StreamHandler())
94
Thomas Wouters477c8d52006-05-27 19:21:47 +000095 # XXX The rest of these tests aren't very good -- they don't check much.
96 # They do sometimes catch some major disasters, though.
97
98 def test_ftp(self):
99 urls = [
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200100 'ftp://ftp.debian.org/debian/README',
101 ('ftp://ftp.debian.org/debian/non-existent-file',
102 None, urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000103 ]
104 self._test_urls(urls, self._extra_handlers())
105
Thomas Wouters477c8d52006-05-27 19:21:47 +0000106 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000107 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000108 f = open(TESTFN, 'w')
109 try:
110 f.write('hi there\n')
111 f.close()
112 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000113 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
114 ('file:///nonsensename/etc/passwd', None,
115 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000117 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000118 finally:
119 os.remove(TESTFN)
120
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800121 self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
122
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 # XXX Following test depends on machine configurations that are internal
124 # to CNRI. Need to set up a public server with the right authentication
125 # configuration for test purposes.
126
127## def test_cnri(self):
128## if socket.gethostname() == 'bitdiddle':
129## localhost = 'bitdiddle.cnri.reston.va.us'
130## elif socket.gethostname() == 'bitdiddle.concentric.net':
131## localhost = 'localhost'
132## else:
133## localhost = None
134## if localhost is not None:
135## urls = [
136## 'file://%s/etc/passwd' % localhost,
137## 'http://%s/simple/' % localhost,
138## 'http://%s/digest/' % localhost,
139## 'http://%s/not/found.h' % localhost,
140## ]
141
142## bauth = HTTPBasicAuthHandler()
143## bauth.add_password('basic_test_realm', localhost, 'jhylton',
144## 'password')
145## dauth = HTTPDigestAuthHandler()
146## dauth.add_password('digest_test_realm', localhost, 'jhylton',
147## 'password')
148
149## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
150
Senthil Kumarand95cc752010-08-08 11:27:53 +0000151 def test_urlwithfrag(self):
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500152 urlwith_frag = "http://www.pythontest.net/index.html#frag"
Georg Brandl5be365f2010-10-28 14:55:02 +0000153 with support.transient_internet(urlwith_frag):
154 req = urllib.request.Request(urlwith_frag)
155 res = urllib.request.urlopen(req)
156 self.assertEqual(res.geturl(),
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500157 "http://www.pythontest.net/index.html#frag")
Senthil Kumarand95cc752010-08-08 11:27:53 +0000158
Senthil Kumaran83070752013-05-24 09:14:12 -0700159 def test_redirect_url_withfrag(self):
Benjamin Petersonb811a972014-11-05 13:10:08 -0500160 redirect_url_with_frag = "http://www.pythontest.net/redir/with_frag/"
Senthil Kumaran83070752013-05-24 09:14:12 -0700161 with support.transient_internet(redirect_url_with_frag):
162 req = urllib.request.Request(redirect_url_with_frag)
163 res = urllib.request.urlopen(req)
164 self.assertEqual(res.geturl(),
Benjamin Petersonb811a972014-11-05 13:10:08 -0500165 "http://www.pythontest.net/elsewhere/#frag")
Senthil Kumaran83070752013-05-24 09:14:12 -0700166
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000167 def test_custom_headers(self):
168 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000169 with support.transient_internet(url):
170 opener = urllib.request.build_opener()
171 request = urllib.request.Request(url)
172 self.assertFalse(request.header_items())
173 opener.open(request)
174 self.assertTrue(request.header_items())
175 self.assertTrue(request.has_header('User-agent'))
176 request.add_header('User-Agent','Test-Agent')
177 opener.open(request)
178 self.assertEqual(request.get_header('User-agent'),'Test-Agent')
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000179
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800180 def test_sites_no_connection_close(self):
181 # Some sites do not send Connection: close header.
182 # Verify that those work properly. (#issue12576)
183
Senthil Kumarane324c572011-07-31 11:45:14 +0800184 URL = 'http://www.imdb.com' # mangles Connection:close
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800185
Senthil Kumarane324c572011-07-31 11:45:14 +0800186 with support.transient_internet(URL):
187 try:
188 with urllib.request.urlopen(URL) as res:
189 pass
190 except ValueError as e:
191 self.fail("urlopen failed for site not sending \
192 Connection:close")
193 else:
194 self.assertTrue(res)
195
196 req = urllib.request.urlopen(URL)
197 res = req.read()
198 self.assertTrue(res)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800199
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000200 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000201 import time
202 import logging
203 debug = logging.getLogger("test_urllib2").debug
204
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000205 urlopen = urllib.request.build_opener(*handlers).open
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000206 if retry:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000207 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208
209 for url in urls:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200210 with self.subTest(url=url):
211 if isinstance(url, tuple):
212 url, req, expected_err = url
Georg Brandl5be365f2010-10-28 14:55:02 +0000213 else:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200214 req = expected_err = None
215
216 with support.transient_internet(url):
Georg Brandl5be365f2010-10-28 14:55:02 +0000217 try:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200218 f = urlopen(url, req, TIMEOUT)
Berker Peksag8b63d3a2014-10-25 05:42:30 +0300219 # urllib.error.URLError is a subclass of OSError
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200220 except OSError as err:
221 if expected_err:
222 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
223 (expected_err, url, req, type(err), err))
224 self.assertIsInstance(err, expected_err, msg)
225 else:
226 raise
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200227 else:
228 try:
229 with support.time_out, \
230 support.socket_peer_reset, \
231 support.ioerror_peer_reset:
232 buf = f.read()
233 debug("read %d bytes" % len(buf))
234 except socket.timeout:
235 print("<timeout: %s>" % url, file=sys.stderr)
236 f.close()
237 time.sleep(0.1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000238
239 def _extra_handlers(self):
240 handlers = []
241
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000242 cfh = urllib.request.CacheFTPHandler()
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200243 self.addCleanup(cfh.clear_cache)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000244 cfh.setTimeout(1)
245 handlers.append(cfh)
246
247 return handlers
248
Christian Heimesbbe741d2008-03-28 10:53:29 +0000249
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000250class TimeoutTest(unittest.TestCase):
251 def test_http_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200252 self.assertIsNone(socket.getdefaulttimeout())
Ned Deily5a507f02014-03-26 23:31:39 -0700253 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000254 with support.transient_internet(url, timeout=None):
255 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200256 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200257 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000258
Georg Brandlf78e02b2008-06-10 17:40:04 +0000259 def test_http_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200260 self.assertIsNone(socket.getdefaulttimeout())
Ned Deily5a507f02014-03-26 23:31:39 -0700261 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000262 with support.transient_internet(url):
263 socket.setdefaulttimeout(60)
264 try:
265 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200266 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000267 finally:
268 socket.setdefaulttimeout(None)
269 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000270
271 def test_http_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200272 self.assertIsNone(socket.getdefaulttimeout())
Ned Deily5a507f02014-03-26 23:31:39 -0700273 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000274 with support.transient_internet(url):
275 socket.setdefaulttimeout(60)
276 try:
277 u = _urlopen_with_retry(url, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200278 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000279 finally:
280 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200281 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000282
Georg Brandlf78e02b2008-06-10 17:40:04 +0000283 def test_http_timeout(self):
Ned Deily5a507f02014-03-26 23:31:39 -0700284 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000285 with support.transient_internet(url):
286 u = _urlopen_with_retry(url, timeout=120)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200287 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000288 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000289
Victor Stinner4bea4612015-04-07 12:52:50 +0200290 FTP_HOST = 'ftp://ftp.debian.org/debian/'
Christian Heimes969fe572008-01-25 11:23:10 +0000291
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000292 def test_ftp_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200293 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000294 with support.transient_internet(self.FTP_HOST, timeout=None):
295 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200296 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200297 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000298
Georg Brandlf78e02b2008-06-10 17:40:04 +0000299 def test_ftp_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200300 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000301 with support.transient_internet(self.FTP_HOST):
302 socket.setdefaulttimeout(60)
303 try:
304 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200305 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000306 finally:
307 socket.setdefaulttimeout(None)
308 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000309
310 def test_ftp_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200311 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000312 with support.transient_internet(self.FTP_HOST):
313 socket.setdefaulttimeout(60)
314 try:
315 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200316 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000317 finally:
318 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200319 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000320
Georg Brandlf78e02b2008-06-10 17:40:04 +0000321 def test_ftp_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000322 with support.transient_internet(self.FTP_HOST):
323 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200324 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000325 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000326
Thomas Wouters477c8d52006-05-27 19:21:47 +0000327
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000328if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400329 unittest.main()