blob: c318ef3ea1a69d98a12ac4df77287f3d3ce7e67d [file] [log] [blame]
Skip Montanaro89feabc2003-03-30 04:54:24 +00001import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00002from test import support
Skip Montanaro89feabc2003-03-30 04:54:24 +00003
Antoine Pitroua98d26a2011-05-22 17:35:17 +02004import contextlib
Skip Montanaro89feabc2003-03-30 04:54:24 +00005import socket
Jeremy Hylton1afc1692008-06-18 20:49:58 +00006import urllib.request
Brett Cannona71319e2003-05-14 02:18:31 +00007import os
Barry Warsaw820c1202008-06-12 04:06:45 +00008import email.message
Senthil Kumaranf6c456d2010-05-01 08:29:18 +00009import time
Skip Montanaro89feabc2003-03-30 04:54:24 +000010
Christian Heimesaf98da12008-01-27 15:18:18 +000011
Senthil Kumarancfdd0162014-04-14 21:31:41 -040012support.requires('network')
13
Skip Montanaro89feabc2003-03-30 04:54:24 +000014class URLTimeoutTest(unittest.TestCase):
Antoine Pitroud9faa202011-03-26 18:38:06 +010015 # XXX this test doesn't seem to test anything useful.
Skip Montanaro89feabc2003-03-30 04:54:24 +000016
Senthil Kumaranbd8f1452010-12-15 04:02:45 +000017 TIMEOUT = 30.0
Skip Montanaro89feabc2003-03-30 04:54:24 +000018
19 def setUp(self):
20 socket.setdefaulttimeout(self.TIMEOUT)
21
22 def tearDown(self):
23 socket.setdefaulttimeout(None)
24
25 def testURLread(self):
Ned Deily5a507f02014-03-26 23:31:39 -070026 with support.transient_internet("www.example.com"):
27 f = urllib.request.urlopen("http://www.example.com/")
Antoine Pitroud9faa202011-03-26 18:38:06 +010028 x = f.read()
Skip Montanaro89feabc2003-03-30 04:54:24 +000029
Antoine Pitroua98d26a2011-05-22 17:35:17 +020030
Brett Cannona71319e2003-05-14 02:18:31 +000031class urlopenNetworkTests(unittest.TestCase):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000032 """Tests urllib.reqest.urlopen using the network.
Tim Peters813cec92003-05-16 15:35:10 +000033
Brett Cannona71319e2003-05-14 02:18:31 +000034 These tests are not exhaustive. Assuming that testing using files does a
35 good job overall of some of the basic interface features. There are no
36 tests exercising the optional 'data' and 'proxies' arguments. No tests
37 for transparent redirection have been written.
Tim Peters813cec92003-05-16 15:35:10 +000038
Brett Cannona71319e2003-05-14 02:18:31 +000039 setUp is not used for always constructing a connection to
Ned Deily5a507f02014-03-26 23:31:39 -070040 http://www.example.com/ since there a few tests that don't use that address
Brett Cannona71319e2003-05-14 02:18:31 +000041 and making a connection is expensive enough to warrant minimizing unneeded
42 connections.
Tim Peters813cec92003-05-16 15:35:10 +000043
Brett Cannona71319e2003-05-14 02:18:31 +000044 """
45
Antoine Pitroua98d26a2011-05-22 17:35:17 +020046 @contextlib.contextmanager
Senthil Kumaranee2538b2010-10-17 10:52:12 +000047 def urlopen(self, *args, **kwargs):
48 resource = args[0]
Antoine Pitroua98d26a2011-05-22 17:35:17 +020049 with support.transient_internet(resource):
50 r = urllib.request.urlopen(*args, **kwargs)
51 try:
52 yield r
53 finally:
54 r.close()
Christian Heimesaf98da12008-01-27 15:18:18 +000055
Brett Cannona71319e2003-05-14 02:18:31 +000056 def test_basic(self):
57 # Simple test expected to pass.
Ned Deily5a507f02014-03-26 23:31:39 -070058 with self.urlopen("http://www.example.com/") as open_url:
Antoine Pitroua98d26a2011-05-22 17:35:17 +020059 for attr in ("read", "readline", "readlines", "fileno", "close",
60 "info", "geturl"):
61 self.assertTrue(hasattr(open_url, attr), "object returned from "
62 "urlopen lacks the %s attribute" % attr)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000063 self.assertTrue(open_url.read(), "calling 'read' failed")
Brett Cannona71319e2003-05-14 02:18:31 +000064
65 def test_readlines(self):
66 # Test both readline and readlines.
Ned Deily5a507f02014-03-26 23:31:39 -070067 with self.urlopen("http://www.example.com/") as open_url:
Ezio Melottie9615932010-01-24 19:26:24 +000068 self.assertIsInstance(open_url.readline(), bytes,
69 "readline did not return a string")
70 self.assertIsInstance(open_url.readlines(), list,
71 "readlines did not return a list")
Brett Cannona71319e2003-05-14 02:18:31 +000072
73 def test_info(self):
74 # Test 'info'.
Ned Deily5a507f02014-03-26 23:31:39 -070075 with self.urlopen("http://www.example.com/") as open_url:
Brett Cannona71319e2003-05-14 02:18:31 +000076 info_obj = open_url.info()
Ezio Melottie9615932010-01-24 19:26:24 +000077 self.assertIsInstance(info_obj, email.message.Message,
78 "object returned by 'info' is not an "
79 "instance of email.message.Message")
Barry Warsaw820c1202008-06-12 04:06:45 +000080 self.assertEqual(info_obj.get_content_subtype(), "html")
Brett Cannona71319e2003-05-14 02:18:31 +000081
82 def test_geturl(self):
83 # Make sure same URL as opened is returned by geturl.
Ned Deily5a507f02014-03-26 23:31:39 -070084 URL = "http://www.example.com/"
Antoine Pitroua98d26a2011-05-22 17:35:17 +020085 with self.urlopen(URL) as open_url:
Brett Cannona71319e2003-05-14 02:18:31 +000086 gotten_url = open_url.geturl()
Antoine Pitroua98d26a2011-05-22 17:35:17 +020087 self.assertEqual(gotten_url, URL)
Brett Cannona71319e2003-05-14 02:18:31 +000088
Christian Heimes9bd667a2008-01-20 15:14:11 +000089 def test_getcode(self):
90 # test getcode() with the fancy opener to get 404 error codes
Ned Deily5a507f02014-03-26 23:31:39 -070091 URL = "http://www.example.com/XXXinvalidXXX"
Antoine Pitroua98d26a2011-05-22 17:35:17 +020092 with support.transient_internet(URL):
R David Murray130a5662014-06-11 17:09:43 -040093 with self.assertWarns(DeprecationWarning):
94 open_url = urllib.request.FancyURLopener().open(URL)
Antoine Pitroua98d26a2011-05-22 17:35:17 +020095 try:
96 code = open_url.getcode()
97 finally:
98 open_url.close()
99 self.assertEqual(code, 404)
Christian Heimes9bd667a2008-01-20 15:14:11 +0000100
Brett Cannona71319e2003-05-14 02:18:31 +0000101 def test_bad_address(self):
102 # Make sure proper exception is raised when connecting to a bogus
103 # address.
Martin Pantera7f99332015-12-16 04:36:20 +0000104
105 # Given that both VeriSign and various ISPs have in
106 # the past or are presently hijacking various invalid
107 # domain name requests in an attempt to boost traffic
108 # to their own sites, finding a domain name to use
109 # for this test is difficult. RFC2606 leads one to
110 # believe that '.invalid' should work, but experience
111 # seemed to indicate otherwise. Single character
112 # TLDs are likely to remain invalid, so this seems to
113 # be the best choice. The trailing '.' prevents a
114 # related problem: The normal DNS resolver appends
115 # the domain names from the search path if there is
116 # no '.' the end and, and if one of those domains
117 # implements a '*' rule a result is returned.
118 # However, none of this will prevent the test from
119 # failing if the ISP hijacks all invalid domain
120 # requests. The real solution would be to be able to
121 # parameterize the framework with a mock resolver.
122 bogus_domain = "sadflkjsasf.i.nvali.d."
Antoine Pitrou72fff042011-07-08 19:19:57 +0200123 try:
124 socket.gethostbyname(bogus_domain)
Antoine Pitrou6b5a38c2013-05-25 13:08:13 +0200125 except OSError:
126 # socket.gaierror is too narrow, since getaddrinfo() may also
127 # fail with EAI_SYSTEM and ETIMEDOUT (seen on Ubuntu 13.04),
128 # i.e. Python's TimeoutError.
Antoine Pitrou72fff042011-07-08 19:19:57 +0200129 pass
130 else:
131 # This happens with some overzealous DNS providers such as OpenDNS
132 self.skipTest("%r should not resolve for test to work" % bogus_domain)
Brett Cannonb463c482013-01-11 11:17:53 -0500133 failure_explanation = ('opening an invalid URL did not raise OSError; '
134 'can be caused by a broken DNS server '
135 '(e.g. returns 404 or hijacks page)')
136 with self.assertRaises(OSError, msg=failure_explanation):
Martin Pantera7f99332015-12-16 04:36:20 +0000137 urllib.request.urlopen("http://{}/".format(bogus_domain))
Brett Cannona71319e2003-05-14 02:18:31 +0000138
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200139
Brett Cannona71319e2003-05-14 02:18:31 +0000140class urlretrieveNetworkTests(unittest.TestCase):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000141 """Tests urllib.request.urlretrieve using the network."""
Brett Cannona71319e2003-05-14 02:18:31 +0000142
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200143 @contextlib.contextmanager
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800144 def urlretrieve(self, *args, **kwargs):
Senthil Kumaranee2538b2010-10-17 10:52:12 +0000145 resource = args[0]
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200146 with support.transient_internet(resource):
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800147 file_location, info = urllib.request.urlretrieve(*args, **kwargs)
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200148 try:
149 yield file_location, info
150 finally:
151 support.unlink(file_location)
Christian Heimesaf98da12008-01-27 15:18:18 +0000152
Brett Cannona71319e2003-05-14 02:18:31 +0000153 def test_basic(self):
154 # Test basic functionality.
Ned Deily5a507f02014-03-26 23:31:39 -0700155 with self.urlretrieve("http://www.example.com/") as (file_location, info):
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200156 self.assertTrue(os.path.exists(file_location), "file location returned by"
157 " urlretrieve is not a valid path")
Benjamin Petersona96ed632014-02-19 23:06:41 -0500158 with open(file_location, 'rb') as f:
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200159 self.assertTrue(f.read(), "reading from the file location returned"
160 " by urlretrieve failed")
Brett Cannona71319e2003-05-14 02:18:31 +0000161
162 def test_specified_path(self):
163 # Make sure that specifying the location of the file to write to works.
Ned Deily5a507f02014-03-26 23:31:39 -0700164 with self.urlretrieve("http://www.example.com/",
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200165 support.TESTFN) as (file_location, info):
166 self.assertEqual(file_location, support.TESTFN)
167 self.assertTrue(os.path.exists(file_location))
Benjamin Petersona96ed632014-02-19 23:06:41 -0500168 with open(file_location, 'rb') as f:
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200169 self.assertTrue(f.read(), "reading from temporary file failed")
Brett Cannona71319e2003-05-14 02:18:31 +0000170
171 def test_header(self):
172 # Make sure header returned as 2nd value from urlretrieve is good.
Ned Deily5a507f02014-03-26 23:31:39 -0700173 with self.urlretrieve("http://www.example.com/") as (file_location, info):
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200174 self.assertIsInstance(info, email.message.Message,
175 "info is not an instance of email.message.Message")
Tim Peters813cec92003-05-16 15:35:10 +0000176
Ned Deily5a507f02014-03-26 23:31:39 -0700177 logo = "http://www.example.com/"
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800178
Senthil Kumaranf6c456d2010-05-01 08:29:18 +0000179 def test_data_header(self):
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800180 with self.urlretrieve(self.logo) as (file_location, fileheaders):
Antoine Pitroua98d26a2011-05-22 17:35:17 +0200181 datevalue = fileheaders.get('Date')
182 dateformat = '%a, %d %b %Y %H:%M:%S GMT'
183 try:
184 time.strptime(datevalue, dateformat)
185 except ValueError:
186 self.fail('Date value not in %r format', dateformat)
Brett Cannona71319e2003-05-14 02:18:31 +0000187
Gregory P. Smith6b0bdab2012-11-10 13:43:44 -0800188 def test_reporthook(self):
189 records = []
190 def recording_reporthook(blocks, block_size, total_size):
191 records.append((blocks, block_size, total_size))
192
193 with self.urlretrieve(self.logo, reporthook=recording_reporthook) as (
194 file_location, fileheaders):
195 expected_size = int(fileheaders['Content-Length'])
196
197 records_repr = repr(records) # For use in error messages.
198 self.assertGreater(len(records), 1, msg="There should always be two "
199 "calls; the first one before the transfer starts.")
200 self.assertEqual(records[0][0], 0)
201 self.assertGreater(records[0][1], 0,
202 msg="block size can't be 0 in %s" % records_repr)
203 self.assertEqual(records[0][2], expected_size)
204 self.assertEqual(records[-1][2], expected_size)
205
206 block_sizes = {block_size for _, block_size, _ in records}
207 self.assertEqual({records[0][1]}, block_sizes,
208 msg="block sizes in %s must be equal" % records_repr)
209 self.assertGreaterEqual(records[-1][0]*records[0][1], expected_size,
210 msg="number of blocks * block size must be"
211 " >= total size in %s" % records_repr)
212
Brett Cannona71319e2003-05-14 02:18:31 +0000213
Skip Montanaro89feabc2003-03-30 04:54:24 +0000214if __name__ == "__main__":
Senthil Kumarancfdd0162014-04-14 21:31:41 -0400215 unittest.main()