blob: 17f9d1bdee3d5432f35c51da2da8dfb43152925d [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
23 except:
24 raise
25 raise last_exc
26
Georg Brandlc28e1fa2008-06-10 19:20:26 +000027def _wrap_with_retry_thrice(func, exc):
28 def wrapped(*args, **kwargs):
29 return _retry_thrice(func, exc, *args, **kwargs)
30 return wrapped
31
32# Connecting to remote hosts is flaky. Make it more robust by retrying
33# the connection several times.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000034_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
35 urllib.error.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000036
Thomas Wouters477c8d52006-05-27 19:21:47 +000037
38class AuthTests(unittest.TestCase):
39 """Tests urllib2 authentication features."""
40
41## Disabled at the moment since there is no page under python.org which
42## could be used to HTTP authentication.
43#
44# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000045# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000046#
47# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
48# test_hostport = "www.python.org"
49# test_realm = 'Test Realm'
50# test_user = 'test.test_urllib2net'
51# test_password = 'blah'
52#
53# # failure
54# try:
Christian Heimes969fe572008-01-25 11:23:10 +000055# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000056# except urllib2.HTTPError, exc:
57# self.assertEqual(exc.code, 401)
58# else:
59# self.fail("urlopen() should have failed with 401")
60#
61# # success
62# auth_handler = urllib2.HTTPBasicAuthHandler()
63# auth_handler.add_password(test_realm, test_hostport,
64# test_user, test_password)
65# opener = urllib2.build_opener(auth_handler)
66# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000067# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000068#
69# # The 'userinfo' URL component is deprecated by RFC 3986 for security
70# # reasons, let's not implement it! (it's already implemented for proxy
71# # specification strings (that is, URLs or authorities specifying a
72# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000073# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000074# urllib2.urlopen, "http://evil:thing@example.com")
75
76
Thomas Woutersb2137042007-02-01 18:02:27 +000077class CloseSocketTest(unittest.TestCase):
78
79 def test_close(self):
Thomas Woutersb2137042007-02-01 18:02:27 +000080 # calling .close() on urllib2's response objects should close the
81 # underlying socket
Ned Deily5a507f02014-03-26 23:31:39 -070082 url = "http://www.example.com/"
Nadeem Vawda61baebd2012-01-25 08:02:05 +020083 with support.transient_internet(url):
84 response = _urlopen_with_retry(url)
85 sock = response.fp
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +020086 self.assertFalse(sock.closed)
Nadeem Vawda61baebd2012-01-25 08:02:05 +020087 response.close()
88 self.assertTrue(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000089
Thomas Wouters477c8d52006-05-27 19:21:47 +000090class OtherNetworkTests(unittest.TestCase):
91 def setUp(self):
92 if 0: # for debugging
93 import logging
94 logger = logging.getLogger("test_urllib2net")
95 logger.addHandler(logging.StreamHandler())
96
Thomas Wouters477c8d52006-05-27 19:21:47 +000097 # XXX The rest of these tests aren't very good -- they don't check much.
98 # They do sometimes catch some major disasters, though.
99
100 def test_ftp(self):
101 urls = [
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200102 'ftp://ftp.debian.org/debian/README',
103 ('ftp://ftp.debian.org/debian/non-existent-file',
104 None, urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000105 ]
106 self._test_urls(urls, self._extra_handlers())
107
Thomas Wouters477c8d52006-05-27 19:21:47 +0000108 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000109 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000110 f = open(TESTFN, 'w')
111 try:
112 f.write('hi there\n')
113 f.close()
114 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000115 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
116 ('file:///nonsensename/etc/passwd', None,
117 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000118 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000119 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000120 finally:
121 os.remove(TESTFN)
122
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800123 self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
124
Thomas Wouters477c8d52006-05-27 19:21:47 +0000125 # XXX Following test depends on machine configurations that are internal
126 # to CNRI. Need to set up a public server with the right authentication
127 # configuration for test purposes.
128
129## def test_cnri(self):
130## if socket.gethostname() == 'bitdiddle':
131## localhost = 'bitdiddle.cnri.reston.va.us'
132## elif socket.gethostname() == 'bitdiddle.concentric.net':
133## localhost = 'localhost'
134## else:
135## localhost = None
136## if localhost is not None:
137## urls = [
138## 'file://%s/etc/passwd' % localhost,
139## 'http://%s/simple/' % localhost,
140## 'http://%s/digest/' % localhost,
141## 'http://%s/not/found.h' % localhost,
142## ]
143
144## bauth = HTTPBasicAuthHandler()
145## bauth.add_password('basic_test_realm', localhost, 'jhylton',
146## 'password')
147## dauth = HTTPDigestAuthHandler()
148## dauth.add_password('digest_test_realm', localhost, 'jhylton',
149## 'password')
150
151## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
152
Senthil Kumarand95cc752010-08-08 11:27:53 +0000153 def test_urlwithfrag(self):
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500154 urlwith_frag = "http://www.pythontest.net/index.html#frag"
Georg Brandl5be365f2010-10-28 14:55:02 +0000155 with support.transient_internet(urlwith_frag):
156 req = urllib.request.Request(urlwith_frag)
157 res = urllib.request.urlopen(req)
158 self.assertEqual(res.geturl(),
Benjamin Peterson258f3f02014-11-05 11:27:14 -0500159 "http://www.pythontest.net/index.html#frag")
Senthil Kumarand95cc752010-08-08 11:27:53 +0000160
Senthil Kumaran83070752013-05-24 09:14:12 -0700161 def test_redirect_url_withfrag(self):
Benjamin Petersonb811a972014-11-05 13:10:08 -0500162 redirect_url_with_frag = "http://www.pythontest.net/redir/with_frag/"
Senthil Kumaran83070752013-05-24 09:14:12 -0700163 with support.transient_internet(redirect_url_with_frag):
164 req = urllib.request.Request(redirect_url_with_frag)
165 res = urllib.request.urlopen(req)
166 self.assertEqual(res.geturl(),
Benjamin Petersonb811a972014-11-05 13:10:08 -0500167 "http://www.pythontest.net/elsewhere/#frag")
Senthil Kumaran83070752013-05-24 09:14:12 -0700168
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000169 def test_custom_headers(self):
170 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000171 with support.transient_internet(url):
172 opener = urllib.request.build_opener()
173 request = urllib.request.Request(url)
174 self.assertFalse(request.header_items())
175 opener.open(request)
176 self.assertTrue(request.header_items())
177 self.assertTrue(request.has_header('User-agent'))
178 request.add_header('User-Agent','Test-Agent')
179 opener.open(request)
180 self.assertEqual(request.get_header('User-agent'),'Test-Agent')
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000181
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800182 def test_sites_no_connection_close(self):
183 # Some sites do not send Connection: close header.
184 # Verify that those work properly. (#issue12576)
185
Senthil Kumarane324c572011-07-31 11:45:14 +0800186 URL = 'http://www.imdb.com' # mangles Connection:close
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800187
Senthil Kumarane324c572011-07-31 11:45:14 +0800188 with support.transient_internet(URL):
189 try:
190 with urllib.request.urlopen(URL) as res:
191 pass
192 except ValueError as e:
193 self.fail("urlopen failed for site not sending \
194 Connection:close")
195 else:
196 self.assertTrue(res)
197
198 req = urllib.request.urlopen(URL)
199 res = req.read()
200 self.assertTrue(res)
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800201
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000202 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000203 import time
204 import logging
205 debug = logging.getLogger("test_urllib2").debug
206
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000207 urlopen = urllib.request.build_opener(*handlers).open
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000208 if retry:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000209 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210
211 for url in urls:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200212 with self.subTest(url=url):
213 if isinstance(url, tuple):
214 url, req, expected_err = url
Georg Brandl5be365f2010-10-28 14:55:02 +0000215 else:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200216 req = expected_err = None
217
218 with support.transient_internet(url):
Georg Brandl5be365f2010-10-28 14:55:02 +0000219 try:
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200220 f = urlopen(url, req, TIMEOUT)
Berker Peksag8b63d3a2014-10-25 05:42:30 +0300221 # urllib.error.URLError is a subclass of OSError
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200222 except OSError as err:
223 if expected_err:
224 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
225 (expected_err, url, req, type(err), err))
226 self.assertIsInstance(err, expected_err, msg)
227 else:
228 raise
Antoine Pitroubc2c4c92014-09-17 00:39:21 +0200229 else:
230 try:
231 with support.time_out, \
232 support.socket_peer_reset, \
233 support.ioerror_peer_reset:
234 buf = f.read()
235 debug("read %d bytes" % len(buf))
236 except socket.timeout:
237 print("<timeout: %s>" % url, file=sys.stderr)
238 f.close()
239 time.sleep(0.1)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000240
241 def _extra_handlers(self):
242 handlers = []
243
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000244 cfh = urllib.request.CacheFTPHandler()
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200245 self.addCleanup(cfh.clear_cache)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000246 cfh.setTimeout(1)
247 handlers.append(cfh)
248
249 return handlers
250
Christian Heimesbbe741d2008-03-28 10:53:29 +0000251
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000252class TimeoutTest(unittest.TestCase):
253 def test_http_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200254 self.assertIsNone(socket.getdefaulttimeout())
Ned Deily5a507f02014-03-26 23:31:39 -0700255 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000256 with support.transient_internet(url, timeout=None):
257 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200258 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200259 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000260
Georg Brandlf78e02b2008-06-10 17:40:04 +0000261 def test_http_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200262 self.assertIsNone(socket.getdefaulttimeout())
Ned Deily5a507f02014-03-26 23:31:39 -0700263 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000264 with support.transient_internet(url):
265 socket.setdefaulttimeout(60)
266 try:
267 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200268 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000269 finally:
270 socket.setdefaulttimeout(None)
271 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000272
273 def test_http_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200274 self.assertIsNone(socket.getdefaulttimeout())
Ned Deily5a507f02014-03-26 23:31:39 -0700275 url = "http://www.example.com"
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, timeout=None)
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)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200283 self.assertIsNone(u.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000284
Georg Brandlf78e02b2008-06-10 17:40:04 +0000285 def test_http_timeout(self):
Ned Deily5a507f02014-03-26 23:31:39 -0700286 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000287 with support.transient_internet(url):
288 u = _urlopen_with_retry(url, timeout=120)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200289 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000290 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000291
Victor Stinner4bea4612015-04-07 12:52:50 +0200292 FTP_HOST = 'ftp://ftp.debian.org/debian/'
Christian Heimes969fe572008-01-25 11:23:10 +0000293
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000294 def test_ftp_basic(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200295 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000296 with support.transient_internet(self.FTP_HOST, timeout=None):
297 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200298 self.addCleanup(u.close)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200299 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000300
Georg Brandlf78e02b2008-06-10 17:40:04 +0000301 def test_ftp_default_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200302 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000303 with support.transient_internet(self.FTP_HOST):
304 socket.setdefaulttimeout(60)
305 try:
306 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200307 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000308 finally:
309 socket.setdefaulttimeout(None)
310 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000311
312 def test_ftp_no_timeout(self):
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200313 self.assertIsNone(socket.getdefaulttimeout())
Georg Brandl5be365f2010-10-28 14:55:02 +0000314 with support.transient_internet(self.FTP_HOST):
315 socket.setdefaulttimeout(60)
316 try:
317 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200318 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000319 finally:
320 socket.setdefaulttimeout(None)
Serhiy Storchaka25d8aea2014-02-08 14:50:08 +0200321 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000322
Georg Brandlf78e02b2008-06-10 17:40:04 +0000323 def test_ftp_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000324 with support.transient_internet(self.FTP_HOST):
325 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200326 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000327 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000328
Thomas Wouters477c8d52006-05-27 19:21:47 +0000329
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000330if __name__ == "__main__":
Brett Cannon3e9a9ae2013-06-12 21:25:59 -0400331 unittest.main()