blob: e276d2ebfca6aeb4b005dbee99a579a48e624477 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00002
3import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00004from test import support
Thomas Wouters477c8d52006-05-27 19:21:47 +00005from test.test_urllib2 import sanepathname2url
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00006
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00007import os
Jeremy Hylton1afc1692008-06-18 20:49:58 +00008import socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +00009import urllib.error
10import urllib.request
Senthil Kumaranb8f7ea62010-04-20 10:35:49 +000011import sys
Antoine Pitroud5323212010-10-22 18:19:07 +000012try:
13 import ssl
14except ImportError:
15 ssl = None
Senthil Kumaranb8f7ea62010-04-20 10:35:49 +000016
17TIMEOUT = 60 # seconds
Jeremy Hylton5d9c3032004-08-07 17:40:50 +000018
Christian Heimes969fe572008-01-25 11:23:10 +000019
Georg Brandlc28e1fa2008-06-10 19:20:26 +000020def _retry_thrice(func, exc, *args, **kwargs):
Christian Heimes969fe572008-01-25 11:23:10 +000021 for i in range(3):
22 try:
Georg Brandlc28e1fa2008-06-10 19:20:26 +000023 return func(*args, **kwargs)
24 except exc as e:
Neal Norwitz2f142582008-01-26 19:49:41 +000025 last_exc = e
Christian Heimes969fe572008-01-25 11:23:10 +000026 continue
27 except:
28 raise
29 raise last_exc
30
Georg Brandlc28e1fa2008-06-10 19:20:26 +000031def _wrap_with_retry_thrice(func, exc):
32 def wrapped(*args, **kwargs):
33 return _retry_thrice(func, exc, *args, **kwargs)
34 return wrapped
35
36# Connecting to remote hosts is flaky. Make it more robust by retrying
37# the connection several times.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000038_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
39 urllib.error.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000040
Thomas Wouters477c8d52006-05-27 19:21:47 +000041
42class AuthTests(unittest.TestCase):
43 """Tests urllib2 authentication features."""
44
45## Disabled at the moment since there is no page under python.org which
46## could be used to HTTP authentication.
47#
48# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000049# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000050#
51# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
52# test_hostport = "www.python.org"
53# test_realm = 'Test Realm'
54# test_user = 'test.test_urllib2net'
55# test_password = 'blah'
56#
57# # failure
58# try:
Christian Heimes969fe572008-01-25 11:23:10 +000059# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000060# except urllib2.HTTPError, exc:
61# self.assertEqual(exc.code, 401)
62# else:
63# self.fail("urlopen() should have failed with 401")
64#
65# # success
66# auth_handler = urllib2.HTTPBasicAuthHandler()
67# auth_handler.add_password(test_realm, test_hostport,
68# test_user, test_password)
69# opener = urllib2.build_opener(auth_handler)
70# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000071# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000072#
73# # The 'userinfo' URL component is deprecated by RFC 3986 for security
74# # reasons, let's not implement it! (it's already implemented for proxy
75# # specification strings (that is, URLs or authorities specifying a
76# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000077# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000078# urllib2.urlopen, "http://evil:thing@example.com")
79
80
Thomas Woutersb2137042007-02-01 18:02:27 +000081class CloseSocketTest(unittest.TestCase):
82
83 def test_close(self):
Thomas Woutersb2137042007-02-01 18:02:27 +000084 # calling .close() on urllib2's response objects should close the
85 # underlying socket
Nadeem Vawda61baebd2012-01-25 08:02:05 +020086 url = "http://www.python.org/"
87 with support.transient_internet(url):
88 response = _urlopen_with_retry(url)
89 sock = response.fp
90 self.assertTrue(not sock.closed)
91 response.close()
92 self.assertTrue(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000093
Thomas Wouters477c8d52006-05-27 19:21:47 +000094class OtherNetworkTests(unittest.TestCase):
95 def setUp(self):
96 if 0: # for debugging
97 import logging
98 logger = logging.getLogger("test_urllib2net")
99 logger.addHandler(logging.StreamHandler())
100
Thomas Wouters477c8d52006-05-27 19:21:47 +0000101 # XXX The rest of these tests aren't very good -- they don't check much.
102 # They do sometimes catch some major disasters, though.
103
104 def test_ftp(self):
105 urls = [
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000106 'ftp://ftp.kernel.org/pub/linux/kernel/README',
Mark Dickinson934896d2009-02-21 20:59:32 +0000107 'ftp://ftp.kernel.org/pub/linux/kernel/non-existent-file',
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000108 #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
110 '/research-reports/00README-Legal-Rules-Regs',
111 ]
112 self._test_urls(urls, self._extra_handlers())
113
Thomas Wouters477c8d52006-05-27 19:21:47 +0000114 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000115 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000116 f = open(TESTFN, 'w')
117 try:
118 f.write('hi there\n')
119 f.close()
120 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000121 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
122 ('file:///nonsensename/etc/passwd', None,
123 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000124 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000125 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 finally:
127 os.remove(TESTFN)
128
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800129 self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
130
Thomas Wouters477c8d52006-05-27 19:21:47 +0000131 # XXX Following test depends on machine configurations that are internal
132 # to CNRI. Need to set up a public server with the right authentication
133 # configuration for test purposes.
134
135## def test_cnri(self):
136## if socket.gethostname() == 'bitdiddle':
137## localhost = 'bitdiddle.cnri.reston.va.us'
138## elif socket.gethostname() == 'bitdiddle.concentric.net':
139## localhost = 'localhost'
140## else:
141## localhost = None
142## if localhost is not None:
143## urls = [
144## 'file://%s/etc/passwd' % localhost,
145## 'http://%s/simple/' % localhost,
146## 'http://%s/digest/' % localhost,
147## 'http://%s/not/found.h' % localhost,
148## ]
149
150## bauth = HTTPBasicAuthHandler()
151## bauth.add_password('basic_test_realm', localhost, 'jhylton',
152## 'password')
153## dauth = HTTPDigestAuthHandler()
154## dauth.add_password('digest_test_realm', localhost, 'jhylton',
155## 'password')
156
157## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
158
Senthil Kumarand95cc752010-08-08 11:27:53 +0000159 def test_urlwithfrag(self):
Georg Brandl579d5cd2012-10-28 10:51:35 +0100160 urlwith_frag = "http://docs.python.org/2/glossary.html#glossary"
Georg Brandl5be365f2010-10-28 14:55:02 +0000161 with support.transient_internet(urlwith_frag):
162 req = urllib.request.Request(urlwith_frag)
163 res = urllib.request.urlopen(req)
164 self.assertEqual(res.geturl(),
Georg Brandl579d5cd2012-10-28 10:51:35 +0100165 "http://docs.python.org/2/glossary.html#glossary")
Senthil Kumarand95cc752010-08-08 11:27:53 +0000166
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:
210 if isinstance(url, tuple):
211 url, req, expected_err = url
212 else:
213 req = expected_err = None
Georg Brandl5be365f2010-10-28 14:55:02 +0000214
215 with support.transient_internet(url):
216 debug(url)
Senthil Kumaranb8f7ea62010-04-20 10:35:49 +0000217 try:
Georg Brandl5be365f2010-10-28 14:55:02 +0000218 f = urlopen(url, req, TIMEOUT)
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200219 except OSError as err:
Georg Brandl5be365f2010-10-28 14:55:02 +0000220 debug(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 except urllib.error.URLError as err:
226 if isinstance(err[0], socket.timeout):
227 print("<timeout: %s>" % url, file=sys.stderr)
228 continue
229 else:
230 raise
231 else:
232 try:
233 with support.time_out, \
234 support.socket_peer_reset, \
235 support.ioerror_peer_reset:
236 buf = f.read()
237 debug("read %d bytes" % len(buf))
238 except socket.timeout:
239 print("<timeout: %s>" % url, file=sys.stderr)
240 f.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000241 debug("******** next url coming up...")
242 time.sleep(0.1)
243
244 def _extra_handlers(self):
245 handlers = []
246
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000247 cfh = urllib.request.CacheFTPHandler()
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200248 self.addCleanup(cfh.clear_cache)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000249 cfh.setTimeout(1)
250 handlers.append(cfh)
251
252 return handlers
253
Christian Heimesbbe741d2008-03-28 10:53:29 +0000254
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000255class TimeoutTest(unittest.TestCase):
256 def test_http_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000257 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000258 url = "http://www.python.org"
259 with support.transient_internet(url, timeout=None):
260 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200261 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000262 self.assertTrue(u.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000263
Georg Brandlf78e02b2008-06-10 17:40:04 +0000264 def test_http_default_timeout(self):
265 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000266 url = "http://www.python.org"
267 with support.transient_internet(url):
268 socket.setdefaulttimeout(60)
269 try:
270 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200271 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000272 finally:
273 socket.setdefaulttimeout(None)
274 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000275
276 def test_http_no_timeout(self):
277 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000278 url = "http://www.python.org"
279 with support.transient_internet(url):
280 socket.setdefaulttimeout(60)
281 try:
282 u = _urlopen_with_retry(url, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200283 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000284 finally:
285 socket.setdefaulttimeout(None)
286 self.assertTrue(u.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000287
Georg Brandlf78e02b2008-06-10 17:40:04 +0000288 def test_http_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000289 url = "http://www.python.org"
290 with support.transient_internet(url):
291 u = _urlopen_with_retry(url, timeout=120)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200292 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000293 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000294
Benjamin Peterson87cb7872010-04-11 21:59:57 +0000295 FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/"
Christian Heimes969fe572008-01-25 11:23:10 +0000296
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000297 def test_ftp_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000298 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000299 with support.transient_internet(self.FTP_HOST, timeout=None):
300 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200301 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000302 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000303
Georg Brandlf78e02b2008-06-10 17:40:04 +0000304 def test_ftp_default_timeout(self):
305 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000306 with support.transient_internet(self.FTP_HOST):
307 socket.setdefaulttimeout(60)
308 try:
309 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200310 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000311 finally:
312 socket.setdefaulttimeout(None)
313 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000314
315 def test_ftp_no_timeout(self):
316 self.assertTrue(socket.getdefaulttimeout() is None)
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, timeout=None)
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.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000325
Georg Brandlf78e02b2008-06-10 17:40:04 +0000326 def test_ftp_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000327 with support.transient_internet(self.FTP_HOST):
328 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200329 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000330 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000331
Thomas Wouters477c8d52006-05-27 19:21:47 +0000332
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000333def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000334 support.requires("network")
335 support.run_unittest(AuthTests,
Antoine Pitroud5323212010-10-22 18:19:07 +0000336 OtherNetworkTests,
337 CloseSocketTest,
338 TimeoutTest,
339 )
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000340
341if __name__ == "__main__":
342 test_main()