blob: 623eb5ef2f948b839fb0099b86aab9e14fc9d387 [file] [log] [blame]
Brett Cannon74bfd702003-04-25 09:39:47 +00001"""Regresssion tests for urllib"""
2
Jeremy Hylton1afc1692008-06-18 20:49:58 +00003import urllib.parse
4import urllib.request
guido@google.coma119df92011-03-29 11:41:02 -07005import urllib.error
Georg Brandl24420152008-05-26 16:32:26 +00006import http.client
Barry Warsaw820c1202008-06-12 04:06:45 +00007import email.message
Jeremy Hylton66dc8c52007-08-04 03:42:26 +00008import io
Brett Cannon74bfd702003-04-25 09:39:47 +00009import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Brett Cannon74bfd702003-04-25 09:39:47 +000011import os
Senthil Kumaran2d2ea1b2011-04-14 13:16:30 +080012import sys
Georg Brandl5a650a22005-08-26 08:51:34 +000013import tempfile
Jeremy Hylton6102e292000-08-31 15:48:10 +000014
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080015from base64 import b64encode
Georg Brandl2daf6ae2012-02-20 19:54:16 +010016import collections
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080017
Brett Cannon74bfd702003-04-25 09:39:47 +000018def hexescape(char):
19 """Escape char as RFC 2396 specifies"""
20 hex_repr = hex(ord(char))[2:].upper()
21 if len(hex_repr) == 1:
22 hex_repr = "0%s" % hex_repr
23 return "%" + hex_repr
Jeremy Hylton6102e292000-08-31 15:48:10 +000024
Jeremy Hylton1afc1692008-06-18 20:49:58 +000025# Shortcut for testing FancyURLopener
26_urlopener = None
27def urlopen(url, data=None, proxies=None):
28 """urlopen(url [, data]) -> open file-like object"""
29 global _urlopener
30 if proxies is not None:
31 opener = urllib.request.FancyURLopener(proxies=proxies)
32 elif not _urlopener:
33 opener = urllib.request.FancyURLopener()
34 _urlopener = opener
35 else:
36 opener = _urlopener
37 if data is None:
38 return opener.open(url)
39 else:
40 return opener.open(url, data)
41
Senthil Kumarance260142011-11-01 01:35:17 +080042
43class FakeHTTPMixin(object):
44 def fakehttp(self, fakedata):
45 class FakeSocket(io.BytesIO):
46 io_refs = 1
47
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080048 def sendall(self, data):
49 FakeHTTPConnection.buf = data
Senthil Kumarance260142011-11-01 01:35:17 +080050
51 def makefile(self, *args, **kwds):
52 self.io_refs += 1
53 return self
54
55 def read(self, amt=None):
56 if self.closed:
57 return b""
58 return io.BytesIO.read(self, amt)
59
60 def readline(self, length=None):
61 if self.closed:
62 return b""
63 return io.BytesIO.readline(self, length)
64
65 def close(self):
66 self.io_refs -= 1
67 if self.io_refs == 0:
68 io.BytesIO.close(self)
69
70 class FakeHTTPConnection(http.client.HTTPConnection):
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080071
72 # buffer to store data for verification in urlopen tests.
73 buf = None
74
Senthil Kumarance260142011-11-01 01:35:17 +080075 def connect(self):
76 self.sock = FakeSocket(fakedata)
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080077
Senthil Kumarance260142011-11-01 01:35:17 +080078 self._connection_class = http.client.HTTPConnection
79 http.client.HTTPConnection = FakeHTTPConnection
80
81 def unfakehttp(self):
82 http.client.HTTPConnection = self._connection_class
83
84
Brett Cannon74bfd702003-04-25 09:39:47 +000085class urlopen_FileTests(unittest.TestCase):
86 """Test urlopen() opening a temporary file.
Jeremy Hylton6102e292000-08-31 15:48:10 +000087
Brett Cannon74bfd702003-04-25 09:39:47 +000088 Try to test as much functionality as possible so as to cut down on reliance
Andrew M. Kuchlingf1a2f9e2004-06-29 13:07:53 +000089 on connecting to the Net for testing.
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000090
Brett Cannon74bfd702003-04-25 09:39:47 +000091 """
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000092
Brett Cannon74bfd702003-04-25 09:39:47 +000093 def setUp(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000094 # Create a temp file to use for testing
95 self.text = bytes("test_urllib: %s\n" % self.__class__.__name__,
96 "ascii")
97 f = open(support.TESTFN, 'wb')
Brett Cannon74bfd702003-04-25 09:39:47 +000098 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +000099 f.write(self.text)
Brett Cannon74bfd702003-04-25 09:39:47 +0000100 finally:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000101 f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000102 self.pathname = support.TESTFN
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000103 self.returned_obj = urlopen("file:%s" % self.pathname)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +0000104
Brett Cannon74bfd702003-04-25 09:39:47 +0000105 def tearDown(self):
106 """Shut down the open object"""
107 self.returned_obj.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000108 os.remove(support.TESTFN)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +0000109
Brett Cannon74bfd702003-04-25 09:39:47 +0000110 def test_interface(self):
111 # Make sure object returned by urlopen() has the specified methods
112 for attr in ("read", "readline", "readlines", "fileno",
Christian Heimes9bd667a2008-01-20 15:14:11 +0000113 "close", "info", "geturl", "getcode", "__iter__"):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000114 self.assertTrue(hasattr(self.returned_obj, attr),
Brett Cannon74bfd702003-04-25 09:39:47 +0000115 "object returned by urlopen() lacks %s attribute" %
116 attr)
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000117
Brett Cannon74bfd702003-04-25 09:39:47 +0000118 def test_read(self):
119 self.assertEqual(self.text, self.returned_obj.read())
Skip Montanaro080c9972001-01-28 21:12:22 +0000120
Brett Cannon74bfd702003-04-25 09:39:47 +0000121 def test_readline(self):
122 self.assertEqual(self.text, self.returned_obj.readline())
Guido van Rossuma0982942007-07-10 08:30:03 +0000123 self.assertEqual(b'', self.returned_obj.readline(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000124 "calling readline() after exhausting the file did not"
125 " return an empty string")
Skip Montanaro080c9972001-01-28 21:12:22 +0000126
Brett Cannon74bfd702003-04-25 09:39:47 +0000127 def test_readlines(self):
128 lines_list = self.returned_obj.readlines()
129 self.assertEqual(len(lines_list), 1,
130 "readlines() returned the wrong number of lines")
131 self.assertEqual(lines_list[0], self.text,
132 "readlines() returned improper text")
Skip Montanaro080c9972001-01-28 21:12:22 +0000133
Brett Cannon74bfd702003-04-25 09:39:47 +0000134 def test_fileno(self):
135 file_num = self.returned_obj.fileno()
Ezio Melottie9615932010-01-24 19:26:24 +0000136 self.assertIsInstance(file_num, int, "fileno() did not return an int")
Brett Cannon74bfd702003-04-25 09:39:47 +0000137 self.assertEqual(os.read(file_num, len(self.text)), self.text,
138 "Reading on the file descriptor returned by fileno() "
139 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000140
Brett Cannon74bfd702003-04-25 09:39:47 +0000141 def test_close(self):
Senthil Kumarand91ffca2011-03-19 17:25:27 +0800142 # Test close() by calling it here and then having it be called again
Brett Cannon74bfd702003-04-25 09:39:47 +0000143 # by the tearDown() method for the test
144 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +0000145
Brett Cannon74bfd702003-04-25 09:39:47 +0000146 def test_info(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000147 self.assertIsInstance(self.returned_obj.info(), email.message.Message)
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000148
Brett Cannon74bfd702003-04-25 09:39:47 +0000149 def test_geturl(self):
150 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +0000151
Christian Heimes9bd667a2008-01-20 15:14:11 +0000152 def test_getcode(self):
Florent Xicluna419e3842010-08-08 16:16:07 +0000153 self.assertIsNone(self.returned_obj.getcode())
Christian Heimes9bd667a2008-01-20 15:14:11 +0000154
Brett Cannon74bfd702003-04-25 09:39:47 +0000155 def test_iter(self):
156 # Test iterator
157 # Don't need to count number of iterations since test would fail the
158 # instant it returned anything beyond the first line from the
Raymond Hettinger038018a2011-06-26 14:29:35 +0200159 # comparison.
160 # Use the iterator in the usual implicit way to test for ticket #4608.
161 for line in self.returned_obj:
Brett Cannon74bfd702003-04-25 09:39:47 +0000162 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +0000163
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800164 def test_relativelocalfile(self):
165 self.assertRaises(ValueError,urllib.request.urlopen,'./' + self.pathname)
166
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000167class ProxyTests(unittest.TestCase):
168
169 def setUp(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +0000170 # Records changes to env vars
171 self.env = support.EnvironmentVarGuard()
Benjamin Peterson46a99002010-01-09 18:45:30 +0000172 # Delete all proxy related env vars
Antoine Pitroub3a88b52010-10-14 18:31:39 +0000173 for k in list(os.environ):
Antoine Pitrou8c8f1ac2010-10-14 18:32:54 +0000174 if 'proxy' in k.lower():
Benjamin Peterson46a99002010-01-09 18:45:30 +0000175 self.env.unset(k)
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000176
177 def tearDown(self):
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000178 # Restore all proxy related env vars
Walter Dörwaldb525e182009-04-26 21:39:21 +0000179 self.env.__exit__()
180 del self.env
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000181
182 def test_getproxies_environment_keep_no_proxies(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +0000183 self.env.set('NO_PROXY', 'localhost')
184 proxies = urllib.request.getproxies_environment()
185 # getproxies_environment use lowered case truncated (no '_proxy') keys
Florent Xicluna419e3842010-08-08 16:16:07 +0000186 self.assertEqual('localhost', proxies['no'])
Senthil Kumaran89976f12011-08-06 12:27:40 +0800187 # List of no_proxies with space.
188 self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com')
189 self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com'))
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000190
Senthil Kumarance260142011-11-01 01:35:17 +0800191class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000192 """Test urlopen() opening a fake http connection."""
193
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000194 def check_read(self, ver):
195 self.fakehttp(b"HTTP/" + ver + b" 200 OK\r\n\r\nHello!")
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000196 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000197 fp = urlopen("http://python.org/")
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000198 self.assertEqual(fp.readline(), b"Hello!")
199 self.assertEqual(fp.readline(), b"")
Christian Heimes9bd667a2008-01-20 15:14:11 +0000200 self.assertEqual(fp.geturl(), 'http://python.org/')
201 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000202 finally:
203 self.unfakehttp()
204
Senthil Kumaran26430412011-04-13 07:01:19 +0800205 def test_url_fragment(self):
206 # Issue #11703: geturl() omits fragments in the original URL.
207 url = 'http://docs.python.org/library/urllib.html#OK'
Senthil Kumaranb17abb12011-04-13 07:22:29 +0800208 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
Senthil Kumaran26430412011-04-13 07:01:19 +0800209 try:
210 fp = urllib.request.urlopen(url)
211 self.assertEqual(fp.geturl(), url)
212 finally:
213 self.unfakehttp()
214
Senthil Kumarand91ffca2011-03-19 17:25:27 +0800215 def test_willclose(self):
216 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
Senthil Kumaranacbaa922011-03-20 05:30:16 +0800217 try:
218 resp = urlopen("http://www.python.org")
219 self.assertTrue(resp.fp.will_close)
220 finally:
221 self.unfakehttp()
Senthil Kumarand91ffca2011-03-19 17:25:27 +0800222
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000223 def test_read_0_9(self):
224 # "0.9" response accepted (but not "simple responses" without
225 # a status line)
226 self.check_read(b"0.9")
227
228 def test_read_1_0(self):
229 self.check_read(b"1.0")
230
231 def test_read_1_1(self):
232 self.check_read(b"1.1")
233
Christian Heimes57dddfb2008-01-02 18:30:52 +0000234 def test_read_bogus(self):
235 # urlopen() should raise IOError for many error codes.
236 self.fakehttp(b'''HTTP/1.1 401 Authentication Required
237Date: Wed, 02 Jan 2008 03:03:54 GMT
238Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
239Connection: close
240Content-Type: text/html; charset=iso-8859-1
241''')
242 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000243 self.assertRaises(IOError, urlopen, "http://python.org/")
Christian Heimes57dddfb2008-01-02 18:30:52 +0000244 finally:
245 self.unfakehttp()
246
guido@google.coma119df92011-03-29 11:41:02 -0700247 def test_invalid_redirect(self):
248 # urlopen() should raise IOError for many error codes.
249 self.fakehttp(b'''HTTP/1.1 302 Found
250Date: Wed, 02 Jan 2008 03:03:54 GMT
251Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
252Location: file://guidocomputer.athome.com:/python/license
253Connection: close
254Content-Type: text/html; charset=iso-8859-1
255''')
256 try:
257 self.assertRaises(urllib.error.HTTPError, urlopen,
258 "http://python.org/")
259 finally:
260 self.unfakehttp()
261
Guido van Rossumd8faa362007-04-27 19:54:29 +0000262 def test_empty_socket(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000263 # urlopen() raises IOError if the underlying socket does not send any
264 # data. (#1680230)
Christian Heimes57dddfb2008-01-02 18:30:52 +0000265 self.fakehttp(b'')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000266 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000267 self.assertRaises(IOError, urlopen, "http://something")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000268 finally:
269 self.unfakehttp()
270
Senthil Kumarancad7b312012-10-27 02:26:46 -0700271 def test_missing_localfile(self):
272 # Test for #10836
Senthil Kumarancc2f0422012-10-27 02:48:21 -0700273 # 3.3 - URLError is not captured, explicit IOError is raised.
274 with self.assertRaises(IOError):
Senthil Kumarancad7b312012-10-27 02:26:46 -0700275 urlopen('file://localhost/a/file/which/doesnot/exists.py')
Senthil Kumarancad7b312012-10-27 02:26:46 -0700276
277 def test_file_notexists(self):
278 fd, tmp_file = tempfile.mkstemp()
279 tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/')
280 try:
281 self.assertTrue(os.path.exists(tmp_file))
282 with urlopen(tmp_fileurl) as fobj:
283 self.assertTrue(fobj)
284 finally:
285 os.close(fd)
286 os.unlink(tmp_file)
287 self.assertFalse(os.path.exists(tmp_file))
Senthil Kumarancc2f0422012-10-27 02:48:21 -0700288 # 3.3 - IOError instead of URLError
289 with self.assertRaises(IOError):
Senthil Kumarancad7b312012-10-27 02:26:46 -0700290 urlopen(tmp_fileurl)
291
292 def test_ftp_nohost(self):
293 test_ftp_url = 'ftp:///path'
Senthil Kumarancc2f0422012-10-27 02:48:21 -0700294 # 3.3 - IOError instead of URLError
295 with self.assertRaises(IOError):
Senthil Kumarancad7b312012-10-27 02:26:46 -0700296 urlopen(test_ftp_url)
Senthil Kumarancad7b312012-10-27 02:26:46 -0700297
298 def test_ftp_nonexisting(self):
Senthil Kumarancc2f0422012-10-27 02:48:21 -0700299 # 3.3 - IOError instead of URLError
300 with self.assertRaises(IOError):
Senthil Kumarancad7b312012-10-27 02:26:46 -0700301 urlopen('ftp://localhost/a/file/which/doesnot/exists.py')
Senthil Kumarancad7b312012-10-27 02:26:46 -0700302
303
Senthil Kumarande0eb242010-08-01 17:53:37 +0000304 def test_userpass_inurl(self):
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000305 self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
Senthil Kumarande0eb242010-08-01 17:53:37 +0000306 try:
307 fp = urlopen("http://user:pass@python.org/")
308 self.assertEqual(fp.readline(), b"Hello!")
309 self.assertEqual(fp.readline(), b"")
310 self.assertEqual(fp.geturl(), 'http://user:pass@python.org/')
311 self.assertEqual(fp.getcode(), 200)
312 finally:
313 self.unfakehttp()
314
Senthil Kumaranc5c5a142012-01-14 19:09:04 +0800315 def test_userpass_inurl_w_spaces(self):
316 self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
317 try:
318 userpass = "a b:c d"
319 url = "http://{}@python.org/".format(userpass)
320 fakehttp_wrapper = http.client.HTTPConnection
321 authorization = ("Authorization: Basic %s\r\n" %
322 b64encode(userpass.encode("ASCII")).decode("ASCII"))
323 fp = urlopen(url)
324 # The authorization header must be in place
325 self.assertIn(authorization, fakehttp_wrapper.buf.decode("UTF-8"))
326 self.assertEqual(fp.readline(), b"Hello!")
327 self.assertEqual(fp.readline(), b"")
328 # the spaces are quoted in URL so no match
329 self.assertNotEqual(fp.geturl(), url)
330 self.assertEqual(fp.getcode(), 200)
331 finally:
332 self.unfakehttp()
333
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700334 def test_URLopener_deprecation(self):
335 with support.check_warnings(('',DeprecationWarning)):
Senthil Kumarancc2f0422012-10-27 02:48:21 -0700336 urllib.request.URLopener()
Senthil Kumaran38b968b92012-03-14 13:43:53 -0700337
Brett Cannon19691362003-04-29 05:08:06 +0000338class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000339 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000340
Brett Cannon19691362003-04-29 05:08:06 +0000341 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000342 # Create a list of temporary files. Each item in the list is a file
343 # name (absolute path or relative to the current working directory).
344 # All files in this list will be deleted in the tearDown method. Note,
345 # this only helps to makes sure temporary files get deleted, but it
346 # does nothing about trying to close files that may still be open. It
347 # is the responsibility of the developer to properly close files even
348 # when exceptional conditions occur.
349 self.tempFiles = []
350
Brett Cannon19691362003-04-29 05:08:06 +0000351 # Create a temporary file.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000352 self.registerFileForCleanUp(support.TESTFN)
Guido van Rossuma0982942007-07-10 08:30:03 +0000353 self.text = b'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000354 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000355 FILE = open(support.TESTFN, 'wb')
Georg Brandl5a650a22005-08-26 08:51:34 +0000356 FILE.write(self.text)
357 FILE.close()
358 finally:
359 try: FILE.close()
360 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000361
362 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000363 # Delete the temporary files.
364 for each in self.tempFiles:
365 try: os.remove(each)
366 except: pass
367
368 def constructLocalFileUrl(self, filePath):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000369 filePath = os.path.abspath(filePath)
370 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000371 filePath.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000372 except UnicodeEncodeError:
373 raise unittest.SkipTest("filePath is not encodable to utf8")
374 return "file://%s" % urllib.request.pathname2url(filePath)
Georg Brandl5a650a22005-08-26 08:51:34 +0000375
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000376 def createNewTempFile(self, data=b""):
Georg Brandl5a650a22005-08-26 08:51:34 +0000377 """Creates a new temporary file containing the specified data,
378 registers the file for deletion during the test fixture tear down, and
379 returns the absolute path of the file."""
380
381 newFd, newFilePath = tempfile.mkstemp()
382 try:
383 self.registerFileForCleanUp(newFilePath)
384 newFile = os.fdopen(newFd, "wb")
385 newFile.write(data)
386 newFile.close()
387 finally:
388 try: newFile.close()
389 except: pass
390 return newFilePath
391
392 def registerFileForCleanUp(self, fileName):
393 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000394
395 def test_basic(self):
396 # Make sure that a local file just gets its own location returned and
397 # a headers value is returned.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000398 result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000399 self.assertEqual(result[0], support.TESTFN)
Ezio Melottie9615932010-01-24 19:26:24 +0000400 self.assertIsInstance(result[1], email.message.Message,
401 "did not get a email.message.Message instance "
402 "as second returned value")
Brett Cannon19691362003-04-29 05:08:06 +0000403
404 def test_copy(self):
405 # Test that setting the filename argument works.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000406 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000407 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000408 result = urllib.request.urlretrieve(self.constructLocalFileUrl(
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000409 support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000410 self.assertEqual(second_temp, result[0])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000411 self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
Brett Cannon19691362003-04-29 05:08:06 +0000412 "made")
Alex Martelli01c77c62006-08-24 02:58:11 +0000413 FILE = open(second_temp, 'rb')
Brett Cannon19691362003-04-29 05:08:06 +0000414 try:
415 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000416 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000417 finally:
418 try: FILE.close()
419 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000420 self.assertEqual(self.text, text)
421
422 def test_reporthook(self):
423 # Make sure that the reporthook works.
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700424 def hooktester(block_count, block_read_size, file_size, count_holder=[0]):
425 self.assertIsInstance(block_count, int)
426 self.assertIsInstance(block_read_size, int)
427 self.assertIsInstance(file_size, int)
428 self.assertEqual(block_count, count_holder[0])
Brett Cannon19691362003-04-29 05:08:06 +0000429 count_holder[0] = count_holder[0] + 1
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000430 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000431 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000432 urllib.request.urlretrieve(
433 self.constructLocalFileUrl(support.TESTFN),
Georg Brandl5a650a22005-08-26 08:51:34 +0000434 second_temp, hooktester)
435
436 def test_reporthook_0_bytes(self):
437 # Test on zero length file. Should call reporthook only 1 time.
438 report = []
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700439 def hooktester(block_count, block_read_size, file_size, _report=report):
440 _report.append((block_count, block_read_size, file_size))
Georg Brandl5a650a22005-08-26 08:51:34 +0000441 srcFileName = self.createNewTempFile()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000442 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000443 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000444 self.assertEqual(len(report), 1)
445 self.assertEqual(report[0][2], 0)
446
447 def test_reporthook_5_bytes(self):
448 # Test on 5 byte file. Should call reporthook only 2 times (once when
449 # the "network connection" is established and once when the block is
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700450 # read).
Georg Brandl5a650a22005-08-26 08:51:34 +0000451 report = []
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700452 def hooktester(block_count, block_read_size, file_size, _report=report):
453 _report.append((block_count, block_read_size, file_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000454 srcFileName = self.createNewTempFile(b"x" * 5)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000455 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000456 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000457 self.assertEqual(len(report), 2)
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700458 self.assertEqual(report[0][1], 0)
459 self.assertEqual(report[1][1], 5)
Georg Brandl5a650a22005-08-26 08:51:34 +0000460
461 def test_reporthook_8193_bytes(self):
462 # Test on 8193 byte file. Should call reporthook only 3 times (once
463 # when the "network connection" is established, once for the next 8192
464 # bytes, and once for the last byte).
465 report = []
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700466 def hooktester(block_count, block_read_size, file_size, _report=report):
467 _report.append((block_count, block_read_size, file_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000468 srcFileName = self.createNewTempFile(b"x" * 8193)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000469 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000470 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000471 self.assertEqual(len(report), 3)
Senthil Kumarane24f96a2012-03-13 19:29:33 -0700472 self.assertEqual(report[0][1], 0)
473 self.assertEqual(report[1][1], 8192)
474 self.assertEqual(report[2][1], 1)
Skip Montanaro080c9972001-01-28 21:12:22 +0000475
Senthil Kumarance260142011-11-01 01:35:17 +0800476
477class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin):
478 """Test urllib.urlretrieve() using fake http connections"""
479
480 def test_short_content_raises_ContentTooShortError(self):
481 self.fakehttp(b'''HTTP/1.1 200 OK
482Date: Wed, 02 Jan 2008 03:03:54 GMT
483Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
484Connection: close
485Content-Length: 100
486Content-Type: text/html; charset=iso-8859-1
487
488FF
489''')
490
491 def _reporthook(par1, par2, par3):
492 pass
493
494 with self.assertRaises(urllib.error.ContentTooShortError):
495 try:
496 urllib.request.urlretrieve('http://example.com/',
497 reporthook=_reporthook)
498 finally:
499 self.unfakehttp()
500
501 def test_short_content_raises_ContentTooShortError_without_reporthook(self):
502 self.fakehttp(b'''HTTP/1.1 200 OK
503Date: Wed, 02 Jan 2008 03:03:54 GMT
504Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
505Connection: close
506Content-Length: 100
507Content-Type: text/html; charset=iso-8859-1
508
509FF
510''')
511 with self.assertRaises(urllib.error.ContentTooShortError):
512 try:
513 urllib.request.urlretrieve('http://example.com/')
514 finally:
515 self.unfakehttp()
516
517
Brett Cannon74bfd702003-04-25 09:39:47 +0000518class QuotingTests(unittest.TestCase):
519 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000520
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000521 According to RFC 2396 (Uniform Resource Identifiers), to escape a
522 character you write it as '%' + <2 character US-ASCII hex value>.
523 The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
524 character properly. Case does not matter on the hex letters.
Brett Cannon74bfd702003-04-25 09:39:47 +0000525
526 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000527
Brett Cannon74bfd702003-04-25 09:39:47 +0000528 Reserved characters : ";/?:@&=+$,"
529 Have special meaning in URIs and must be escaped if not being used for
530 their special meaning
531 Data characters : letters, digits, and "-_.!~*'()"
532 Unreserved and do not need to be escaped; can be, though, if desired
533 Control characters : 0x00 - 0x1F, 0x7F
534 Have no use in URIs so must be escaped
535 space : 0x20
536 Must be escaped
537 Delimiters : '<>#%"'
538 Must be escaped
539 Unwise : "{}|\^[]`"
540 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000541
Brett Cannon74bfd702003-04-25 09:39:47 +0000542 """
543
544 def test_never_quote(self):
545 # Make sure quote() does not quote letters, digits, and "_,.-"
546 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
547 "abcdefghijklmnopqrstuvwxyz",
548 "0123456789",
549 "_.-"])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000550 result = urllib.parse.quote(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000551 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000552 "using quote(): %r != %r" % (do_not_quote, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000553 result = urllib.parse.quote_plus(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000554 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000555 "using quote_plus(): %r != %r" % (do_not_quote, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000556
557 def test_default_safe(self):
558 # Test '/' is default value for 'safe' parameter
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000559 self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
Brett Cannon74bfd702003-04-25 09:39:47 +0000560
561 def test_safe(self):
562 # Test setting 'safe' parameter does what it should do
563 quote_by_default = "<>"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000564 result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000565 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000566 "using quote(): %r != %r" % (quote_by_default, result))
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000567 result = urllib.parse.quote_plus(quote_by_default,
568 safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000569 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000570 "using quote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000571 (quote_by_default, result))
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000572 # Safe expressed as bytes rather than str
573 result = urllib.parse.quote(quote_by_default, safe=b"<>")
574 self.assertEqual(quote_by_default, result,
575 "using quote(): %r != %r" % (quote_by_default, result))
576 # "Safe" non-ASCII characters should have no effect
577 # (Since URIs are not allowed to have non-ASCII characters)
578 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc")
579 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
580 self.assertEqual(expect, result,
581 "using quote(): %r != %r" %
582 (expect, result))
583 # Same as above, but using a bytes rather than str
584 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc")
585 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
586 self.assertEqual(expect, result,
587 "using quote(): %r != %r" %
588 (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000589
590 def test_default_quoting(self):
591 # Make sure all characters that should be quoted are by default sans
592 # space (separate test for that).
593 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
594 should_quote.append('<>#%"{}|\^[]`')
595 should_quote.append(chr(127)) # For 0x7F
596 should_quote = ''.join(should_quote)
597 for char in should_quote:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000598 result = urllib.parse.quote(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000599 self.assertEqual(hexescape(char), result,
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000600 "using quote(): "
601 "%s should be escaped to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000602 (char, hexescape(char), result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000603 result = urllib.parse.quote_plus(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000604 self.assertEqual(hexescape(char), result,
605 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000606 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000607 (char, hexescape(char), result))
608 del should_quote
609 partial_quote = "ab[]cd"
610 expected = "ab%5B%5Dcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000611 result = urllib.parse.quote(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000612 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000613 "using quote(): %r != %r" % (expected, result))
Senthil Kumaran305a68e2011-09-13 06:40:27 +0800614 result = urllib.parse.quote_plus(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000615 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000616 "using quote_plus(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000617
618 def test_quoting_space(self):
619 # Make sure quote() and quote_plus() handle spaces as specified in
620 # their unique way
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000621 result = urllib.parse.quote(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000622 self.assertEqual(result, hexescape(' '),
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000623 "using quote(): %r != %r" % (result, hexescape(' ')))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000624 result = urllib.parse.quote_plus(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000625 self.assertEqual(result, '+',
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000626 "using quote_plus(): %r != +" % result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000627 given = "a b cd e f"
628 expect = given.replace(' ', hexescape(' '))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000629 result = urllib.parse.quote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000630 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000631 "using quote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000632 expect = given.replace(' ', '+')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000633 result = urllib.parse.quote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000634 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000635 "using quote_plus(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000636
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000637 def test_quoting_plus(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000638 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000639 'alpha%2Bbeta+gamma')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000640 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000641 'alpha+beta+gamma')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000642 # Test with bytes
643 self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
644 'alpha%2Bbeta+gamma')
645 # Test with safe bytes
646 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
647 'alpha+beta+gamma')
648
649 def test_quote_bytes(self):
650 # Bytes should quote directly to percent-encoded values
651 given = b"\xa2\xd8ab\xff"
652 expect = "%A2%D8ab%FF"
653 result = urllib.parse.quote(given)
654 self.assertEqual(expect, result,
655 "using quote(): %r != %r" % (expect, result))
656 # Encoding argument should raise type error on bytes input
657 self.assertRaises(TypeError, urllib.parse.quote, given,
658 encoding="latin-1")
659 # quote_from_bytes should work the same
660 result = urllib.parse.quote_from_bytes(given)
661 self.assertEqual(expect, result,
662 "using quote_from_bytes(): %r != %r"
663 % (expect, result))
664
665 def test_quote_with_unicode(self):
666 # Characters in Latin-1 range, encoded by default in UTF-8
667 given = "\xa2\xd8ab\xff"
668 expect = "%C2%A2%C3%98ab%C3%BF"
669 result = urllib.parse.quote(given)
670 self.assertEqual(expect, result,
671 "using quote(): %r != %r" % (expect, result))
672 # Characters in Latin-1 range, encoded by with None (default)
673 result = urllib.parse.quote(given, encoding=None, errors=None)
674 self.assertEqual(expect, result,
675 "using quote(): %r != %r" % (expect, result))
676 # Characters in Latin-1 range, encoded with Latin-1
677 given = "\xa2\xd8ab\xff"
678 expect = "%A2%D8ab%FF"
679 result = urllib.parse.quote(given, encoding="latin-1")
680 self.assertEqual(expect, result,
681 "using quote(): %r != %r" % (expect, result))
682 # Characters in BMP, encoded by default in UTF-8
683 given = "\u6f22\u5b57" # "Kanji"
684 expect = "%E6%BC%A2%E5%AD%97"
685 result = urllib.parse.quote(given)
686 self.assertEqual(expect, result,
687 "using quote(): %r != %r" % (expect, result))
688 # Characters in BMP, encoded with Latin-1
689 given = "\u6f22\u5b57"
690 self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
691 encoding="latin-1")
692 # Characters in BMP, encoded with Latin-1, with replace error handling
693 given = "\u6f22\u5b57"
694 expect = "%3F%3F" # "??"
695 result = urllib.parse.quote(given, encoding="latin-1",
696 errors="replace")
697 self.assertEqual(expect, result,
698 "using quote(): %r != %r" % (expect, result))
699 # Characters in BMP, Latin-1, with xmlcharref error handling
700 given = "\u6f22\u5b57"
701 expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;"
702 result = urllib.parse.quote(given, encoding="latin-1",
703 errors="xmlcharrefreplace")
704 self.assertEqual(expect, result,
705 "using quote(): %r != %r" % (expect, result))
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000706
Georg Brandlfaf41492009-05-26 18:31:11 +0000707 def test_quote_plus_with_unicode(self):
708 # Encoding (latin-1) test for quote_plus
709 given = "\xa2\xd8 \xff"
710 expect = "%A2%D8+%FF"
711 result = urllib.parse.quote_plus(given, encoding="latin-1")
712 self.assertEqual(expect, result,
713 "using quote_plus(): %r != %r" % (expect, result))
714 # Errors test for quote_plus
715 given = "ab\u6f22\u5b57 cd"
716 expect = "ab%3F%3F+cd"
717 result = urllib.parse.quote_plus(given, encoding="latin-1",
718 errors="replace")
719 self.assertEqual(expect, result,
720 "using quote_plus(): %r != %r" % (expect, result))
721
Senthil Kumarand496c4c2010-07-30 19:34:36 +0000722
Brett Cannon74bfd702003-04-25 09:39:47 +0000723class UnquotingTests(unittest.TestCase):
724 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000725
Brett Cannon74bfd702003-04-25 09:39:47 +0000726 See the doc string for quoting_Tests for details on quoting and such.
727
728 """
729
730 def test_unquoting(self):
731 # Make sure unquoting of all ASCII values works
732 escape_list = []
733 for num in range(128):
734 given = hexescape(chr(num))
735 expect = chr(num)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000736 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000737 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000738 "using unquote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000739 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000740 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000741 "using unquote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000742 (expect, result))
743 escape_list.append(given)
744 escape_string = ''.join(escape_list)
745 del escape_list
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000746 result = urllib.parse.unquote(escape_string)
Brett Cannon74bfd702003-04-25 09:39:47 +0000747 self.assertEqual(result.count('%'), 1,
Brett Cannon74bfd702003-04-25 09:39:47 +0000748 "using unquote(): not all characters escaped: "
749 "%s" % result)
Georg Brandl604ef372010-07-31 08:20:02 +0000750 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
751 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
Florent Xicluna62829dc2010-08-14 20:51:58 +0000752 with support.check_warnings(('', BytesWarning), quiet=True):
753 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, b'')
Brett Cannon74bfd702003-04-25 09:39:47 +0000754
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000755 def test_unquoting_badpercent(self):
756 # Test unquoting on bad percent-escapes
757 given = '%xab'
758 expect = given
759 result = urllib.parse.unquote(given)
760 self.assertEqual(expect, result, "using unquote(): %r != %r"
761 % (expect, result))
762 given = '%x'
763 expect = given
764 result = urllib.parse.unquote(given)
765 self.assertEqual(expect, result, "using unquote(): %r != %r"
766 % (expect, result))
767 given = '%'
768 expect = given
769 result = urllib.parse.unquote(given)
770 self.assertEqual(expect, result, "using unquote(): %r != %r"
771 % (expect, result))
772 # unquote_to_bytes
773 given = '%xab'
774 expect = bytes(given, 'ascii')
775 result = urllib.parse.unquote_to_bytes(given)
776 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
777 % (expect, result))
778 given = '%x'
779 expect = bytes(given, 'ascii')
780 result = urllib.parse.unquote_to_bytes(given)
781 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
782 % (expect, result))
783 given = '%'
784 expect = bytes(given, 'ascii')
785 result = urllib.parse.unquote_to_bytes(given)
786 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
787 % (expect, result))
Georg Brandl604ef372010-07-31 08:20:02 +0000788 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None)
789 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ())
Senthil Kumaran79e17f62010-07-19 18:17:19 +0000790
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000791 def test_unquoting_mixed_case(self):
792 # Test unquoting on mixed-case hex digits in the percent-escapes
793 given = '%Ab%eA'
794 expect = b'\xab\xea'
795 result = urllib.parse.unquote_to_bytes(given)
796 self.assertEqual(expect, result,
797 "using unquote_to_bytes(): %r != %r"
798 % (expect, result))
799
Brett Cannon74bfd702003-04-25 09:39:47 +0000800 def test_unquoting_parts(self):
801 # Make sure unquoting works when have non-quoted characters
802 # interspersed
803 given = 'ab%sd' % hexescape('c')
804 expect = "abcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000805 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000806 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000807 "using quote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000808 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000809 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000810 "using unquote_plus(): %r != %r" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000811
Brett Cannon74bfd702003-04-25 09:39:47 +0000812 def test_unquoting_plus(self):
813 # Test difference between unquote() and unquote_plus()
814 given = "are+there+spaces..."
815 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000816 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000817 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000818 "using unquote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000819 expect = given.replace('+', ' ')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000820 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000821 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000822 "using unquote_plus(): %r != %r" % (expect, result))
823
824 def test_unquote_to_bytes(self):
825 given = 'br%C3%BCckner_sapporo_20050930.doc'
826 expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
827 result = urllib.parse.unquote_to_bytes(given)
828 self.assertEqual(expect, result,
829 "using unquote_to_bytes(): %r != %r"
830 % (expect, result))
831 # Test on a string with unescaped non-ASCII characters
832 # (Technically an invalid URI; expect those characters to be UTF-8
833 # encoded).
834 result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
835 expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
836 self.assertEqual(expect, result,
837 "using unquote_to_bytes(): %r != %r"
838 % (expect, result))
839 # Test with a bytes as input
840 given = b'%A2%D8ab%FF'
841 expect = b'\xa2\xd8ab\xff'
842 result = urllib.parse.unquote_to_bytes(given)
843 self.assertEqual(expect, result,
844 "using unquote_to_bytes(): %r != %r"
845 % (expect, result))
846 # Test with a bytes as input, with unescaped non-ASCII bytes
847 # (Technically an invalid URI; expect those bytes to be preserved)
848 given = b'%A2\xd8ab%FF'
849 expect = b'\xa2\xd8ab\xff'
850 result = urllib.parse.unquote_to_bytes(given)
851 self.assertEqual(expect, result,
852 "using unquote_to_bytes(): %r != %r"
853 % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000854
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000855 def test_unquote_with_unicode(self):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000856 # Characters in the Latin-1 range, encoded with UTF-8
857 given = 'br%C3%BCckner_sapporo_20050930.doc'
858 expect = 'br\u00fcckner_sapporo_20050930.doc'
859 result = urllib.parse.unquote(given)
860 self.assertEqual(expect, result,
861 "using unquote(): %r != %r" % (expect, result))
862 # Characters in the Latin-1 range, encoded with None (default)
863 result = urllib.parse.unquote(given, encoding=None, errors=None)
864 self.assertEqual(expect, result,
865 "using unquote(): %r != %r" % (expect, result))
866
867 # Characters in the Latin-1 range, encoded with Latin-1
868 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
869 encoding="latin-1")
870 expect = 'br\u00fcckner_sapporo_20050930.doc'
871 self.assertEqual(expect, result,
872 "using unquote(): %r != %r" % (expect, result))
873
874 # Characters in BMP, encoded with UTF-8
875 given = "%E6%BC%A2%E5%AD%97"
876 expect = "\u6f22\u5b57" # "Kanji"
877 result = urllib.parse.unquote(given)
878 self.assertEqual(expect, result,
879 "using unquote(): %r != %r" % (expect, result))
880
881 # Decode with UTF-8, invalid sequence
882 given = "%F3%B1"
883 expect = "\ufffd" # Replacement character
884 result = urllib.parse.unquote(given)
885 self.assertEqual(expect, result,
886 "using unquote(): %r != %r" % (expect, result))
887
888 # Decode with UTF-8, invalid sequence, replace errors
889 result = urllib.parse.unquote(given, errors="replace")
890 self.assertEqual(expect, result,
891 "using unquote(): %r != %r" % (expect, result))
892
893 # Decode with UTF-8, invalid sequence, ignoring errors
894 given = "%F3%B1"
895 expect = ""
896 result = urllib.parse.unquote(given, errors="ignore")
897 self.assertEqual(expect, result,
898 "using unquote(): %r != %r" % (expect, result))
899
900 # A mix of non-ASCII and percent-encoded characters, UTF-8
901 result = urllib.parse.unquote("\u6f22%C3%BC")
902 expect = '\u6f22\u00fc'
903 self.assertEqual(expect, result,
904 "using unquote(): %r != %r" % (expect, result))
905
906 # A mix of non-ASCII and percent-encoded characters, Latin-1
907 # (Note, the string contains non-Latin-1-representable characters)
908 result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
909 expect = '\u6f22\u00fc'
910 self.assertEqual(expect, result,
911 "using unquote(): %r != %r" % (expect, result))
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000912
Brett Cannon74bfd702003-04-25 09:39:47 +0000913class urlencode_Tests(unittest.TestCase):
914 """Tests for urlencode()"""
915
916 def help_inputtype(self, given, test_type):
917 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000918
Brett Cannon74bfd702003-04-25 09:39:47 +0000919 'given' must lead to only the pairs:
920 * 1st, 1
921 * 2nd, 2
922 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000923
Brett Cannon74bfd702003-04-25 09:39:47 +0000924 Test cannot assume anything about order. Docs make no guarantee and
925 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000926
Brett Cannon74bfd702003-04-25 09:39:47 +0000927 """
928 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000929 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000930 for expected in expect_somewhere:
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000931 self.assertIn(expected, result,
Brett Cannon74bfd702003-04-25 09:39:47 +0000932 "testing %s: %s not found in %s" %
933 (test_type, expected, result))
934 self.assertEqual(result.count('&'), 2,
935 "testing %s: expected 2 '&'s; got %s" %
936 (test_type, result.count('&')))
937 amp_location = result.index('&')
938 on_amp_left = result[amp_location - 1]
939 on_amp_right = result[amp_location + 1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000940 self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000941 "testing %s: '&' not located in proper place in %s" %
942 (test_type, result))
943 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
944 "testing %s: "
945 "unexpected number of characters: %s != %s" %
946 (test_type, len(result), (5 * 3) + 2))
947
948 def test_using_mapping(self):
949 # Test passing in a mapping object as an argument.
950 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
951 "using dict as input type")
952
953 def test_using_sequence(self):
954 # Test passing in a sequence of two-item sequences as an argument.
955 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
956 "using sequence of two-item tuples as input")
957
958 def test_quoting(self):
959 # Make sure keys and values are quoted using quote_plus()
960 given = {"&":"="}
961 expect = "%s=%s" % (hexescape('&'), hexescape('='))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000962 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000963 self.assertEqual(expect, result)
964 given = {"key name":"A bunch of pluses"}
965 expect = "key+name=A+bunch+of+pluses"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000966 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000967 self.assertEqual(expect, result)
968
969 def test_doseq(self):
970 # Test that passing True for 'doseq' parameter works correctly
971 given = {'sequence':['1', '2', '3']}
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000972 expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
973 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000974 self.assertEqual(expect, result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000975 result = urllib.parse.urlencode(given, True)
Brett Cannon74bfd702003-04-25 09:39:47 +0000976 for value in given["sequence"]:
977 expect = "sequence=%s" % value
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000978 self.assertIn(expect, result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000979 self.assertEqual(result.count('&'), 2,
980 "Expected 2 '&'s, got %s" % result.count('&'))
981
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000982 def test_empty_sequence(self):
983 self.assertEqual("", urllib.parse.urlencode({}))
984 self.assertEqual("", urllib.parse.urlencode([]))
985
986 def test_nonstring_values(self):
987 self.assertEqual("a=1", urllib.parse.urlencode({"a": 1}))
988 self.assertEqual("a=None", urllib.parse.urlencode({"a": None}))
989
990 def test_nonstring_seq_values(self):
991 self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True))
992 self.assertEqual("a=None&a=a",
993 urllib.parse.urlencode({"a": [None, "a"]}, True))
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100994 data = collections.OrderedDict([("a", 1), ("b", 1)])
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000995 self.assertEqual("a=a&a=b",
Georg Brandl2daf6ae2012-02-20 19:54:16 +0100996 urllib.parse.urlencode({"a": data}, True))
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000997
Senthil Kumarandf022da2010-07-03 17:48:22 +0000998 def test_urlencode_encoding(self):
999 # ASCII encoding. Expect %3F with errors="replace'
1000 given = (('\u00a0', '\u00c1'),)
1001 expect = '%3F=%3F'
1002 result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
1003 self.assertEqual(expect, result)
1004
1005 # Default is UTF-8 encoding.
1006 given = (('\u00a0', '\u00c1'),)
1007 expect = '%C2%A0=%C3%81'
1008 result = urllib.parse.urlencode(given)
1009 self.assertEqual(expect, result)
1010
1011 # Latin-1 encoding.
1012 given = (('\u00a0', '\u00c1'),)
1013 expect = '%A0=%C1'
1014 result = urllib.parse.urlencode(given, encoding="latin-1")
1015 self.assertEqual(expect, result)
1016
1017 def test_urlencode_encoding_doseq(self):
1018 # ASCII Encoding. Expect %3F with errors="replace'
1019 given = (('\u00a0', '\u00c1'),)
1020 expect = '%3F=%3F'
1021 result = urllib.parse.urlencode(given, doseq=True,
1022 encoding="ASCII", errors="replace")
1023 self.assertEqual(expect, result)
1024
1025 # ASCII Encoding. On a sequence of values.
1026 given = (("\u00a0", (1, "\u00c1")),)
1027 expect = '%3F=1&%3F=%3F'
1028 result = urllib.parse.urlencode(given, True,
1029 encoding="ASCII", errors="replace")
1030 self.assertEqual(expect, result)
1031
1032 # Utf-8
1033 given = (("\u00a0", "\u00c1"),)
1034 expect = '%C2%A0=%C3%81'
1035 result = urllib.parse.urlencode(given, True)
1036 self.assertEqual(expect, result)
1037
1038 given = (("\u00a0", (42, "\u00c1")),)
1039 expect = '%C2%A0=42&%C2%A0=%C3%81'
1040 result = urllib.parse.urlencode(given, True)
1041 self.assertEqual(expect, result)
1042
1043 # latin-1
1044 given = (("\u00a0", "\u00c1"),)
1045 expect = '%A0=%C1'
1046 result = urllib.parse.urlencode(given, True, encoding="latin-1")
1047 self.assertEqual(expect, result)
1048
1049 given = (("\u00a0", (42, "\u00c1")),)
1050 expect = '%A0=42&%A0=%C1'
1051 result = urllib.parse.urlencode(given, True, encoding="latin-1")
1052 self.assertEqual(expect, result)
1053
1054 def test_urlencode_bytes(self):
1055 given = ((b'\xa0\x24', b'\xc1\x24'),)
1056 expect = '%A0%24=%C1%24'
1057 result = urllib.parse.urlencode(given)
1058 self.assertEqual(expect, result)
1059 result = urllib.parse.urlencode(given, True)
1060 self.assertEqual(expect, result)
1061
1062 # Sequence of values
1063 given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
1064 expect = '%A0%24=42&%A0%24=%C1%24'
1065 result = urllib.parse.urlencode(given, True)
1066 self.assertEqual(expect, result)
1067
1068 def test_urlencode_encoding_safe_parameter(self):
1069
1070 # Send '$' (\x24) as safe character
1071 # Default utf-8 encoding
1072
1073 given = ((b'\xa0\x24', b'\xc1\x24'),)
1074 result = urllib.parse.urlencode(given, safe=":$")
1075 expect = '%A0$=%C1$'
1076 self.assertEqual(expect, result)
1077
1078 given = ((b'\xa0\x24', b'\xc1\x24'),)
1079 result = urllib.parse.urlencode(given, doseq=True, safe=":$")
1080 expect = '%A0$=%C1$'
1081 self.assertEqual(expect, result)
1082
1083 # Safe parameter in sequence
1084 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
1085 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
1086 result = urllib.parse.urlencode(given, True, safe=":$")
1087 self.assertEqual(expect, result)
1088
1089 # Test all above in latin-1 encoding
1090
1091 given = ((b'\xa0\x24', b'\xc1\x24'),)
1092 result = urllib.parse.urlencode(given, safe=":$",
1093 encoding="latin-1")
1094 expect = '%A0$=%C1$'
1095 self.assertEqual(expect, result)
1096
1097 given = ((b'\xa0\x24', b'\xc1\x24'),)
1098 expect = '%A0$=%C1$'
1099 result = urllib.parse.urlencode(given, doseq=True, safe=":$",
1100 encoding="latin-1")
1101
1102 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
1103 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
1104 result = urllib.parse.urlencode(given, True, safe=":$",
1105 encoding="latin-1")
1106 self.assertEqual(expect, result)
1107
Brett Cannon74bfd702003-04-25 09:39:47 +00001108class Pathname_Tests(unittest.TestCase):
1109 """Test pathname2url() and url2pathname()"""
1110
1111 def test_basic(self):
1112 # Make sure simple tests pass
1113 expected_path = os.path.join("parts", "of", "a", "path")
1114 expected_url = "parts/of/a/path"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001115 result = urllib.request.pathname2url(expected_path)
Brett Cannon74bfd702003-04-25 09:39:47 +00001116 self.assertEqual(expected_url, result,
1117 "pathname2url() failed; %s != %s" %
1118 (result, expected_url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001119 result = urllib.request.url2pathname(expected_url)
Brett Cannon74bfd702003-04-25 09:39:47 +00001120 self.assertEqual(expected_path, result,
1121 "url2pathame() failed; %s != %s" %
1122 (result, expected_path))
1123
1124 def test_quoting(self):
1125 # Test automatic quoting and unquoting works for pathnam2url() and
1126 # url2pathname() respectively
1127 given = os.path.join("needs", "quot=ing", "here")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001128 expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
1129 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +00001130 self.assertEqual(expect, result,
1131 "pathname2url() failed; %s != %s" %
1132 (expect, result))
1133 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001134 result = urllib.request.url2pathname(result)
Brett Cannon74bfd702003-04-25 09:39:47 +00001135 self.assertEqual(expect, result,
1136 "url2pathname() failed; %s != %s" %
1137 (expect, result))
1138 given = os.path.join("make sure", "using_quote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001139 expect = "%s/using_quote" % urllib.parse.quote("make sure")
1140 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +00001141 self.assertEqual(expect, result,
1142 "pathname2url() failed; %s != %s" %
1143 (expect, result))
1144 given = "make+sure/using_unquote"
1145 expect = os.path.join("make+sure", "using_unquote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001146 result = urllib.request.url2pathname(given)
Brett Cannon74bfd702003-04-25 09:39:47 +00001147 self.assertEqual(expect, result,
1148 "url2pathname() failed; %s != %s" %
1149 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +00001150
Senthil Kumaran2d2ea1b2011-04-14 13:16:30 +08001151 @unittest.skipUnless(sys.platform == 'win32',
1152 'test specific to the urllib.url2path function.')
1153 def test_ntpath(self):
1154 given = ('/C:/', '///C:/', '/C|//')
1155 expect = 'C:\\'
1156 for url in given:
1157 result = urllib.request.url2pathname(url)
1158 self.assertEqual(expect, result,
1159 'urllib.request..url2pathname() failed; %s != %s' %
1160 (expect, result))
1161 given = '///C|/path'
1162 expect = 'C:\\path'
1163 result = urllib.request.url2pathname(given)
1164 self.assertEqual(expect, result,
1165 'urllib.request.url2pathname() failed; %s != %s' %
1166 (expect, result))
1167
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001168class Utility_Tests(unittest.TestCase):
1169 """Testcase to test the various utility functions in the urllib."""
1170
1171 def test_splitpasswd(self):
1172 """Some of password examples are not sensible, but it is added to
1173 confirming to RFC2617 and addressing issue4675.
1174 """
1175 self.assertEqual(('user', 'ab'),urllib.parse.splitpasswd('user:ab'))
1176 self.assertEqual(('user', 'a\nb'),urllib.parse.splitpasswd('user:a\nb'))
1177 self.assertEqual(('user', 'a\tb'),urllib.parse.splitpasswd('user:a\tb'))
1178 self.assertEqual(('user', 'a\rb'),urllib.parse.splitpasswd('user:a\rb'))
1179 self.assertEqual(('user', 'a\fb'),urllib.parse.splitpasswd('user:a\fb'))
1180 self.assertEqual(('user', 'a\vb'),urllib.parse.splitpasswd('user:a\vb'))
1181 self.assertEqual(('user', 'a:b'),urllib.parse.splitpasswd('user:a:b'))
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001182 self.assertEqual(('user', 'a b'),urllib.parse.splitpasswd('user:a b'))
1183 self.assertEqual(('user 2', 'ab'),urllib.parse.splitpasswd('user 2:ab'))
1184 self.assertEqual(('user+1', 'a+b'),urllib.parse.splitpasswd('user+1:a+b'))
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001185
Senthil Kumaran1b7da512011-10-06 00:32:02 +08001186 def test_thishost(self):
1187 """Test the urllib.request.thishost utility function returns a tuple"""
1188 self.assertIsInstance(urllib.request.thishost(), tuple)
1189
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001190
1191class URLopener_Tests(unittest.TestCase):
1192 """Testcase to test the open method of URLopener class."""
1193
1194 def test_quoted_open(self):
1195 class DummyURLopener(urllib.request.URLopener):
1196 def open_spam(self, url):
1197 return url
1198
1199 self.assertEqual(DummyURLopener().open(
1200 'spam://example/ /'),'//example/%20/')
1201
Senthil Kumaran734f0592010-02-20 22:19:04 +00001202 # test the safe characters are not quoted by urlopen
1203 self.assertEqual(DummyURLopener().open(
1204 "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
1205 "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
1206
Guido van Rossume7ba4952007-06-06 23:52:48 +00001207# Just commented them out.
1208# Can't really tell why keep failing in windows and sparc.
Ezio Melotti13925002011-03-16 11:05:33 +02001209# Everywhere else they work ok, but on those machines, sometimes
Guido van Rossume7ba4952007-06-06 23:52:48 +00001210# fail in one of the tests, sometimes in other. I have a linux, and
1211# the tests go ok.
1212# If anybody has one of the problematic enviroments, please help!
1213# . Facundo
1214#
1215# def server(evt):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001216# import socket, time
Guido van Rossume7ba4952007-06-06 23:52:48 +00001217# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1218# serv.settimeout(3)
1219# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1220# serv.bind(("", 9093))
1221# serv.listen(5)
1222# try:
1223# conn, addr = serv.accept()
1224# conn.send("1 Hola mundo\n")
1225# cantdata = 0
1226# while cantdata < 13:
1227# data = conn.recv(13-cantdata)
1228# cantdata += len(data)
1229# time.sleep(.3)
1230# conn.send("2 No more lines\n")
1231# conn.close()
1232# except socket.timeout:
1233# pass
1234# finally:
1235# serv.close()
1236# evt.set()
1237#
1238# class FTPWrapperTests(unittest.TestCase):
1239#
1240# def setUp(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001241# import ftplib, time, threading
Guido van Rossume7ba4952007-06-06 23:52:48 +00001242# ftplib.FTP.port = 9093
1243# self.evt = threading.Event()
1244# threading.Thread(target=server, args=(self.evt,)).start()
1245# time.sleep(.1)
1246#
1247# def tearDown(self):
1248# self.evt.wait()
1249#
1250# def testBasic(self):
1251# # connects
1252# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Georg Brandlf78e02b2008-06-10 17:40:04 +00001253# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001254#
1255# def testTimeoutNone(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001256# # global default timeout is ignored
1257# import socket
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001258# self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001259# socket.setdefaulttimeout(30)
1260# try:
1261# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
1262# finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001263# socket.setdefaulttimeout(None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001264# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001265# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001266#
Georg Brandlf78e02b2008-06-10 17:40:04 +00001267# def testTimeoutDefault(self):
1268# # global default timeout is used
1269# import socket
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001270# self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001271# socket.setdefaulttimeout(30)
1272# try:
1273# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
1274# finally:
1275# socket.setdefaulttimeout(None)
1276# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
1277# ftp.close()
1278#
1279# def testTimeoutValue(self):
1280# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
1281# timeout=30)
1282# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
1283# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001284
Senthil Kumarande49d642011-10-16 23:54:44 +08001285class RequestTests(unittest.TestCase):
1286 """Unit tests for urllib.request.Request."""
1287
1288 def test_default_values(self):
1289 Request = urllib.request.Request
1290 request = Request("http://www.python.org")
1291 self.assertEqual(request.get_method(), 'GET')
1292 request = Request("http://www.python.org", {})
1293 self.assertEqual(request.get_method(), 'POST')
1294
1295 def test_with_method_arg(self):
1296 Request = urllib.request.Request
1297 request = Request("http://www.python.org", method='HEAD')
1298 self.assertEqual(request.method, 'HEAD')
1299 self.assertEqual(request.get_method(), 'HEAD')
1300 request = Request("http://www.python.org", {}, method='HEAD')
1301 self.assertEqual(request.method, 'HEAD')
1302 self.assertEqual(request.get_method(), 'HEAD')
1303 request = Request("http://www.python.org", method='GET')
1304 self.assertEqual(request.get_method(), 'GET')
1305 request.method = 'HEAD'
1306 self.assertEqual(request.get_method(), 'HEAD')
Skip Montanaro080c9972001-01-28 21:12:22 +00001307
1308
Brett Cannon74bfd702003-04-25 09:39:47 +00001309def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001310 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001311 urlopen_FileTests,
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001312 urlopen_HttpTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001313 urlretrieve_FileTests,
Senthil Kumarance260142011-11-01 01:35:17 +08001314 urlretrieve_HttpTests,
Benjamin Peterson9bc93512008-09-22 22:10:59 +00001315 ProxyTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001316 QuotingTests,
1317 UnquotingTests,
1318 urlencode_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001319 Pathname_Tests,
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001320 Utility_Tests,
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001321 URLopener_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001322 #FTPWrapperTests,
Senthil Kumarande49d642011-10-16 23:54:44 +08001323 RequestTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001324 )
Brett Cannon74bfd702003-04-25 09:39:47 +00001325
1326
1327
1328if __name__ == '__main__':
1329 test_main()