blob: b3a5e8974df32541a0458e1e68ab95ceed2e0015 [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
Christian Heimes969fe572008-01-25 11:23:10 +000013
Georg Brandlc28e1fa2008-06-10 19:20:26 +000014def _retry_thrice(func, exc, *args, **kwargs):
Christian Heimes969fe572008-01-25 11:23:10 +000015 for i in range(3):
16 try:
Georg Brandlc28e1fa2008-06-10 19:20:26 +000017 return func(*args, **kwargs)
18 except exc as e:
Neal Norwitz2f142582008-01-26 19:49:41 +000019 last_exc = e
Christian Heimes969fe572008-01-25 11:23:10 +000020 continue
Christian Heimes969fe572008-01-25 11:23:10 +000021 raise last_exc
22
Georg Brandlc28e1fa2008-06-10 19:20:26 +000023def _wrap_with_retry_thrice(func, exc):
24 def wrapped(*args, **kwargs):
25 return _retry_thrice(func, exc, *args, **kwargs)
26 return wrapped
27
Victor Stinnerc11b3b12018-12-05 01:58:31 +010028# bpo-35411: FTP tests of test_urllib2net randomly fail
29# with "425 Security: Bad IP connecting" on Travis CI
30skip_ftp_test_on_travis = unittest.skipIf('TRAVIS' in os.environ,
31 'bpo-35411: skip FTP test '
32 'on Travis CI')
33
34
Georg Brandlc28e1fa2008-06-10 19:20:26 +000035# Connecting to remote hosts is flaky. Make it more robust by retrying
36# the connection several times.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000037_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
38 urllib.error.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000039
Thomas Wouters477c8d52006-05-27 19:21:47 +000040
41class AuthTests(unittest.TestCase):
42 """Tests urllib2 authentication features."""
43
44## Disabled at the moment since there is no page under python.org which
45## could be used to HTTP authentication.
46#
47# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000048# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000049#
50# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
51# test_hostport = "www.python.org"
52# test_realm = 'Test Realm'
53# test_user = 'test.test_urllib2net'
54# test_password = 'blah'
55#
56# # failure
57# try:
Christian Heimes969fe572008-01-25 11:23:10 +000058# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000059# except urllib2.HTTPError, exc:
60# self.assertEqual(exc.code, 401)
61# else:
62# self.fail("urlopen() should have failed with 401")
63#
64# # success
65# auth_handler = urllib2.HTTPBasicAuthHandler()
66# auth_handler.add_password(test_realm, test_hostport,
67# test_user, test_password)
68# opener = urllib2.build_opener(auth_handler)
69# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000070# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000071#
72# # The 'userinfo' URL component is deprecated by RFC 3986 for security
73# # reasons, let's not implement it! (it's already implemented for proxy
74# # specification strings (that is, URLs or authorities specifying a
75# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000076# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000077# urllib2.urlopen, "http://evil:thing@example.com")
78
79
Thomas Woutersb2137042007-02-01 18:02:27 +000080class CloseSocketTest(unittest.TestCase):
81
82 def test_close(self):
Victor Stinner7cb92042019-07-02 14:50:19 +020083 # clear _opener global variable
84 self.addCleanup(urllib.request.urlcleanup)
85
Thomas Woutersb2137042007-02-01 18:02:27 +000086 # calling .close() on urllib2's response objects should close the
87 # underlying socket
Stéphane Wirtela40681d2019-02-22 14:45:36 +010088 url = support.TEST_HTTP_URL
Nadeem Vawda61baebd2012-01-25 08:02:05 +020089 with support.transient_internet(url):
90 response = _urlopen_with_retry(url)
91 sock = response.fp
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +020092 self.assertFalse(sock.closed)
Nadeem Vawda61baebd2012-01-25 08:02:05 +020093 response.close()
94 self.assertTrue(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000095
Thomas Wouters477c8d52006-05-27 19:21:47 +000096class OtherNetworkTests(unittest.TestCase):
97 def setUp(self):
98 if 0: # for debugging
99 import logging
100 logger = logging.getLogger("test_urllib2net")
101 logger.addHandler(logging.StreamHandler())
102
Thomas Wouters477c8d52006-05-27 19:21:47 +0000103 # XXX The rest of these tests aren't very good -- they don't check much.
104 # They do sometimes catch some major disasters, though.
105
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100106 @skip_ftp_test_on_travis
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107 def test_ftp(self):
108 urls = [
Ammar Askard81bea62017-07-18 19:27:24 -0700109 'ftp://www.pythontest.net/README',
110 ('ftp://www.pythontest.net/non-existent-file',
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200111 None, urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112 ]
113 self._test_urls(urls, self._extra_handlers())
114
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000116 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000117 f = open(TESTFN, 'w')
118 try:
119 f.write('hi there\n')
120 f.close()
121 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000122 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
123 ('file:///nonsensename/etc/passwd', None,
124 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000125 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000126 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000127 finally:
128 os.remove(TESTFN)
129
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800130 self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
131
Thomas Wouters477c8d52006-05-27 19:21:47 +0000132 # XXX Following test depends on machine configurations that are internal
133 # to CNRI. Need to set up a public server with the right authentication
134 # configuration for test purposes.
135
136## def test_cnri(self):
137## if socket.gethostname() == 'bitdiddle':
138## localhost = 'bitdiddle.cnri.reston.va.us'
139## elif socket.gethostname() == 'bitdiddle.concentric.net':
140## localhost = 'localhost'
141## else:
142## localhost = None
143## if localhost is not None:
144## urls = [
145## 'file://%s/etc/passwd' % localhost,
146## 'http://%s/simple/' % localhost,
147## 'http://%s/digest/' % localhost,
148## 'http://%s/not/found.h' % localhost,
149## ]
150
151## bauth = HTTPBasicAuthHandler()
152## bauth.add_password('basic_test_realm', localhost, 'jhylton',
153## 'password')
154## dauth = HTTPDigestAuthHandler()
155## dauth.add_password('digest_test_realm', localhost, 'jhylton',
156## 'password')
157
158## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
159
Senthil Kumarand95cc752010-08-08 11:27:53 +0000160 def test_urlwithfrag(self):
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500161 urlwith_frag = "http://www.pythontest.net/index.html#frag"
Georg Brandl5be365f2010-10-28 14:55:02 +0000162 with support.transient_internet(urlwith_frag):
163 req = urllib.request.Request(urlwith_frag)
164 res = urllib.request.urlopen(req)
165 self.assertEqual(res.geturl(),
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500166 "http://www.pythontest.net/index.html#frag")
Senthil Kumarand95cc752010-08-08 11:27:53 +0000167
Senthil Kumaran83070752013-05-24 09:14:12 -0700168 def test_redirect_url_withfrag(self):
Benjamin Petersonb811a972014-11-05 13:10:08 -0500169 redirect_url_with_frag = "http://www.pythontest.net/redir/with_frag/"
Senthil Kumaran83070752013-05-24 09:14:12 -0700170 with support.transient_internet(redirect_url_with_frag):
171 req = urllib.request.Request(redirect_url_with_frag)
172 res = urllib.request.urlopen(req)
173 self.assertEqual(res.geturl(),
Benjamin Petersonb811a972014-11-05 13:10:08 -0500174 "http://www.pythontest.net/elsewhere/#frag")
Senthil Kumaran83070752013-05-24 09:14:12 -0700175
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000176 def test_custom_headers(self):
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100177 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000178 with support.transient_internet(url):
179 opener = urllib.request.build_opener()
180 request = urllib.request.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 Kumaran42ef4b12010-09-27 01:26:03 +0000188
INADA Naoki36d56ea2018-04-18 00:31:29 +0900189 @unittest.skip('XXX: http://www.imdb.com is gone')
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800190 def test_sites_no_connection_close(self):
191 # Some sites do not send Connection: close header.
192 # Verify that those work properly. (#issue12576)
193
Senthil Kumarane324c572011-07-31 11:45:14 +0800194 URL = 'http://www.imdb.com' # mangles Connection:close
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800195
Senthil Kumarane324c572011-07-31 11:45:14 +0800196 with support.transient_internet(URL):
197 try:
198 with urllib.request.urlopen(URL) as res:
199 pass
Pablo Galindo293dd232019-11-19 21:34:03 +0000200 except ValueError:
Senthil Kumarane324c572011-07-31 11:45:14 +0800201 self.fail("urlopen failed for site not sending \
202 Connection:close")
203 else:
204 self.assertTrue(res)
205
206 req = urllib.request.urlopen(URL)
207 res = req.read()
208 self.assertTrue(res)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800209
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000210 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000211 import time
212 import logging
213 debug = logging.getLogger("test_urllib2").debug
214
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000215 urlopen = urllib.request.build_opener(*handlers).open
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000216 if retry:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000217 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000218
219 for url in urls:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200220 with self.subTest(url=url):
221 if isinstance(url, tuple):
222 url, req, expected_err = url
Georg Brandl5be365f2010-10-28 14:55:02 +0000223 else:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200224 req = expected_err = None
225
226 with support.transient_internet(url):
Georg Brandl5be365f2010-10-28 14:55:02 +0000227 try:
Victor Stinner1d0f9b32019-12-10 22:09:23 +0100228 f = urlopen(url, req, support.INTERNET_TIMEOUT)
Berker Peksag8b63d3a2014-10-25 05:42:30 +0300229 # urllib.error.URLError is a subclass of OSError
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200230 except OSError as err:
231 if expected_err:
232 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
233 (expected_err, url, req, type(err), err))
234 self.assertIsInstance(err, expected_err, msg)
235 else:
236 raise
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200237 else:
238 try:
239 with support.time_out, \
240 support.socket_peer_reset, \
241 support.ioerror_peer_reset:
242 buf = f.read()
243 debug("read %d bytes" % len(buf))
244 except socket.timeout:
245 print("<timeout: %s>" % url, file=sys.stderr)
246 f.close()
247 time.sleep(0.1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000248
249 def _extra_handlers(self):
250 handlers = []
251
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000252 cfh = urllib.request.CacheFTPHandler()
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200253 self.addCleanup(cfh.clear_cache)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000254 cfh.setTimeout(1)
255 handlers.append(cfh)
256
257 return handlers
258
Christian Heimesbbe741d2008-03-28 10:53:29 +0000259
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000260class TimeoutTest(unittest.TestCase):
Victor Stinner7cb92042019-07-02 14:50:19 +0200261 def setUp(self):
262 # clear _opener global variable
263 self.addCleanup(urllib.request.urlcleanup)
264
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000265 def test_http_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200266 self.assertIsNone(socket.getdefaulttimeout())
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100267 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000268 with support.transient_internet(url, timeout=None):
269 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200270 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200271 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000272
Georg Brandlf78e02b2008-06-10 17:40:04 +0000273 def test_http_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200274 self.assertIsNone(socket.getdefaulttimeout())
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100275 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000276 with support.transient_internet(url):
277 socket.setdefaulttimeout(60)
278 try:
279 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200280 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000281 finally:
282 socket.setdefaulttimeout(None)
283 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000284
285 def test_http_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200286 self.assertIsNone(socket.getdefaulttimeout())
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100287 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000288 with support.transient_internet(url):
289 socket.setdefaulttimeout(60)
290 try:
291 u = _urlopen_with_retry(url, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200292 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000293 finally:
294 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200295 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000296
Georg Brandlf78e02b2008-06-10 17:40:04 +0000297 def test_http_timeout(self):
Stéphane Wirtela40681d2019-02-22 14:45:36 +0100298 url = support.TEST_HTTP_URL
Georg Brandl5be365f2010-10-28 14:55:02 +0000299 with support.transient_internet(url):
300 u = _urlopen_with_retry(url, timeout=120)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200301 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000302 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000303
Ammar Askard81bea62017-07-18 19:27:24 -0700304 FTP_HOST = 'ftp://www.pythontest.net/'
Christian Heimes969fe572008-01-25 11:23:10 +0000305
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100306 @skip_ftp_test_on_travis
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000307 def test_ftp_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200308 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000309 with support.transient_internet(self.FTP_HOST, timeout=None):
310 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200311 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200312 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000313
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100314 @skip_ftp_test_on_travis
Georg Brandlf78e02b2008-06-10 17:40:04 +0000315 def test_ftp_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200316 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000317 with support.transient_internet(self.FTP_HOST):
318 socket.setdefaulttimeout(60)
319 try:
320 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200321 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000322 finally:
323 socket.setdefaulttimeout(None)
324 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000325
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100326 @skip_ftp_test_on_travis
Georg Brandlf78e02b2008-06-10 17:40:04 +0000327 def test_ftp_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200328 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000329 with support.transient_internet(self.FTP_HOST):
330 socket.setdefaulttimeout(60)
331 try:
332 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200333 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000334 finally:
335 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200336 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000337
Victor Stinnerc11b3b12018-12-05 01:58:31 +0100338 @skip_ftp_test_on_travis
Georg Brandlf78e02b2008-06-10 17:40:04 +0000339 def test_ftp_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000340 with support.transient_internet(self.FTP_HOST):
341 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200342 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000343 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000344
Thomas Wouters477c8d52006-05-27 19:21:47 +0000345
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000346if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400347 unittest.main()