Debian Codegraph @

cpython27/Lib/test/test_urllibnet.py

raw symbols SCIP
1 import unittest
2 from test import test_support
3 from test.test_urllib2net import skip_ftp_test_on_travis
4
5 import socket
6 import urllib
7 import sys
8 import os
9 import time
10
11 try:
12 import ssl
13 except ImportError:
14 ssl = None
15
16 here = os.path.dirname(__file__)
17 # Self-signed cert file for self-signed.pythontest.net
18 CERT_selfsigned_pythontestdotnet = os.path.join(here, 'selfsigned_pythontestdotnet.pem')
19
20 mimetools = test_support.import_module("mimetools", deprecated=True)
21
22
23 def _open_with_retry(func, host, *args, **kwargs):
24 # Connecting to remote hosts is flaky. Make it more robust
25 # by retrying the connection several times.
26 for i in range(3):
27 try:
28 return func(host, *args, **kwargs)
29 except IOError, last_exc:
30 continue
31 except:
32 raise
33 raise last_exc
34
35
36 class URLTimeoutTest(unittest.TestCase):
37
38 TIMEOUT = 10.0
39
40 def setUp(self):
41 socket.setdefaulttimeout(self.TIMEOUT)
42
43 def tearDown(self):
44 socket.setdefaulttimeout(None)
45
46 def testURLread(self):
47 f = _open_with_retry(urllib.urlopen, test_support.TEST_HTTP_URL)
48 x = f.read()
49
50 class urlopenNetworkTests(unittest.TestCase):
51 """Tests urllib.urlopen using the network.
52
53 These tests are not exhaustive. Assuming that testing using files does a
54 good job overall of some of the basic interface features. There are no
55 tests exercising the optional 'data' and 'proxies' arguments. No tests
56 for transparent redirection have been written.
57
58 setUp is not used for always constructing a connection to
59 http://www.example.com/ since there a few tests that don't use that address
60 and making a connection is expensive enough to warrant minimizing unneeded
61 connections.
62
63 """
64
65 def urlopen(self, *args):
66 return _open_with_retry(urllib.urlopen, *args)
67
68 def test_basic(self):
69 # Simple test expected to pass.
70 open_url = self.urlopen(test_support.TEST_HTTP_URL)
71 for attr in ("read", "readline", "readlines", "fileno", "close",
72 "info", "geturl"):
73 self.assertTrue(hasattr(open_url, attr), "object returned from "
74 "urlopen lacks the %s attribute" % attr)
75 try:
76 self.assertTrue(open_url.read(), "calling 'read' failed")
77 finally:
78 open_url.close()
79
80 def test_readlines(self):
81 # Test both readline and readlines.
82 open_url = self.urlopen(test_support.TEST_HTTP_URL)
83 try:
84 self.assertIsInstance(open_url.readline(), basestring,
85 "readline did not return a string")
86 self.assertIsInstance(open_url.readlines(), list,
87 "readlines did not return a list")
88 finally:
89 open_url.close()
90
91 def test_info(self):
92 # Test 'info'.
93 open_url = self.urlopen(test_support.TEST_HTTP_URL)
94 try:
95 info_obj = open_url.info()
96 finally:
97 open_url.close()
98 self.assertIsInstance(info_obj, mimetools.Message,
99 "object returned by 'info' is not an "
100 "instance of mimetools.Message")
101 self.assertEqual(info_obj.getsubtype(), "html")
102
103 def test_geturl(self):
104 # Make sure same URL as opened is returned by geturl.
105 open_url = self.urlopen(test_support.TEST_HTTP_URL)
106 try:
107 gotten_url = open_url.geturl()
108 finally:
109 open_url.close()
110 self.assertEqual(gotten_url, test_support.TEST_HTTP_URL)
111
112 def test_getcode(self):
113 # test getcode() with the fancy opener to get 404 error codes
114 URL = "http://www.pythontest.net/XXXinvalidXXX"
115 open_url = urllib.FancyURLopener().open(URL)
116 try:
117 code = open_url.getcode()
118 finally:
119 open_url.close()
120 self.assertEqual(code, 404)
121
122 @unittest.skipIf(sys.platform in ('win32',), 'not appropriate for Windows')
123 @unittest.skipUnless(hasattr(os, 'fdopen'), 'os.fdopen not available')
124 def test_fileno(self):
125 # Make sure fd returned by fileno is valid.
126 open_url = self.urlopen(test_support.TEST_HTTP_URL)
127 fd = open_url.fileno()
128 FILE = os.fdopen(fd)
129 try:
130 self.assertTrue(FILE.read(),
131 "reading from file created using fd "
132 "returned by fileno failed")
133 finally:
134 FILE.close()
135
136 def test_bad_address(self):
137 # Make sure proper exception is raised when connecting to a bogus
138 # address.
139 bogus_domain = "sadflkjsasf.i.nvali.d"
140 try:
141 socket.gethostbyname(bogus_domain)
142 except socket.gaierror:
143 pass
144 else:
145 # This happens with some overzealous DNS providers such as OpenDNS
146 self.skipTest("%r should not resolve for test to work" % bogus_domain)
147 self.assertRaises(IOError,
148 # SF patch 809915: In Sep 2003, VeriSign started
149 # highjacking invalid .com and .net addresses to
150 # boost traffic to their own site. This test
151 # started failing then. One hopes the .invalid
152 # domain will be spared to serve its defined
153 # purpose.
154 # urllib.urlopen, "http://www.sadflkjsasadf.com/")
155 urllib.urlopen, "http://sadflkjsasf.i.nvali.d/")
156
157 class urlretrieveNetworkTests(unittest.TestCase):
158 """Tests urllib.urlretrieve using the network."""
159
160 def urlretrieve(self, *args):
161 return _open_with_retry(urllib.urlretrieve, *args)
162
163 def test_basic(self):
164 # Test basic functionality.
165 file_location,info = self.urlretrieve(test_support.TEST_HTTP_URL)
166 self.assertTrue(os.path.exists(file_location), "file location returned by"
167 " urlretrieve is not a valid path")
168 FILE = file(file_location)
169 try:
170 self.assertTrue(FILE.read(), "reading from the file location returned"
171 " by urlretrieve failed")
172 finally:
173 FILE.close()
174 os.unlink(file_location)
175
176 def test_specified_path(self):
177 # Make sure that specifying the location of the file to write to works.
178 file_location,info = self.urlretrieve(test_support.TEST_HTTP_URL,
179 test_support.TESTFN)
180 self.assertEqual(file_location, test_support.TESTFN)
181 self.assertTrue(os.path.exists(file_location))
182 FILE = file(file_location)
183 try:
184 self.assertTrue(FILE.read(), "reading from temporary file failed")
185 finally:
186 FILE.close()
187 os.unlink(file_location)
188
189 def test_header(self):
190 # Make sure header returned as 2nd value from urlretrieve is good.
191 file_location, header = self.urlretrieve(test_support.TEST_HTTP_URL)
192 os.unlink(file_location)
193 self.assertIsInstance(header, mimetools.Message,
194 "header is not an instance of mimetools.Message")
195
196 def test_data_header(self):
197 logo = test_support.TEST_HTTP_URL
198 file_location, fileheaders = self.urlretrieve(logo)
199 os.unlink(file_location)
200 datevalue = fileheaders.getheader('Date')
201 dateformat = '%a, %d %b %Y %H:%M:%S GMT'
202 try:
203 time.strptime(datevalue, dateformat)
204 except ValueError:
205 self.fail('Date value not in %r format', dateformat)
206
207
208 @unittest.skipIf(ssl is None, "requires ssl")
209 class urlopen_HttpsTests(unittest.TestCase):
210
211 def test_context_argument(self):
212 context = ssl.create_default_context(cafile=CERT_selfsigned_pythontestdotnet)
213 response = urllib.urlopen("https://self-signed.pythontest.net", context=context)
214 self.assertIn("Python", response.read())
215
216
217 class urlopen_FTPTest(unittest.TestCase):
218 FTP_TEST_FILE = 'ftp://www.pythontest.net/README'
219 NUM_FTP_RETRIEVES = 3
220
221 @skip_ftp_test_on_travis
222 def test_multiple_ftp_retrieves(self):
223
224 with test_support.transient_internet(self.FTP_TEST_FILE):
225 try:
226 for file_num in range(self.NUM_FTP_RETRIEVES):
227 with test_support.temp_dir() as td:
228 urllib.FancyURLopener().retrieve(self.FTP_TEST_FILE,
229 os.path.join(td, str(file_num)))
230 except IOError as e:
231 self.fail("Failed FTP retrieve while accessing ftp url "
232 "multiple times.\n Error message was : %s" % e)
233
234 @skip_ftp_test_on_travis
235 def test_multiple_ftp_urlopen_same_host(self):
236 with test_support.transient_internet(self.FTP_TEST_FILE):
237 ftp_fds_to_close = []
238 try:
239 for _ in range(self.NUM_FTP_RETRIEVES):
240 fd = urllib.urlopen(self.FTP_TEST_FILE)
241 # test ftp open without closing fd as a supported scenario.
242 ftp_fds_to_close.append(fd)
243 except IOError as e:
244 self.fail("Failed FTP binary file open. "
245 "Error message was: %s" % e)
246 finally:
247 # close the open fds
248 for fd in ftp_fds_to_close:
249 fd.close()
250
251
252 def test_main():
253 test_support.requires('network')
254 with test_support.check_py3k_warnings(
255 ("urllib.urlopen.. has been removed", DeprecationWarning)):
256 test_support.run_unittest(URLTimeoutTest,
257 urlopenNetworkTests,
258 urlretrieveNetworkTests,
259 urlopen_HttpsTests,
260 urlopen_FTPTest)
261
262 if __name__ == "__main__":
263 test_main()