blob: 938ab9ffca74ff8cc7c442e4b238c7d8516ef932 [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
7import socket
8import urllib2
9import sys
10import os
Jeremy Hylton5d9c3032004-08-07 17:40:50 +000011
Christian Heimes969fe572008-01-25 11:23:10 +000012
Georg Brandlc28e1fa2008-06-10 19:20:26 +000013def _retry_thrice(func, exc, *args, **kwargs):
Christian Heimes969fe572008-01-25 11:23:10 +000014 for i in range(3):
15 try:
Georg Brandlc28e1fa2008-06-10 19:20:26 +000016 return func(*args, **kwargs)
17 except exc as e:
Neal Norwitz2f142582008-01-26 19:49:41 +000018 last_exc = e
Christian Heimes969fe572008-01-25 11:23:10 +000019 continue
20 except:
21 raise
22 raise last_exc
23
Georg Brandlc28e1fa2008-06-10 19:20:26 +000024def _wrap_with_retry_thrice(func, exc):
25 def wrapped(*args, **kwargs):
26 return _retry_thrice(func, exc, *args, **kwargs)
27 return wrapped
28
29# Connecting to remote hosts is flaky. Make it more robust by retrying
30# the connection several times.
31_urlopen_with_retry = _wrap_with_retry_thrice(urllib2.urlopen, urllib2.URLError)
Christian Heimes969fe572008-01-25 11:23:10 +000032
Thomas Wouters477c8d52006-05-27 19:21:47 +000033
34class AuthTests(unittest.TestCase):
35 """Tests urllib2 authentication features."""
36
37## Disabled at the moment since there is no page under python.org which
38## could be used to HTTP authentication.
39#
40# def test_basic_auth(self):
Georg Brandl24420152008-05-26 16:32:26 +000041# import http.client
Thomas Wouters477c8d52006-05-27 19:21:47 +000042#
43# test_url = "http://www.python.org/test/test_urllib2/basic_auth"
44# test_hostport = "www.python.org"
45# test_realm = 'Test Realm'
46# test_user = 'test.test_urllib2net'
47# test_password = 'blah'
48#
49# # failure
50# try:
Christian Heimes969fe572008-01-25 11:23:10 +000051# _urlopen_with_retry(test_url)
Thomas Wouters477c8d52006-05-27 19:21:47 +000052# except urllib2.HTTPError, exc:
53# self.assertEqual(exc.code, 401)
54# else:
55# self.fail("urlopen() should have failed with 401")
56#
57# # success
58# auth_handler = urllib2.HTTPBasicAuthHandler()
59# auth_handler.add_password(test_realm, test_hostport,
60# test_user, test_password)
61# opener = urllib2.build_opener(auth_handler)
62# f = opener.open('http://localhost/')
Christian Heimes969fe572008-01-25 11:23:10 +000063# response = _urlopen_with_retry("http://www.python.org/")
Thomas Wouters477c8d52006-05-27 19:21:47 +000064#
65# # The 'userinfo' URL component is deprecated by RFC 3986 for security
66# # reasons, let's not implement it! (it's already implemented for proxy
67# # specification strings (that is, URLs or authorities specifying a
68# # proxy), so we must keep that)
Georg Brandl24420152008-05-26 16:32:26 +000069# self.assertRaises(http.client.InvalidURL,
Thomas Wouters477c8d52006-05-27 19:21:47 +000070# urllib2.urlopen, "http://evil:thing@example.com")
71
72
Thomas Woutersb2137042007-02-01 18:02:27 +000073class CloseSocketTest(unittest.TestCase):
74
75 def test_close(self):
Georg Brandl24420152008-05-26 16:32:26 +000076 import socket, http.client, gc
Thomas Woutersb2137042007-02-01 18:02:27 +000077
78 # calling .close() on urllib2's response objects should close the
79 # underlying socket
80
81 # delve deep into response to fetch socket._socketobject
Christian Heimes969fe572008-01-25 11:23:10 +000082 response = _urlopen_with_retry("http://www.python.org/")
Thomas Woutersb2137042007-02-01 18:02:27 +000083 abused_fileobject = response.fp
Jeremy Hyltonec0c5082007-08-03 21:03:02 +000084 httpresponse = abused_fileobject.raw
Georg Brandl24420152008-05-26 16:32:26 +000085 self.assert_(httpresponse.__class__ is http.client.HTTPResponse)
Thomas Woutersb2137042007-02-01 18:02:27 +000086 fileobject = httpresponse.fp
Thomas Woutersb2137042007-02-01 18:02:27 +000087
88 self.assert_(not fileobject.closed)
89 response.close()
90 self.assert_(fileobject.closed)
91
Thomas Wouters477c8d52006-05-27 19:21:47 +000092class OtherNetworkTests(unittest.TestCase):
93 def setUp(self):
94 if 0: # for debugging
95 import logging
96 logger = logging.getLogger("test_urllib2net")
97 logger.addHandler(logging.StreamHandler())
98
Thomas Wouters477c8d52006-05-27 19:21:47 +000099 # XXX The rest of these tests aren't very good -- they don't check much.
100 # They do sometimes catch some major disasters, though.
101
102 def test_ftp(self):
103 urls = [
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000104 'ftp://ftp.kernel.org/pub/linux/kernel/README',
105 'ftp://ftp.kernel.org/pub/linux/kernel/non-existant-file',
106 #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
108 '/research-reports/00README-Legal-Rules-Regs',
109 ]
110 self._test_urls(urls, self._extra_handlers())
111
Thomas Wouters477c8d52006-05-27 19:21:47 +0000112 def test_file(self):
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000113 TESTFN = support.TESTFN
Thomas Wouters477c8d52006-05-27 19:21:47 +0000114 f = open(TESTFN, 'w')
115 try:
116 f.write('hi there\n')
117 f.close()
118 urls = [
119 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000120 ('file:///nonsensename/etc/passwd', None, urllib2.URLError),
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121 ]
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000122 self._test_urls(urls, self._extra_handlers(), retry=True)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 finally:
124 os.remove(TESTFN)
125
Thomas Wouters477c8d52006-05-27 19:21:47 +0000126 # XXX Following test depends on machine configurations that are internal
127 # to CNRI. Need to set up a public server with the right authentication
128 # configuration for test purposes.
129
130## def test_cnri(self):
131## if socket.gethostname() == 'bitdiddle':
132## localhost = 'bitdiddle.cnri.reston.va.us'
133## elif socket.gethostname() == 'bitdiddle.concentric.net':
134## localhost = 'localhost'
135## else:
136## localhost = None
137## if localhost is not None:
138## urls = [
139## 'file://%s/etc/passwd' % localhost,
140## 'http://%s/simple/' % localhost,
141## 'http://%s/digest/' % localhost,
142## 'http://%s/not/found.h' % localhost,
143## ]
144
145## bauth = HTTPBasicAuthHandler()
146## bauth.add_password('basic_test_realm', localhost, 'jhylton',
147## 'password')
148## dauth = HTTPDigestAuthHandler()
149## dauth.add_password('digest_test_realm', localhost, 'jhylton',
150## 'password')
151
152## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
153
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000154 def _test_urls(self, urls, handlers, retry=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000155 import socket
156 import time
157 import logging
158 debug = logging.getLogger("test_urllib2").debug
159
Georg Brandlc28e1fa2008-06-10 19:20:26 +0000160 urlopen = urllib2.build_opener(*handlers).open
161 if retry:
162 urlopen = _wrap_with_retry_thrice(urlopen, urllib2.URLError)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000163
164 for url in urls:
165 if isinstance(url, tuple):
166 url, req, expected_err = url
167 else:
168 req = expected_err = None
169 debug(url)
170 try:
Christian Heimes969fe572008-01-25 11:23:10 +0000171 f = urlopen(url, req)
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000172 except EnvironmentError as err:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000173 debug(err)
174 if expected_err:
Gregory P. Smithc111d9f2007-09-09 23:55:55 +0000175 msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
176 (expected_err, url, req, type(err), err))
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000177 self.assert_(isinstance(err, expected_err), msg)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000178 else:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000179 with support.transient_internet():
Guido van Rossumd8faa362007-04-27 19:54:29 +0000180 buf = f.read()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000181 f.close()
182 debug("read %d bytes" % len(buf))
183 debug("******** next url coming up...")
184 time.sleep(0.1)
185
186 def _extra_handlers(self):
187 handlers = []
188
Thomas Wouters477c8d52006-05-27 19:21:47 +0000189 cfh = urllib2.CacheFTPHandler()
190 cfh.setTimeout(1)
191 handlers.append(cfh)
192
193 return handlers
194
Christian Heimesbbe741d2008-03-28 10:53:29 +0000195
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000196class TimeoutTest(unittest.TestCase):
197 def test_http_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000198 self.assertTrue(socket.getdefaulttimeout() is None)
Christian Heimes969fe572008-01-25 11:23:10 +0000199 u = _urlopen_with_retry("http://www.python.org")
Jeremy Hyltoncf2f4192007-08-03 20:31:38 +0000200 self.assertTrue(u.fp.raw.fp._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000201
Georg Brandlf78e02b2008-06-10 17:40:04 +0000202 def test_http_default_timeout(self):
203 self.assertTrue(socket.getdefaulttimeout() is None)
204 socket.setdefaulttimeout(60)
205 try:
206 u = _urlopen_with_retry("http://www.python.org")
207 finally:
208 socket.setdefaulttimeout(None)
209 self.assertEqual(u.fp.raw.fp._sock.gettimeout(), 60)
210
211 def test_http_no_timeout(self):
212 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000213 socket.setdefaulttimeout(60)
214 try:
Christian Heimes969fe572008-01-25 11:23:10 +0000215 u = _urlopen_with_retry("http://www.python.org", timeout=None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000216 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000217 socket.setdefaulttimeout(None)
218 self.assertTrue(u.fp.raw.fp._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000219
Georg Brandlf78e02b2008-06-10 17:40:04 +0000220 def test_http_timeout(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000221 u = _urlopen_with_retry("http://www.python.org", timeout=120)
Jeremy Hyltoncf2f4192007-08-03 20:31:38 +0000222 self.assertEqual(u.fp.raw.fp._sock.gettimeout(), 120)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000223
Christian Heimes969fe572008-01-25 11:23:10 +0000224 FTP_HOST = "ftp://ftp.mirror.nl/pub/mirror/gnu/"
225
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000226 def test_ftp_basic(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000227 self.assertTrue(socket.getdefaulttimeout() is None)
Christian Heimes969fe572008-01-25 11:23:10 +0000228 u = _urlopen_with_retry(self.FTP_HOST)
Jeremy Hyltoncf2f4192007-08-03 20:31:38 +0000229 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000230
Georg Brandlf78e02b2008-06-10 17:40:04 +0000231 def test_ftp_default_timeout(self):
232 self.assertTrue(socket.getdefaulttimeout() is None)
233 socket.setdefaulttimeout(60)
234 try:
235 u = _urlopen_with_retry(self.FTP_HOST)
236 finally:
237 socket.setdefaulttimeout(None)
238 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
239
240 def test_ftp_no_timeout(self):
241 self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000242 socket.setdefaulttimeout(60)
243 try:
Christian Heimes969fe572008-01-25 11:23:10 +0000244 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000245 finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000246 socket.setdefaulttimeout(None)
Neal Norwitz2f142582008-01-26 19:49:41 +0000247 self.assertTrue(u.fp.fp.raw._sock.gettimeout() is None)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000248
Georg Brandlf78e02b2008-06-10 17:40:04 +0000249 def test_ftp_timeout(self):
Christian Heimes969fe572008-01-25 11:23:10 +0000250 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
Jeremy Hyltoncf2f4192007-08-03 20:31:38 +0000251 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000252
Thomas Wouters477c8d52006-05-27 19:21:47 +0000253
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000254def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000255 support.requires("network")
256 support.run_unittest(AuthTests,
Thomas Woutersb2137042007-02-01 18:02:27 +0000257 OtherNetworkTests,
258 CloseSocketTest,
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000259 TimeoutTest,
Thomas Woutersb2137042007-02-01 18:02:27 +0000260 )
Jeremy Hylton5d9c3032004-08-07 17:40:50 +0000261
262if __name__ == "__main__":
263 test_main()