blob: a18a4bb983fc3c5da2c126d9927ff81bee948cd8 [file] [log] [blame]
Jeremy Hylton5d9c3032004-08-07 17:40:50 +00001#!/usr/bin/env python
2
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
9import sys
10import urllib.error
11import urllib.request
Jeremy Hylton5d9c3032004-08-07 17:40:50 +000012
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
21 except:
22 raise
23 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
30# Connecting to remote hosts is flaky. Make it more robust by retrying
31# the connection several times.
Jeremy Hylton1afc1692008-06-18 20:49:58 +000032_urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
33 urllib.error.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000034
Thomas Wouters477c8d52006-05-27 19:21:47 +000035
36class AuthTests(unittest.TestCase):
37 """Tests urllib2 authentication features."""
38
39## Disabled at the moment since there is no page under python.org which
40## could be used to HTTP authentication.
41#
42# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000043# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000044#
45# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
46# test_hostport = "www.python.org"
47# test_realm = 'Test Realm'
48# test_user = 'test.test_urllib2net'
49# test_password = 'blah'
50#
51# # failure
52# try:
Christian Heimes969fe572008-01-25 11:23:10 +000053# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000054# except urllib2.HTTPError, exc:
55# self.assertEqual(exc.code, 401)
56# else:
57# self.fail("urlopen() should have failed with 401")
58#
59# # success
60# auth_handler = urllib2.HTTPBasicAuthHandler()
61# auth_handler.add_password(test_realm, test_hostport,
62# test_user, test_password)
63# opener = urllib2.build_opener(auth_handler)
64# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000065# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000066#
67# # The 'userinfo' URL component is deprecated by RFC 3986 for security
68# # reasons, let's not implement it! (it's already implemented for proxy
69# # specification strings (that is, URLs or authorities specifying a
70# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000071# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000072# urllib2.urlopen, "http://evil:thing@example.com")
73
74
Thomas Woutersb2137042007-02-01 18:02:27 +000075class CloseSocketTest(unittest.TestCase):
76
77 def test_close(self):
Georg Brandl24420152008-05-26 16:32:26 +000078 import socket, http.client, gc
Thomas Woutersb2137042007-02-01 18:02:27 +000079
80 # calling .close() on urllib2's response objects should close the
81 # underlying socket
82
Christian Heimes969fe572008-01-25 11:23:10 +000083 response = _urlopen_with_retry("http://www.python.org/")
Jeremy Hylton1afc1692008-06-18 20:49:58 +000084 sock = response.fp
85 self.assert_(not sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000086 response.close()
Jeremy Hylton1afc1692008-06-18 20:49:58 +000087 self.assert_(sock.closed)
Thomas Woutersb2137042007-02-01 18:02:27 +000088
Thomas Wouters477c8d52006-05-27 19:21:47 +000089class OtherNetworkTests(unittest.TestCase):
90 def setUp(self):
91 if 0: # for debugging
92 import logging
93 logger = logging.getLogger("test_urllib2net")
94 logger.addHandler(logging.StreamHandler())
95
Thomas Wouters477c8d52006-05-27 19:21:47 +000096 # XXX The rest of these tests aren't very good -- they don't check much.
97 # They do sometimes catch some major disasters, though.
98
99 def test_ftp(self):
100 urls = [
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000101 'ftp://ftp.kernel.org/pub/linux/kernel/README',
102 'ftp://ftp.kernel.org/pub/linux/kernel/non-existant-file',
103 #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
Thomas Wouters477c8d52006-05-27 19:21:47 +0000104 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
105 '/research-reports/00README-Legal-Rules-Regs',
106 ]
107 self._test_urls(urls, self._extra_handlers())
108
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000110 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000111 f = open(TESTFN, 'w')
112 try:
113 f.write('hi there\n')
114 f.close()
115 urls = [
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000116 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
117 ('file:///nonsensename/etc/passwd', None,
118 urllib.error.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000120 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121 finally:
122 os.remove(TESTFN)
123
Thomas Wouters477c8d52006-05-27 19:21:47 +0000124 # XXX Following test depends on machine configurations that are internal
125 # to CNRI. Need to set up a public server with the right authentication
126 # configuration for test purposes.
127
128## def test_cnri(self):
129## if socket.gethostname() == 'bitdiddle':
130## localhost = 'bitdiddle.cnri.reston.va.us'
131## elif socket.gethostname() == 'bitdiddle.concentric.net':
132## localhost = 'localhost'
133## else:
134## localhost = None
135## if localhost is not None:
136## urls = [
137## 'file://%s/etc/passwd' % localhost,
138## 'http://%s/simple/' % localhost,
139## 'http://%s/digest/' % localhost,
140## 'http://%s/not/found.h' % localhost,
141## ]
142
143## bauth = HTTPBasicAuthHandler()
144## bauth.add_password('basic_test_realm', localhost, 'jhylton',
145## 'password')
146## dauth = HTTPDigestAuthHandler()
147## dauth.add_password('digest_test_realm', localhost, 'jhylton',
148## 'password')
149
150## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
151
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000152 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000153 import socket
154 import time
155 import logging
156 debug = logging.getLogger("test_urllib2").debug
157
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000158 urlopen = urllib.request.build_opener(*handlers).open
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000159 if retry:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000160 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000161
162 for url in urls:
163 if isinstance(url, tuple):
164 url, req, expected_err = url
165 else:
166 req = expected_err = None
167 debug(url)
168 try:
Christian Heimes969fe572008-01-25 11:23:10 +0000169 f = urlopen(url, req)
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000170 except EnvironmentError as err:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000171 debug(err)
172 if expected_err:
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000173 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
174 (expected_err, url, req, type(err), err))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000175 self.assert_(isinstance(err, expected_err), msg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000176 else:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000177 with support.transient_internet():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000178 buf = f.read()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000179 f.close()
180 debug("read %d bytes" % len(buf))
181 debug("******** next url coming up...")
182 time.sleep(0.1)
183
184 def _extra_handlers(self):
185 handlers = []
186
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000187 cfh = urllib.request.CacheFTPHandler()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000188 cfh.setTimeout(1)
189 handlers.append(cfh)
190
191 return handlers
192
Christian Heimesbbe741d2008-03-28 10:53:29 +0000193
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000194class TimeoutTest(unittest.TestCase):
195 def test_http_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000196 self.assertTrue(socket.getdefaulttimeout() is None)
Christian Heimes969fe572008-01-25 11:23:10 +0000197 u = _urlopen_with_retry("http://www.python.org")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000198 self.assertTrue(u.fp._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000199
Georg Brandlf78e02b2008-06-10 17:40:04 +0000200 def test_http_default_timeout(self):
201 self.assertTrue(socket.getdefaulttimeout() is None)
202 socket.setdefaulttimeout(60)
203 try:
204 u = _urlopen_with_retry("http://www.python.org")
205 finally:
206 socket.setdefaulttimeout(None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000207 self.assertEqual(u.fp._sock.gettimeout(), 60)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000208
209 def test_http_no_timeout(self):
210 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000211 socket.setdefaulttimeout(60)
212 try:
Christian Heimes969fe572008-01-25 11:23:10 +0000213 u = _urlopen_with_retry("http://www.python.org", timeout=None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000214 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000215 socket.setdefaulttimeout(None)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000216 self.assertTrue(u.fp._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000217
Georg Brandlf78e02b2008-06-10 17:40:04 +0000218 def test_http_timeout(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000219 u = _urlopen_with_retry("http://www.python.org", timeout=120)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000220 self.assertEqual(u.fp._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000221
Christian Heimes969fe572008-01-25 11:23:10 +0000222 FTP_HOST = "ftp://ftp.mirror.nl/pub/mirror/gnu/"
223
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000224 def test_ftp_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000225 self.assertTrue(socket.getdefaulttimeout() is None)
Christian Heimes969fe572008-01-25 11:23:10 +0000226 u = _urlopen_with_retry(self.FTP_HOST)
Jeremy Hyltoncf2f4192007-08-03 20:31:38 +0000227 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000228
Georg Brandlf78e02b2008-06-10 17:40:04 +0000229 def test_ftp_default_timeout(self):
230 self.assertTrue(socket.getdefaulttimeout() is None)
231 socket.setdefaulttimeout(60)
232 try:
233 u = _urlopen_with_retry(self.FTP_HOST)
234 finally:
235 socket.setdefaulttimeout(None)
236 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
237
238 def test_ftp_no_timeout(self):
239 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000240 socket.setdefaulttimeout(60)
241 try:
Christian Heimes969fe572008-01-25 11:23:10 +0000242 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000243 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000244 socket.setdefaulttimeout(None)
Neal Norwitz2f142582008-01-26 19:49:41 +0000245 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000246
Georg Brandlf78e02b2008-06-10 17:40:04 +0000247 def test_ftp_timeout(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000248 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Jeremy Hyltoncf2f4192007-08-03 20:31:38 +0000249 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000250
Thomas Wouters477c8d52006-05-27 19:21:47 +0000251
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000252def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000253 support.requires("network")
254 support.run_unittest(AuthTests,
Thomas Woutersb2137042007-02-01 18:02:27 +0000255 OtherNetworkTests,
256 CloseSocketTest,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000257 TimeoutTest,
Thomas Woutersb2137042007-02-01 18:02:27 +0000258 )
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000259
260if __name__ == "__main__":
261 test_main()