Debian Codegraph @

Lib/test/test_urllib2net.py

raw
1 import contextlib
2 import errno
3 import sysconfig
4 import unittest
5 from unittest import mock
6 from test import support
7 from test.support import os_helper
8 from test.support import socket_helper
9 from test.support import ResourceDenied
10 from test.test_urllib2 import sanepathname2url
11 from test.support.warnings_helper import check_no_resource_warning
12
13 import os
14 import socket
15 import urllib.error
16 import urllib.request
17 import sys
18
19 support.requires("network")
20
21
22 def _retry_thrice(func, exc, *args, **kwargs):
23 for i in range(3):
24 try:
25 return func(*args, **kwargs)
26 except exc as e:
27 last_exc = e
28 continue
29 raise last_exc
30
31 def _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.
38 _urlopen_with_retry = _wrap_with_retry_thrice(urllib.request.urlopen,
39 urllib.error.URLError)
40
41
42 class TransientResource(object):
43
44 """Raise ResourceDenied if an exception is raised while the context manager
45 is in effect that matches the specified exception and attributes."""
46
47 def __init__(self, exc, **kwargs):
48 self.exc = exc
49 self.attrs = kwargs
50
51 def __enter__(self):
52 return self
53
54 def __exit__(self, type_=None, value=None, traceback=None):
55 """If type_ is a subclass of self.exc and value has attributes matching
56 self.attrs, raise ResourceDenied. Otherwise let the exception
57 propagate (if any)."""
58 if type_ is not None and issubclass(self.exc, type_):
59 for attr, attr_value in self.attrs.items():
60 if not hasattr(value, attr):
61 break
62 if getattr(value, attr) != attr_value:
63 break
64 else:
65 raise ResourceDenied("an optional resource is not available")
66
67 # Context managers that raise ResourceDenied when various issues
68 # with the internet connection manifest themselves as exceptions.
69 # XXX deprecate these and use transient_internet() instead
70 time_out = TransientResource(OSError, errno=errno.ETIMEDOUT)
71 socket_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
72 ioerror_peer_reset = TransientResource(OSError, errno=errno.ECONNRESET)
73
74
75 class AuthTests(unittest.TestCase):
76 """Tests urllib2 authentication features."""
77
78 ## Disabled at the moment since there is no page under python.org which
79 ## could be used to HTTP authentication.
80 #
81 # def test_basic_auth(self):
82 # import http.client
83 #
84 # test_url = "http://www.python.org/test/test_urllib2/basic_auth"
85 # test_hostport = "www.python.org"
86 # test_realm = 'Test Realm'
87 # test_user = 'test.test_urllib2net'
88 # test_password = 'blah'
89 #
90 # # failure
91 # try:
92 # _urlopen_with_retry(test_url)
93 # except urllib2.HTTPError, exc:
94 # self.assertEqual(exc.code, 401)
95 # else:
96 # self.fail("urlopen() should have failed with 401")
97 #
98 # # success
99 # auth_handler = urllib2.HTTPBasicAuthHandler()
100 # auth_handler.add_password(test_realm, test_hostport,
101 # test_user, test_password)
102 # opener = urllib2.build_opener(auth_handler)
103 # f = opener.open('http://localhost/')
104 # response = _urlopen_with_retry("http://www.python.org/")
105 #
106 # # The 'userinfo' URL component is deprecated by RFC 3986 for security
107 # # reasons, let's not implement it! (it's already implemented for proxy
108 # # specification strings (that is, URLs or authorities specifying a
109 # # proxy), so we must keep that)
110 # self.assertRaises(http.client.InvalidURL,
111 # urllib2.urlopen, "http://evil:[email protected]")
112
113
114 class CloseSocketTest(unittest.TestCase):
115
116 def test_close(self):
117 # clear _opener global variable
118 self.addCleanup(urllib.request.urlcleanup)
119
120 # calling .close() on urllib2's response objects should close the
121 # underlying socket
122 url = support.TEST_HTTP_URL
123 with socket_helper.transient_internet(url):
124 response = _urlopen_with_retry(url)
125 sock = response.fp
126 self.assertFalse(sock.closed)
127 response.close()
128 self.assertTrue(sock.closed)
129
130 class OtherNetworkTests(unittest.TestCase):
131 def setUp(self):
132 if 0: # for debugging
133 import logging
134 logger = logging.getLogger("test_urllib2net")
135 logger.addHandler(logging.StreamHandler())
136
137 # XXX The rest of these tests aren't very good -- they don't check much.
138 # They do sometimes catch some major disasters, though.
139
140 @support.requires_resource('walltime')
141 def test_ftp(self):
142 # Testing the same URL twice exercises the caching in CacheFTPHandler
143 urls = [
144 'ftp://www.pythontest.net/README',
145 'ftp://www.pythontest.net/README',
146 ('ftp://www.pythontest.net/non-existent-file',
147 None, urllib.error.URLError),
148 ]
149 self._test_urls(urls, self._extra_handlers())
150
151 @support.requires_resource('walltime')
152 @unittest.skipIf(sysconfig.get_platform() == 'linux-ppc64le',
153 'leaks on PPC64LE (gh-140691)')
154 def test_ftp_no_leak(self):
155 # gh-140691: When the data connection (but not control connection)
156 # cannot be made established, we shouldn't leave an open socket object.
157
158 class MockError(OSError):
159 pass
160
161 orig_create_connection = socket.create_connection
162 def patched_create_connection(address, *args, **kwargs):
163 """Simulate REJECTing connections to ports other than 21"""
164 host, port = address
165 if port != 21:
166 raise MockError()
167 return orig_create_connection(address, *args, **kwargs)
168
169 url = 'ftp://www.pythontest.net/README'
170 entry = url, None, urllib.error.URLError
171 no_cache_handlers = [urllib.request.FTPHandler()]
172 cache_handlers = self._extra_handlers()
173 with mock.patch('socket.create_connection', patched_create_connection):
174 with check_no_resource_warning(self):
175 # Try without CacheFTPHandler
176 self._test_urls([entry], handlers=no_cache_handlers,
177 retry=False)
178 with check_no_resource_warning(self):
179 # Try with CacheFTPHandler (uncached)
180 self._test_urls([entry], cache_handlers, retry=False)
181 with check_no_resource_warning(self):
182 # Try with CacheFTPHandler (cached)
183 self._test_urls([entry], cache_handlers, retry=False)
184 # Try without the mock: the handler should not use a closed connection
185 with check_no_resource_warning(self):
186 self._test_urls([url], cache_handlers, retry=False)
187
188 def test_file(self):
189 TESTFN = os_helper.TESTFN
190 f = open(TESTFN, 'w')
191 try:
192 f.write('hi there\n')
193 f.close()
194 urls = [
195 'file:' + sanepathname2url(os.path.abspath(TESTFN)),
196 ('file:///nonsensename/etc/passwd', None,
197 urllib.error.URLError),
198 ]
199 self._test_urls(urls, self._extra_handlers(), retry=True)
200 finally:
201 os.remove(TESTFN)
202
203 self.assertRaises(ValueError, urllib.request.urlopen,'./relative_path/to/file')
204
205 # XXX Following test depends on machine configurations that are internal
206 # to CNRI. Need to set up a public server with the right authentication
207 # configuration for test purposes.
208
209 ## def test_cnri(self):
210 ## if socket.gethostname() == 'bitdiddle':
211 ## localhost = 'bitdiddle.cnri.reston.va.us'
212 ## elif socket.gethostname() == 'bitdiddle.concentric.net':
213 ## localhost = 'localhost'
214 ## else:
215 ## localhost = None
216 ## if localhost is not None:
217 ## urls = [
218 ## 'file://%s/etc/passwd' % localhost,
219 ## 'http://%s/simple/' % localhost,
220 ## 'http://%s/digest/' % localhost,
221 ## 'http://%s/not/found.h' % localhost,
222 ## ]
223
224 ## bauth = HTTPBasicAuthHandler()
225 ## bauth.add_password('basic_test_realm', localhost, 'jhylton',
226 ## 'password')
227 ## dauth = HTTPDigestAuthHandler()
228 ## dauth.add_password('digest_test_realm', localhost, 'jhylton',
229 ## 'password')
230
231 ## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
232
233 def test_urlwithfrag(self):
234 urlwith_frag = "http://www.pythontest.net/index.html#frag"
235 with socket_helper.transient_internet(urlwith_frag):
236 req = urllib.request.Request(urlwith_frag)
237 res = urllib.request.urlopen(req)
238 self.assertEqual(res.geturl(),
239 "http://www.pythontest.net/index.html#frag")
240
241 @support.requires_resource('walltime')
242 def test_redirect_url_withfrag(self):
243 redirect_url_with_frag = "http://www.pythontest.net/redir/with_frag/"
244 with socket_helper.transient_internet(redirect_url_with_frag):
245 req = urllib.request.Request(redirect_url_with_frag)
246 res = urllib.request.urlopen(req)
247 self.assertEqual(res.geturl(),
248 "http://www.pythontest.net/elsewhere/#frag")
249
250 def test_custom_headers(self):
251 url = support.TEST_HTTP_URL
252 with socket_helper.transient_internet(url):
253 opener = urllib.request.build_opener()
254 request = urllib.request.Request(url)
255 self.assertFalse(request.header_items())
256 opener.open(request)
257 self.assertTrue(request.header_items())
258 self.assertTrue(request.has_header('User-agent'))
259 request.add_header('User-Agent','Test-Agent')
260 opener.open(request)
261 self.assertEqual(request.get_header('User-agent'),'Test-Agent')
262
263 @unittest.skip('XXX: http://www.imdb.com is gone')
264 def test_sites_no_connection_close(self):
265 # Some sites do not send Connection: close header.
266 # Verify that those work properly. (#issue12576)
267
268 URL = 'http://www.imdb.com' # mangles Connection:close
269
270 with socket_helper.transient_internet(URL):
271 try:
272 with urllib.request.urlopen(URL) as res:
273 pass
274 except ValueError:
275 self.fail("urlopen failed for site not sending \
276 Connection:close")
277 else:
278 self.assertTrue(res)
279
280 req = urllib.request.urlopen(URL)
281 res = req.read()
282 self.assertTrue(res)
283
284 def _test_urls(self, urls, handlers, retry=True):
285 import time
286 import logging
287 debug = logging.getLogger("test_urllib2").debug
288
289 urlopen = urllib.request.build_opener(*handlers).open
290 if retry:
291 urlopen = _wrap_with_retry_thrice(urlopen, urllib.error.URLError)
292
293 for url in urls:
294 with self.subTest(url=url):
295 if isinstance(url, tuple):
296 url, req, expected_err = url
297 else:
298 req = expected_err = None
299
300 if expected_err:
301 context = self.assertRaises(expected_err)
302 else:
303 context = contextlib.nullcontext()
304
305 with socket_helper.transient_internet(url):
306 f = None
307 with context:
308 f = urlopen(url, req, support.INTERNET_TIMEOUT)
309 if f is not None:
310 try:
311 with time_out, \
312 socket_peer_reset, \
313 ioerror_peer_reset:
314 buf = f.read()
315 debug("read %d bytes" % len(buf))
316 except TimeoutError:
317 print("<timeout: %s>" % url, file=sys.stderr)
318 f.close()
319 time.sleep(0.1)
320
321 def _extra_handlers(self):
322 handlers = []
323
324 cfh = urllib.request.CacheFTPHandler()
325 self.addCleanup(cfh.clear_cache)
326 cfh.setTimeout(1)
327 handlers.append(cfh)
328
329 return handlers
330
331
332 class TimeoutTest(unittest.TestCase):
333 def setUp(self):
334 # clear _opener global variable
335 self.addCleanup(urllib.request.urlcleanup)
336
337 def test_http_basic(self):
338 self.assertIsNone(socket.getdefaulttimeout())
339 url = support.TEST_HTTP_URL
340 with socket_helper.transient_internet(url, timeout=None):
341 u = _urlopen_with_retry(url)
342 self.addCleanup(u.close)
343 self.assertIsNone(u.fp.raw._sock.gettimeout())
344
345 def test_http_default_timeout(self):
346 self.assertIsNone(socket.getdefaulttimeout())
347 url = support.TEST_HTTP_URL
348 with socket_helper.transient_internet(url):
349 socket.setdefaulttimeout(60)
350 try:
351 u = _urlopen_with_retry(url)
352 self.addCleanup(u.close)
353 finally:
354 socket.setdefaulttimeout(None)
355 self.assertEqual(u.fp.raw._sock.gettimeout(), 60)
356
357 def test_http_no_timeout(self):
358 self.assertIsNone(socket.getdefaulttimeout())
359 url = support.TEST_HTTP_URL
360 with socket_helper.transient_internet(url):
361 socket.setdefaulttimeout(60)
362 try:
363 u = _urlopen_with_retry(url, timeout=None)
364 self.addCleanup(u.close)
365 finally:
366 socket.setdefaulttimeout(None)
367 self.assertIsNone(u.fp.raw._sock.gettimeout())
368
369 def test_http_timeout(self):
370 url = support.TEST_HTTP_URL
371 with socket_helper.transient_internet(url):
372 u = _urlopen_with_retry(url, timeout=120)
373 self.addCleanup(u.close)
374 self.assertEqual(u.fp.raw._sock.gettimeout(), 120)
375
376 FTP_HOST = 'ftp://www.pythontest.net/'
377
378 @support.requires_resource('walltime')
379 def test_ftp_basic(self):
380 self.assertIsNone(socket.getdefaulttimeout())
381 with socket_helper.transient_internet(self.FTP_HOST, timeout=None):
382 u = _urlopen_with_retry(self.FTP_HOST)
383 self.addCleanup(u.close)
384 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
385
386 def test_ftp_default_timeout(self):
387 self.assertIsNone(socket.getdefaulttimeout())
388 with socket_helper.transient_internet(self.FTP_HOST):
389 socket.setdefaulttimeout(60)
390 try:
391 u = _urlopen_with_retry(self.FTP_HOST)
392 self.addCleanup(u.close)
393 finally:
394 socket.setdefaulttimeout(None)
395 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
396
397 @support.requires_resource('walltime')
398 def test_ftp_no_timeout(self):
399 self.assertIsNone(socket.getdefaulttimeout())
400 with socket_helper.transient_internet(self.FTP_HOST):
401 socket.setdefaulttimeout(60)
402 try:
403 u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
404 self.addCleanup(u.close)
405 finally:
406 socket.setdefaulttimeout(None)
407 self.assertIsNone(u.fp.fp.raw._sock.gettimeout())
408
409 @support.requires_resource('walltime')
410 def test_ftp_timeout(self):
411 with socket_helper.transient_internet(self.FTP_HOST):
412 u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
413 self.addCleanup(u.close)
414 self.assertEqual(u.fp.fp.raw._sock.gettimeout(), 60)
415
416
417 if __name__ == "__main__":
418 unittest.main()