blob: cd225c90fd59175c990851ed57aa50258f826d4f [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
86
Christian Heimes969fe572008-01-25 11:23:10 +000087 response = _urlopen_with_retry("http://www.python.org/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +000088 sock = response.fp
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000089 self.assertTrue(not sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000090 response.close()
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000091 self.assertTrue(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000092
Thomas Wouters477c8d52006-05-27 19:21:47 +000093class OtherNetworkTests(unittest.TestCase):
94 def setUp(self):
95 if 0: # for debugging
96 import logging
97 logger = logging.getLogger("test_urllib2net")
98 logger.addHandler(logging.StreamHandler())
99
Thomas Wouters477c8d52006-05-27 19:21:47 +0000100 # XXX The rest of these tests aren't very good -- they don't check much.
101 # They do sometimes catch some major disasters, though.
102
103 def test_ftp(self):
104 urls = [
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000105 'ftp://ftp.kernel.org/pub/linux/kernel/README',
Mark Dickinson934896d2009-02-21 20:59:32 +0000106 'ftp://ftp.kernel.org/pub/linux/kernel/non-existent-file',
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000107 #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
Thomas Wouters477c8d52006-05-27 19:21:47 +0000108 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
109 '/research-reports/00README-Legal-Rules-Regs',
110 ]
111 self._test_urls(urls, self._extra_handlers())
112
Thomas Wouters477c8d52006-05-27 19:21:47 +0000113 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000114 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115 f = open(TESTFN, 'w')
116 try:
117 f.write('hi there\n')
118 f.close()
119 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000120 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
121 ('file:///nonsensename/etc/passwd', None,
122 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000124 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000125 finally:
126 os.remove(TESTFN)
127
Thomas Wouters477c8d52006-05-27 19:21:47 +0000128 # XXX Following test depends on machine configurations that are internal
129 # to CNRI. Need to set up a public server with the right authentication
130 # configuration for test purposes.
131
132## def test_cnri(self):
133## if socket.gethostname() == 'bitdiddle':
134## localhost = 'bitdiddle.cnri.reston.va.us'
135## elif socket.gethostname() == 'bitdiddle.concentric.net':
136## localhost = 'localhost'
137## else:
138## localhost = None
139## if localhost is not None:
140## urls = [
141## 'file://%s/etc/passwd' % localhost,
142## 'http://%s/simple/' % localhost,
143## 'http://%s/digest/' % localhost,
144## 'http://%s/not/found.h' % localhost,
145## ]
146
147## bauth = HTTPBasicAuthHandler()
148## bauth.add_password('basic_test_realm', localhost, 'jhylton',
149## 'password')
150## dauth = HTTPDigestAuthHandler()
151## dauth.add_password('digest_test_realm', localhost, 'jhylton',
152## 'password')
153
154## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
155
Senthil Kumarand95cc752010-08-08 11:27:53 +0000156 def test_urlwithfrag(self):
157 urlwith_frag = "http://docs.python.org/glossary.html#glossary"
Georg Brandl5be365f2010-10-28 14:55:02 +0000158 with support.transient_internet(urlwith_frag):
159 req = urllib.request.Request(urlwith_frag)
160 res = urllib.request.urlopen(req)
161 self.assertEqual(res.geturl(),
Senthil Kumaran26430412011-04-13 07:01:19 +0800162 "http://docs.python.org/glossary.html#glossary")
Senthil Kumarand95cc752010-08-08 11:27:53 +0000163
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000164 def test_custom_headers(self):
165 url = "http://www.example.com"
Georg Brandl5be365f2010-10-28 14:55:02 +0000166 with support.transient_internet(url):
167 opener = urllib.request.build_opener()
168 request = urllib.request.Request(url)
169 self.assertFalse(request.header_items())
170 opener.open(request)
171 self.assertTrue(request.header_items())
172 self.assertTrue(request.has_header('User-agent'))
173 request.add_header('User-Agent','Test-Agent')
174 opener.open(request)
175 self.assertEqual(request.get_header('User-agent'),'Test-Agent')
Senthil Kumaran42ef4b12010-09-27 01:26:03 +0000176
Senthil Kumaran1299a8f2011-07-27 08:05:58 +0800177 def test_sites_no_connection_close(self):
178 # Some sites do not send Connection: close header.
179 # Verify that those work properly. (#issue12576)
180
181 try:
182 with urllib.request.urlopen('http://www.imdb.com') as res:
183 pass
184 except ValueError as e:
185 self.fail("urlopen failed for sites not sending Connection:close")
186 else:
187 self.assertTrue(res)
188
189 req = urllib.request.urlopen('http://www.imdb.com')
190 res = req.read()
191 self.assertTrue(res)
192
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000193 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000194 import time
195 import logging
196 debug = logging.getLogger("test_urllib2").debug
197
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000198 urlopen = urllib.request.build_opener(*handlers).open
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000199 if retry:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000200 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000201
202 for url in urls:
203 if isinstance(url, tuple):
204 url, req, expected_err = url
205 else:
206 req = expected_err = None
Georg Brandl5be365f2010-10-28 14:55:02 +0000207
208 with support.transient_internet(url):
209 debug(url)
Senthil Kumaranb8f7ea62010-04-20 10:35:49 +0000210 try:
Georg Brandl5be365f2010-10-28 14:55:02 +0000211 f = urlopen(url, req, TIMEOUT)
212 except EnvironmentError as err:
213 debug(err)
214 if expected_err:
215 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
216 (expected_err, url, req, type(err), err))
217 self.assertIsInstance(err, expected_err, msg)
218 except urllib.error.URLError as err:
219 if isinstance(err[0], socket.timeout):
220 print("<timeout: %s>" % url, file=sys.stderr)
221 continue
222 else:
223 raise
224 else:
225 try:
226 with support.time_out, \
227 support.socket_peer_reset, \
228 support.ioerror_peer_reset:
229 buf = f.read()
230 debug("read %d bytes" % len(buf))
231 except socket.timeout:
232 print("<timeout: %s>" % url, file=sys.stderr)
233 f.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000234 debug("******** next url coming up...")
235 time.sleep(0.1)
236
237 def _extra_handlers(self):
238 handlers = []
239
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000240 cfh = urllib.request.CacheFTPHandler()
Nadeem Vawda08f5f7a2011-07-23 14:03:00 +0200241 self.addCleanup(cfh.clear_cache)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000242 cfh.setTimeout(1)
243 handlers.append(cfh)
244
245 return handlers
246
Christian Heimesbbe741d2008-03-28 10:53:29 +0000247
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000248class TimeoutTest(unittest.TestCase):
249 def test_http_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000250 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000251 url = "http://www.python.org"
252 with support.transient_internet(url, timeout=None):
253 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200254 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000255 self.assertTrue(u.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000256
Georg Brandlf78e02b2008-06-10 17:40:04 +0000257 def test_http_default_timeout(self):
258 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000259 url = "http://www.python.org"
260 with support.transient_internet(url):
261 socket.setdefaulttimeout(60)
262 try:
263 u = _urlopen_with_retry(url)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200264 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000265 finally:
266 socket.setdefaulttimeout(None)
267 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000268
269 def test_http_no_timeout(self):
270 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000271 url = "http://www.python.org"
272 with support.transient_internet(url):
273 socket.setdefaulttimeout(60)
274 try:
275 u = _urlopen_with_retry(url, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200276 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000277 finally:
278 socket.setdefaulttimeout(None)
279 self.assertTrue(u.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000280
Georg Brandlf78e02b2008-06-10 17:40:04 +0000281 def test_http_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000282 url = "http://www.python.org"
283 with support.transient_internet(url):
284 u = _urlopen_with_retry(url, timeout=120)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200285 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000286 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000287
Benjamin Peterson87cb7872010-04-11 21:59:57 +0000288 FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/"
Christian Heimes969fe572008-01-25 11:23:10 +0000289
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000290 def test_ftp_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000291 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000292 with support.transient_internet(self.FTP_HOST, timeout=None):
293 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200294 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000295 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000296
Georg Brandlf78e02b2008-06-10 17:40:04 +0000297 def test_ftp_default_timeout(self):
298 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000299 with support.transient_internet(self.FTP_HOST):
300 socket.setdefaulttimeout(60)
301 try:
302 u = _urlopen_with_retry(self.FTP_HOST)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200303 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000304 finally:
305 socket.setdefaulttimeout(None)
306 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000307
308 def test_ftp_no_timeout(self):
309 self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandl5be365f2010-10-28 14:55:02 +0000310 with support.transient_internet(self.FTP_HOST):
311 socket.setdefaulttimeout(60)
312 try:
313 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200314 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000315 finally:
316 socket.setdefaulttimeout(None)
317 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000318
Georg Brandlf78e02b2008-06-10 17:40:04 +0000319 def test_ftp_timeout(self):
Georg Brandl5be365f2010-10-28 14:55:02 +0000320 with support.transient_internet(self.FTP_HOST):
321 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Victor Stinnereaca5c82011-06-17 14:53:02 +0200322 self.addCleanup(u.close)
Georg Brandl5be365f2010-10-28 14:55:02 +0000323 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000324
Thomas Wouters477c8d52006-05-27 19:21:47 +0000325
Antoine Pitroud5323212010-10-22 18:19:07 +0000326@unittest.skipUnless(ssl, "requires SSL support")
327class HTTPSTests(unittest.TestCase):
328
329 def test_sni(self):
Antoine Pitrou0eee1f52010-11-03 08:53:25 +0000330 self.skipTest("test disabled - test server needed")
Antoine Pitroud5323212010-10-22 18:19:07 +0000331 # Checks that Server Name Indication works, if supported by the
332 # OpenSSL linked to.
333 # The ssl module itself doesn't have server-side support for SNI,
334 # so we rely on a third-party test site.
335 expect_sni = ssl.HAS_SNI
Antoine Pitrou0eee1f52010-11-03 08:53:25 +0000336 with support.transient_internet("XXX"):
337 u = urllib.request.urlopen("XXX")
Antoine Pitroud5323212010-10-22 18:19:07 +0000338 contents = u.readall()
339 if expect_sni:
340 self.assertIn(b"Great", contents)
341 self.assertNotIn(b"Unfortunately", contents)
342 else:
343 self.assertNotIn(b"Great", contents)
344 self.assertIn(b"Unfortunately", contents)
345
346
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000347def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000348 support.requires("network")
349 support.run_unittest(AuthTests,
Antoine Pitroud5323212010-10-22 18:19:07 +0000350 HTTPSTests,
351 OtherNetworkTests,
352 CloseSocketTest,
353 TimeoutTest,
354 )
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000355
356if __name__ == "__main__":
357 test_main()