blob: bb0500e12a49a4701b4bd38735e6c0d6cdd6b290 [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
Victor Stinnerc11b3b12018-12-05 01:58:31 +010030# bpo-35411: FTP tests of test_urllib2net randomly fail
31# with "425 Security: Bad IP connecting" on Travis CI
32skip_ftp_test_on_travis = unittest.skipIf('TRAVIS' in os.environ,
33 'bpo-35411: skip FTP test '
34 'on Travis CI')
35
36
Georg Brandlc28e1fa2008-06-10 19:20:26 +000037# Connecting to remote hosts is flaky. Make it more robust by retrying
38# the connection several times.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000039_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
40 urllib.error.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000041
Thomas Wouters477c8d52006-05-27 19:21:47 +000042
43class AuthTests(unittest.TestCase):
44 """Tests urllib2 authentication features."""
45
46## Disabled at the moment since there is no page under python.org which
47## could be used to HTTP authentication.
48#
49# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000050# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000051#
52# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
53# test_hostport = "www.python.org"
54# test_realm = 'Test Realm'
55# test_user = 'test.test_urllib2net'
56# test_password = 'blah'
57#
58# # failure
59# try:
Christian Heimes969fe572008-01-25 11:23:10 +000060# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000061# except urllib2.HTTPError, exc:
62# self.assertEqual(exc.code, 401)
63# else:
64# self.fail("urlopen() should have failed with 401")
65#
66# # success
67# auth_handler = urllib2.HTTPBasicAuthHandler()
68# auth_handler.add_password(test_realm, test_hostport,
69# test_user, test_password)
70# opener = urllib2.build_opener(auth_handler)
71# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000072# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000073#
74# # The 'userinfo' URL component is deprecated by RFC 3986 for security
75# # reasons, let's not implement it! (it's already implemented for proxy
76# # specification strings (that is, URLs or authorities specifying a
77# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000078# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000079# urllib2.urlopen, "http://evil:thing@example.com")
80
81
Thomas Woutersb2137042007-02-01 18:02:27 +000082class CloseSocketTest(unittest.TestCase):
83
84 def test_close(self):
Victor Stinner7cb92042019-07-02 14:50:19 +020085 # clear _opener global variable
86 self.addCleanup(urllib.request.urlcleanup)
87
Thomas Woutersb2137042007-02-01 18:02:27 +000088 # calling .close() on urllib2's response objects should close the
89 # underlying socket
Stéphane Wirtela40681d2019-02-22 14:45:36 +010090 url = support.TEST_HTTP_URL
Nadeem Vawda61baebd2012-01-25 08:02:05 +020091 with support.transient_internet(url):
92 response = _urlopen_with_retry(url)
93 sock = response.fp
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +020094 self.assertFalse(sock.closed)
Nadeem Vawda61baebd2012-01-25 08:02:05 +020095 response.close()
96 self.assertTrue(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000097
Thomas Wouters477c8d52006-05-27 19:21:47 +000098class OtherNetworkTests(unittest.TestCase):
99 def setUp(self):
100 if 0: # for debugging
101 import logging
102 logger = logging.getLogger("test_urllib2net")
103 logger.addHandler(logging.StreamHandler())
104
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105 # XXX The rest of these tests aren't very good -- they don't check much.
106 # They do sometimes catch some major disasters, though.
107
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100108 @skip_ftp_test_on_travis
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 def test_ftp(self):
110 urls = [
Ammar Askard81bea62017-07-18 19:27:24 -0700111 'ftp://www.pythontest.net/README',
112 ('ftp://www.pythontest.net/non-existent-file',
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200113 None, urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000114 ]
115 self._test_urls(urls, self._extra_handlers())
116
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000118 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119 f = open(TESTFN, 'w')
120 try:
121 f.write('hi there\n')
122 f.close()
123 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000124 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
125 ('file:///nonsensename/etc/passwd', None,
126 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000127 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000128 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000129 finally:
130 os.remove(TESTFN)
131
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800132 self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
133
Thomas Wouters477c8d52006-05-27 19:21:47 +0000134 # XXX Following test depends on machine configurations that are internal
135 # to CNRI. Need to set up a public server with the right authentication
136 # configuration for test purposes.
137
138## def test_cnri(self):
139## if socket.gethostname() == 'bitdiddle':
140## localhost = 'bitdiddle.cnri.reston.va.us'
141## elif socket.gethostname() == 'bitdiddle.concentric.net':
142## localhost = 'localhost'
143## else:
144## localhost = None
145## if localhost is not None:
146## urls = [
147## 'file://%s/etc/passwd' % localhost,
148## 'http://%s/simple/' % localhost,
149## 'http://%s/digest/' % localhost,
150## 'http://%s/not/found.h' % localhost,
151## ]
152
153## bauth = HTTPBasicAuthHandler()
154## bauth.add_password('basic_test_realm', localhost, 'jhylton',
155## 'password')
156## dauth = HTTPDigestAuthHandler()
157## dauth.add_password('digest_test_realm', localhost, 'jhylton',
158## 'password')
159
160## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
161
Senthil Kumarand95cc752010-08-08 11:27:53 +0000162 def test_urlwithfrag(self):
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500163 urlwith_frag = "http://www.pythontest.net/index.html#frag"
Georg Brandl5be365f2010-10-28 14:55:02 +0000164 with support.transient_internet(urlwith_frag):
165 req = urllib.request.Request(urlwith_frag)
166 res = urllib.request.urlopen(req)
167 self.assertEqual(res.geturl(),
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500168 "http://www.pythontest.net/index.html#frag")
Senthil Kumarand95cc752010-08-08 11:27:53 +0000169
Senthil Kumaran83070752013-05-24 09:14:12 -0700170 def test_redirect_url_withfrag(self):
Benjamin Petersonb811a972014-11-05 13:10:08 -0500171 redirect_url_with_frag = "http://www.pythontest.net/redir/with_frag/"
Senthil Kumaran83070752013-05-24 09:14:12 -0700172 with support.transient_internet(redirect_url_with_frag):
173 req = urllib.request.Request(redirect_url_with_frag)
174 res = urllib.request.urlopen(req)
175 self.assertEqual(res.geturl(),
Benjamin Petersonb811a972014-11-05 13:10:08 -0500176 "http://www.pythontest.net/elsewhere/#frag")
Senthil Kumaran83070752013-05-24 09:14:12 -0700177
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000178 def test_custom_headers(self):
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100179 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000180 with support.transient_internet(url):
181 opener = urllib.request.build_opener()
182 request = urllib.request.Request(url)
183 self.assertFalse(request.header_items())
184 opener.open(request)
185 self.assertTrue(request.header_items())
186 self.assertTrue(request.has_header('User-agent'))
187 request.add_header('User-Agent','Test-Agent')
188 opener.open(request)
189 self.assertEqual(request.get_header('User-agent'),'Test-Agent')
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000190
INADA Naoki36d56ea2018-04-18 00:31:29 +0900191 @unittest.skip('XXX: http://www.imdb.com is gone')
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800192 def test_sites_no_connection_close(self):
193 # Some sites do not send Connection: close header.
194 # Verify that those work properly. (#issue12576)
195
Senthil Kumarane324c572011-07-31 11:45:14 +0800196 URL = 'http://www.imdb.com' # mangles Connection:close
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800197
Senthil Kumarane324c572011-07-31 11:45:14 +0800198 with support.transient_internet(URL):
199 try:
200 with urllib.request.urlopen(URL) as res:
201 pass
Pablo Galindo293dd232019-11-19 21:34:03 +0000202 except ValueError:
Senthil Kumarane324c572011-07-31 11:45:14 +0800203 self.fail("urlopen failed for site not sending \
204 Connection:close")
205 else:
206 self.assertTrue(res)
207
208 req = urllib.request.urlopen(URL)
209 res = req.read()
210 self.assertTrue(res)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800211
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000212 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213 import time
214 import logging
215 debug = logging.getLogger("test_urllib2").debug
216
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000217 urlopen = urllib.request.build_opener(*handlers).open
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000218 if retry:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000219 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000220
221 for url in urls:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200222 with self.subTest(url=url):
223 if isinstance(url, tuple):
224 url, req, expected_err = url
Georg Brandl5be365f2010-10-28 14:55:02 +0000225 else:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200226 req = expected_err = None
227
228 with support.transient_internet(url):
Georg Brandl5be365f2010-10-28 14:55:02 +0000229 try:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200230 f = urlopen(url, req, TIMEOUT)
Berker Peksag8b63d3a2014-10-25 05:42:30 +0300231 # urllib.error.URLError is a subclass of OSError
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200232 except OSError as err:
233 if expected_err:
234 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
235 (expected_err, url, req, type(err), err))
236 self.assertIsInstance(err, expected_err, msg)
237 else:
238 raise
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200239 else:
240 try:
241 with support.time_out, \
242 support.socket_peer_reset, \
243 support.ioerror_peer_reset:
244 buf = f.read()
245 debug("read %d bytes" % len(buf))
246 except socket.timeout:
247 print("<timeout: %s>" % url, file=sys.stderr)
248 f.close()
249 time.sleep(0.1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000250
251 def _extra_handlers(self):
252 handlers = []
253
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000254 cfh = urllib.request.CacheFTPHandler()
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200255 self.addCleanup(cfh.clear_cache)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000256 cfh.setTimeout(1)
257 handlers.append(cfh)
258
259 return handlers
260
Christian Heimesbbe741d2008-03-28 10:53:29 +0000261
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000262class TimeoutTest(unittest.TestCase):
Victor Stinner7cb92042019-07-02 14:50:19 +0200263 def setUp(self):
264 # clear _opener global variable
265 self.addCleanup(urllib.request.urlcleanup)
266
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000267 def test_http_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200268 self.assertIsNone(socket.getdefaulttimeout())
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100269 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000270 with support.transient_internet(url, timeout=None):
271 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200272 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200273 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000274
Georg Brandlf78e02b2008-06-10 17:40:04 +0000275 def test_http_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200276 self.assertIsNone(socket.getdefaulttimeout())
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100277 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000278 with support.transient_internet(url):
279 socket.setdefaulttimeout(60)
280 try:
281 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200282 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000283 finally:
284 socket.setdefaulttimeout(None)
285 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000286
287 def test_http_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200288 self.assertIsNone(socket.getdefaulttimeout())
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100289 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000290 with support.transient_internet(url):
291 socket.setdefaulttimeout(60)
292 try:
293 u = _urlopen_with_retry(url, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200294 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000295 finally:
296 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200297 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000298
Georg Brandlf78e02b2008-06-10 17:40:04 +0000299 def test_http_timeout(self):
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100300 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000301 with support.transient_internet(url):
302 u = _urlopen_with_retry(url, timeout=120)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200303 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000304 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000305
Ammar Askard81bea62017-07-18 19:27:24 -0700306 FTP_HOST = 'ftp://www.pythontest.net/'
Christian Heimes969fe572008-01-25 11:23:10 +0000307
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100308 @skip_ftp_test_on_travis
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000309 def test_ftp_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200310 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000311 with support.transient_internet(self.FTP_HOST, timeout=None):
312 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200313 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200314 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000315
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100316 @skip_ftp_test_on_travis
Georg Brandlf78e02b2008-06-10 17:40:04 +0000317 def test_ftp_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200318 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000319 with support.transient_internet(self.FTP_HOST):
320 socket.setdefaulttimeout(60)
321 try:
322 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200323 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000324 finally:
325 socket.setdefaulttimeout(None)
326 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000327
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100328 @skip_ftp_test_on_travis
Georg Brandlf78e02b2008-06-10 17:40:04 +0000329 def test_ftp_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200330 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000331 with support.transient_internet(self.FTP_HOST):
332 socket.setdefaulttimeout(60)
333 try:
334 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200335 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000336 finally:
337 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200338 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000339
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100340 @skip_ftp_test_on_travis
Georg Brandlf78e02b2008-06-10 17:40:04 +0000341 def test_ftp_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000342 with support.transient_internet(self.FTP_HOST):
343 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200344 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000345 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000346
Thomas Wouters477c8d52006-05-27 19:21:47 +0000347
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000348if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400349 unittest.main()