PageRenderTime 28ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/contrib/python-x86_64/lib/python2.7/test/test_urllib2net.py

https://gitlab.com/atom-k/android-plus-plus
Python | 332 lines | 213 code | 49 blank | 70 comment | 44 complexity | 5bb59deb5a24a69c763b72e044cf653d MD5 | raw file
  1. #!/usr/bin/env python
  2. import unittest
  3. from test import test_support
  4. from test.test_urllib2 import sanepathname2url
  5. import socket
  6. import urllib2
  7. import os
  8. import sys
  9. TIMEOUT = 60 # seconds
  10. def _retry_thrice(func, exc, *args, **kwargs):
  11. for i in range(3):
  12. try:
  13. return func(*args, **kwargs)
  14. except exc, last_exc:
  15. continue
  16. except:
  17. raise
  18. raise last_exc
  19. def _wrap_with_retry_thrice(func, exc):
  20. def wrapped(*args, **kwargs):
  21. return _retry_thrice(func, exc, *args, **kwargs)
  22. return wrapped
  23. # Connecting to remote hosts is flaky. Make it more robust by retrying
  24. # the connection several times.
  25. _urlopen_with_retry = _wrap_with_retry_thrice(urllib2.urlopen, urllib2.URLError)
  26. class AuthTests(unittest.TestCase):
  27. """Tests urllib2 authentication features."""
  28. ## Disabled at the moment since there is no page under python.org which
  29. ## could be used to HTTP authentication.
  30. #
  31. # def test_basic_auth(self):
  32. # import httplib
  33. #
  34. # test_url = "http://www.python.org/test/test_urllib2/basic_auth"
  35. # test_hostport = "www.python.org"
  36. # test_realm = 'Test Realm'
  37. # test_user = 'test.test_urllib2net'
  38. # test_password = 'blah'
  39. #
  40. # # failure
  41. # try:
  42. # _urlopen_with_retry(test_url)
  43. # except urllib2.HTTPError, exc:
  44. # self.assertEqual(exc.code, 401)
  45. # else:
  46. # self.fail("urlopen() should have failed with 401")
  47. #
  48. # # success
  49. # auth_handler = urllib2.HTTPBasicAuthHandler()
  50. # auth_handler.add_password(test_realm, test_hostport,
  51. # test_user, test_password)
  52. # opener = urllib2.build_opener(auth_handler)
  53. # f = opener.open('http://localhost/')
  54. # response = _urlopen_with_retry("http://www.python.org/")
  55. #
  56. # # The 'userinfo' URL component is deprecated by RFC 3986 for security
  57. # # reasons, let's not implement it! (it's already implemented for proxy
  58. # # specification strings (that is, URLs or authorities specifying a
  59. # # proxy), so we must keep that)
  60. # self.assertRaises(httplib.InvalidURL,
  61. # urllib2.urlopen, "http://evil:thing@example.com")
  62. class CloseSocketTest(unittest.TestCase):
  63. def test_close(self):
  64. import httplib
  65. # calling .close() on urllib2's response objects should close the
  66. # underlying socket
  67. # delve deep into response to fetch socket._socketobject
  68. response = _urlopen_with_retry("http://www.python.org/")
  69. abused_fileobject = response.fp
  70. self.assertTrue(abused_fileobject.__class__ is socket._fileobject)
  71. httpresponse = abused_fileobject._sock
  72. self.assertTrue(httpresponse.__class__ is httplib.HTTPResponse)
  73. fileobject = httpresponse.fp
  74. self.assertTrue(fileobject.__class__ is socket._fileobject)
  75. self.assertTrue(not fileobject.closed)
  76. response.close()
  77. self.assertTrue(fileobject.closed)
  78. class OtherNetworkTests(unittest.TestCase):
  79. def setUp(self):
  80. if 0: # for debugging
  81. import logging
  82. logger = logging.getLogger("test_urllib2net")
  83. logger.addHandler(logging.StreamHandler())
  84. # XXX The rest of these tests aren't very good -- they don't check much.
  85. # They do sometimes catch some major disasters, though.
  86. def test_ftp(self):
  87. urls = [
  88. 'ftp://ftp.kernel.org/pub/linux/kernel/README',
  89. 'ftp://ftp.kernel.org/pub/linux/kernel/non-existent-file',
  90. #'ftp://ftp.kernel.org/pub/leenox/kernel/test',
  91. 'ftp://gatekeeper.research.compaq.com/pub/DEC/SRC'
  92. '/research-reports/00README-Legal-Rules-Regs',
  93. ]
  94. self._test_urls(urls, self._extra_handlers())
  95. def test_file(self):
  96. TESTFN = test_support.TESTFN
  97. f = open(TESTFN, 'w')
  98. try:
  99. f.write('hi there\n')
  100. f.close()
  101. urls = [
  102. 'file:'+sanepathname2url(os.path.abspath(TESTFN)),
  103. ('file:///nonsensename/etc/passwd', None, urllib2.URLError),
  104. ]
  105. self._test_urls(urls, self._extra_handlers(), retry=True)
  106. finally:
  107. os.remove(TESTFN)
  108. self.assertRaises(ValueError, urllib2.urlopen,'./relative_path/to/file')
  109. # XXX Following test depends on machine configurations that are internal
  110. # to CNRI. Need to set up a public server with the right authentication
  111. # configuration for test purposes.
  112. ## def test_cnri(self):
  113. ## if socket.gethostname() == 'bitdiddle':
  114. ## localhost = 'bitdiddle.cnri.reston.va.us'
  115. ## elif socket.gethostname() == 'bitdiddle.concentric.net':
  116. ## localhost = 'localhost'
  117. ## else:
  118. ## localhost = None
  119. ## if localhost is not None:
  120. ## urls = [
  121. ## 'file://%s/etc/passwd' % localhost,
  122. ## 'http://%s/simple/' % localhost,
  123. ## 'http://%s/digest/' % localhost,
  124. ## 'http://%s/not/found.h' % localhost,
  125. ## ]
  126. ## bauth = HTTPBasicAuthHandler()
  127. ## bauth.add_password('basic_test_realm', localhost, 'jhylton',
  128. ## 'password')
  129. ## dauth = HTTPDigestAuthHandler()
  130. ## dauth.add_password('digest_test_realm', localhost, 'jhylton',
  131. ## 'password')
  132. ## self._test_urls(urls, self._extra_handlers()+[bauth, dauth])
  133. def test_urlwithfrag(self):
  134. urlwith_frag = "http://docs.python.org/2/glossary.html#glossary"
  135. with test_support.transient_internet(urlwith_frag):
  136. req = urllib2.Request(urlwith_frag)
  137. res = urllib2.urlopen(req)
  138. self.assertEqual(res.geturl(),
  139. "http://docs.python.org/2/glossary.html#glossary")
  140. def test_fileno(self):
  141. req = urllib2.Request("http://www.python.org")
  142. opener = urllib2.build_opener()
  143. res = opener.open(req)
  144. try:
  145. res.fileno()
  146. except AttributeError:
  147. self.fail("HTTPResponse object should return a valid fileno")
  148. finally:
  149. res.close()
  150. def test_custom_headers(self):
  151. url = "http://www.example.com"
  152. with test_support.transient_internet(url):
  153. opener = urllib2.build_opener()
  154. request = urllib2.Request(url)
  155. self.assertFalse(request.header_items())
  156. opener.open(request)
  157. self.assertTrue(request.header_items())
  158. self.assertTrue(request.has_header('User-agent'))
  159. request.add_header('User-Agent','Test-Agent')
  160. opener.open(request)
  161. self.assertEqual(request.get_header('User-agent'),'Test-Agent')
  162. def test_sites_no_connection_close(self):
  163. # Some sites do not send Connection: close header.
  164. # Verify that those work properly. (#issue12576)
  165. URL = 'http://www.imdb.com' # No Connection:close
  166. with test_support.transient_internet(URL):
  167. req = urllib2.urlopen(URL)
  168. res = req.read()
  169. self.assertTrue(res)
  170. def _test_urls(self, urls, handlers, retry=True):
  171. import time
  172. import logging
  173. debug = logging.getLogger("test_urllib2").debug
  174. urlopen = urllib2.build_opener(*handlers).open
  175. if retry:
  176. urlopen = _wrap_with_retry_thrice(urlopen, urllib2.URLError)
  177. for url in urls:
  178. if isinstance(url, tuple):
  179. url, req, expected_err = url
  180. else:
  181. req = expected_err = None
  182. with test_support.transient_internet(url):
  183. debug(url)
  184. try:
  185. f = urlopen(url, req, TIMEOUT)
  186. except EnvironmentError as err:
  187. debug(err)
  188. if expected_err:
  189. msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
  190. (expected_err, url, req, type(err), err))
  191. self.assertIsInstance(err, expected_err, msg)
  192. except urllib2.URLError as err:
  193. if isinstance(err[0], socket.timeout):
  194. print >>sys.stderr, "<timeout: %s>" % url
  195. continue
  196. else:
  197. raise
  198. else:
  199. try:
  200. with test_support.transient_internet(url):
  201. buf = f.read()
  202. debug("read %d bytes" % len(buf))
  203. except socket.timeout:
  204. print >>sys.stderr, "<timeout: %s>" % url
  205. f.close()
  206. debug("******** next url coming up...")
  207. time.sleep(0.1)
  208. def _extra_handlers(self):
  209. handlers = []
  210. cfh = urllib2.CacheFTPHandler()
  211. self.addCleanup(cfh.clear_cache)
  212. cfh.setTimeout(1)
  213. handlers.append(cfh)
  214. return handlers
  215. class TimeoutTest(unittest.TestCase):
  216. def test_http_basic(self):
  217. self.assertTrue(socket.getdefaulttimeout() is None)
  218. url = "http://www.python.org"
  219. with test_support.transient_internet(url, timeout=None):
  220. u = _urlopen_with_retry(url)
  221. self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
  222. def test_http_default_timeout(self):
  223. self.assertTrue(socket.getdefaulttimeout() is None)
  224. url = "http://www.python.org"
  225. with test_support.transient_internet(url):
  226. socket.setdefaulttimeout(60)
  227. try:
  228. u = _urlopen_with_retry(url)
  229. finally:
  230. socket.setdefaulttimeout(None)
  231. self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 60)
  232. def test_http_no_timeout(self):
  233. self.assertTrue(socket.getdefaulttimeout() is None)
  234. url = "http://www.python.org"
  235. with test_support.transient_internet(url):
  236. socket.setdefaulttimeout(60)
  237. try:
  238. u = _urlopen_with_retry(url, timeout=None)
  239. finally:
  240. socket.setdefaulttimeout(None)
  241. self.assertTrue(u.fp._sock.fp._sock.gettimeout() is None)
  242. def test_http_timeout(self):
  243. url = "http://www.python.org"
  244. with test_support.transient_internet(url):
  245. u = _urlopen_with_retry(url, timeout=120)
  246. self.assertEqual(u.fp._sock.fp._sock.gettimeout(), 120)
  247. FTP_HOST = "ftp://ftp.mirror.nl/pub/gnu/"
  248. def test_ftp_basic(self):
  249. self.assertTrue(socket.getdefaulttimeout() is None)
  250. with test_support.transient_internet(self.FTP_HOST, timeout=None):
  251. u = _urlopen_with_retry(self.FTP_HOST)
  252. self.assertTrue(u.fp.fp._sock.gettimeout() is None)
  253. def test_ftp_default_timeout(self):
  254. self.assertTrue(socket.getdefaulttimeout() is None)
  255. with test_support.transient_internet(self.FTP_HOST):
  256. socket.setdefaulttimeout(60)
  257. try:
  258. u = _urlopen_with_retry(self.FTP_HOST)
  259. finally:
  260. socket.setdefaulttimeout(None)
  261. self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
  262. def test_ftp_no_timeout(self):
  263. self.assertTrue(socket.getdefaulttimeout() is None)
  264. with test_support.transient_internet(self.FTP_HOST):
  265. socket.setdefaulttimeout(60)
  266. try:
  267. u = _urlopen_with_retry(self.FTP_HOST, timeout=None)
  268. finally:
  269. socket.setdefaulttimeout(None)
  270. self.assertTrue(u.fp.fp._sock.gettimeout() is None)
  271. def test_ftp_timeout(self):
  272. with test_support.transient_internet(self.FTP_HOST):
  273. u = _urlopen_with_retry(self.FTP_HOST, timeout=60)
  274. self.assertEqual(u.fp.fp._sock.gettimeout(), 60)
  275. def test_main():
  276. test_support.requires("network")
  277. test_support.run_unittest(AuthTests,
  278. OtherNetworkTests,
  279. CloseSocketTest,
  280. TimeoutTest,
  281. )
  282. if __name__ == "__main__":
  283. test_main()