blob: 44574c9c14585e4b9fdde4a6b502906d679820be [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
Georg Brandl24420152008-05-26 16:32:26 +00005import http.client
Barry Warsaw820c1202008-06-12 04:06:45 +00006import email.message
Jeremy Hylton66dc8c52007-08-04 03:42:26 +00007import io
Brett Cannon74bfd702003-04-25 09:39:47 +00008import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +00009from test import support
Brett Cannon74bfd702003-04-25 09:39:47 +000010import os
Georg Brandl5a650a22005-08-26 08:51:34 +000011import tempfile
Jeremy Hylton6102e292000-08-31 15:48:10 +000012
Brett Cannon74bfd702003-04-25 09:39:47 +000013def hexescape(char):
14 """Escape char as RFC 2396 specifies"""
15 hex_repr = hex(ord(char))[2:].upper()
16 if len(hex_repr) == 1:
17 hex_repr = "0%s" % hex_repr
18 return "%" + hex_repr
Jeremy Hylton6102e292000-08-31 15:48:10 +000019
Jeremy Hylton1afc1692008-06-18 20:49:58 +000020# Shortcut for testing FancyURLopener
21_urlopener = None
22def urlopen(url, data=None, proxies=None):
23 """urlopen(url [, data]) -> open file-like object"""
24 global _urlopener
25 if proxies is not None:
26 opener = urllib.request.FancyURLopener(proxies=proxies)
27 elif not _urlopener:
28 opener = urllib.request.FancyURLopener()
29 _urlopener = opener
30 else:
31 opener = _urlopener
32 if data is None:
33 return opener.open(url)
34 else:
35 return opener.open(url, data)
36
Brett Cannon74bfd702003-04-25 09:39:47 +000037class urlopen_FileTests(unittest.TestCase):
38 """Test urlopen() opening a temporary file.
Jeremy Hylton6102e292000-08-31 15:48:10 +000039
Brett Cannon74bfd702003-04-25 09:39:47 +000040 Try to test as much functionality as possible so as to cut down on reliance
Andrew M. Kuchlingf1a2f9e2004-06-29 13:07:53 +000041 on connecting to the Net for testing.
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000042
Brett Cannon74bfd702003-04-25 09:39:47 +000043 """
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000044
Brett Cannon74bfd702003-04-25 09:39:47 +000045 def setUp(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000046 # Create a temp file to use for testing
47 self.text = bytes("test_urllib: %s\n" % self.__class__.__name__,
48 "ascii")
49 f = open(support.TESTFN, 'wb')
Brett Cannon74bfd702003-04-25 09:39:47 +000050 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +000051 f.write(self.text)
Brett Cannon74bfd702003-04-25 09:39:47 +000052 finally:
Jeremy Hylton1afc1692008-06-18 20:49:58 +000053 f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +000054 self.pathname = support.TESTFN
Jeremy Hylton1afc1692008-06-18 20:49:58 +000055 self.returned_obj = urlopen("file:%s" % self.pathname)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000056
Brett Cannon74bfd702003-04-25 09:39:47 +000057 def tearDown(self):
58 """Shut down the open object"""
59 self.returned_obj.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +000060 os.remove(support.TESTFN)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000061
Brett Cannon74bfd702003-04-25 09:39:47 +000062 def test_interface(self):
63 # Make sure object returned by urlopen() has the specified methods
64 for attr in ("read", "readline", "readlines", "fileno",
Christian Heimes9bd667a2008-01-20 15:14:11 +000065 "close", "info", "geturl", "getcode", "__iter__"):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +000066 self.assertTrue(hasattr(self.returned_obj, attr),
Brett Cannon74bfd702003-04-25 09:39:47 +000067 "object returned by urlopen() lacks %s attribute" %
68 attr)
Skip Montanaroe78b92a2001-01-20 20:22:30 +000069
Brett Cannon74bfd702003-04-25 09:39:47 +000070 def test_read(self):
71 self.assertEqual(self.text, self.returned_obj.read())
Skip Montanaro080c9972001-01-28 21:12:22 +000072
Brett Cannon74bfd702003-04-25 09:39:47 +000073 def test_readline(self):
74 self.assertEqual(self.text, self.returned_obj.readline())
Guido van Rossuma0982942007-07-10 08:30:03 +000075 self.assertEqual(b'', self.returned_obj.readline(),
Brett Cannon74bfd702003-04-25 09:39:47 +000076 "calling readline() after exhausting the file did not"
77 " return an empty string")
Skip Montanaro080c9972001-01-28 21:12:22 +000078
Brett Cannon74bfd702003-04-25 09:39:47 +000079 def test_readlines(self):
80 lines_list = self.returned_obj.readlines()
81 self.assertEqual(len(lines_list), 1,
82 "readlines() returned the wrong number of lines")
83 self.assertEqual(lines_list[0], self.text,
84 "readlines() returned improper text")
Skip Montanaro080c9972001-01-28 21:12:22 +000085
Brett Cannon74bfd702003-04-25 09:39:47 +000086 def test_fileno(self):
87 file_num = self.returned_obj.fileno()
Ezio Melottie9615932010-01-24 19:26:24 +000088 self.assertIsInstance(file_num, int, "fileno() did not return an int")
Brett Cannon74bfd702003-04-25 09:39:47 +000089 self.assertEqual(os.read(file_num, len(self.text)), self.text,
90 "Reading on the file descriptor returned by fileno() "
91 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +000092
Brett Cannon74bfd702003-04-25 09:39:47 +000093 def test_close(self):
94 # Test close() by calling it hear and then having it be called again
95 # by the tearDown() method for the test
96 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +000097
Brett Cannon74bfd702003-04-25 09:39:47 +000098 def test_info(self):
Ezio Melottie9615932010-01-24 19:26:24 +000099 self.assertIsInstance(self.returned_obj.info(), email.message.Message)
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000100
Brett Cannon74bfd702003-04-25 09:39:47 +0000101 def test_geturl(self):
102 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +0000103
Christian Heimes9bd667a2008-01-20 15:14:11 +0000104 def test_getcode(self):
105 self.assertEqual(self.returned_obj.getcode(), None)
106
Brett Cannon74bfd702003-04-25 09:39:47 +0000107 def test_iter(self):
108 # Test iterator
109 # Don't need to count number of iterations since test would fail the
110 # instant it returned anything beyond the first line from the
111 # comparison
112 for line in self.returned_obj.__iter__():
113 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +0000114
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000115class ProxyTests(unittest.TestCase):
116
117 def setUp(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +0000118 # Records changes to env vars
119 self.env = support.EnvironmentVarGuard()
Benjamin Peterson46a99002010-01-09 18:45:30 +0000120 # Delete all proxy related env vars
121 for k in os.environ.keys():
122 if 'proxy' in k.lower():
123 self.env.unset(k)
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000124
125 def tearDown(self):
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000126 # Restore all proxy related env vars
Walter Dörwaldb525e182009-04-26 21:39:21 +0000127 self.env.__exit__()
128 del self.env
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000129
130 def test_getproxies_environment_keep_no_proxies(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +0000131 self.env.set('NO_PROXY', 'localhost')
132 proxies = urllib.request.getproxies_environment()
133 # getproxies_environment use lowered case truncated (no '_proxy') keys
134 self.assertEquals('localhost', proxies['no'])
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000135
136
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000137class urlopen_HttpTests(unittest.TestCase):
138 """Test urlopen() opening a fake http connection."""
139
140 def fakehttp(self, fakedata):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000141 class FakeSocket(io.BytesIO):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000142 def sendall(self, str): pass
Nick Coghlan598c3a82009-02-08 04:01:00 +0000143 def makefile(self, *args, **kwds):
144 return self
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000145 def read(self, amt=None):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000146 if self.closed: return b""
147 return io.BytesIO.read(self, amt)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000148 def readline(self, length=None):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000149 if self.closed: return b""
150 return io.BytesIO.readline(self, length)
Georg Brandl24420152008-05-26 16:32:26 +0000151 class FakeHTTPConnection(http.client.HTTPConnection):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000152 def connect(self):
153 self.sock = FakeSocket(fakedata)
Georg Brandl24420152008-05-26 16:32:26 +0000154 self._connection_class = http.client.HTTPConnection
155 http.client.HTTPConnection = FakeHTTPConnection
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000156
157 def unfakehttp(self):
Georg Brandl24420152008-05-26 16:32:26 +0000158 http.client.HTTPConnection = self._connection_class
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000159
160 def test_read(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000161 self.fakehttp(b"Hello!")
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000162 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000163 fp = urlopen("http://python.org/")
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000164 self.assertEqual(fp.readline(), b"Hello!")
165 self.assertEqual(fp.readline(), b"")
Christian Heimes9bd667a2008-01-20 15:14:11 +0000166 self.assertEqual(fp.geturl(), 'http://python.org/')
167 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000168 finally:
169 self.unfakehttp()
170
Christian Heimes57dddfb2008-01-02 18:30:52 +0000171 def test_read_bogus(self):
172 # urlopen() should raise IOError for many error codes.
173 self.fakehttp(b'''HTTP/1.1 401 Authentication Required
174Date: Wed, 02 Jan 2008 03:03:54 GMT
175Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
176Connection: close
177Content-Type: text/html; charset=iso-8859-1
178''')
179 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000180 self.assertRaises(IOError, urlopen, "http://python.org/")
Christian Heimes57dddfb2008-01-02 18:30:52 +0000181 finally:
182 self.unfakehttp()
183
Guido van Rossumd8faa362007-04-27 19:54:29 +0000184 def test_empty_socket(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000185 # urlopen() raises IOError if the underlying socket does not send any
186 # data. (#1680230)
Christian Heimes57dddfb2008-01-02 18:30:52 +0000187 self.fakehttp(b'')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000188 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000189 self.assertRaises(IOError, urlopen, "http://something")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000190 finally:
191 self.unfakehttp()
192
Brett Cannon19691362003-04-29 05:08:06 +0000193class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000194 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000195
Brett Cannon19691362003-04-29 05:08:06 +0000196 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000197 # Create a list of temporary files. Each item in the list is a file
198 # name (absolute path or relative to the current working directory).
199 # All files in this list will be deleted in the tearDown method. Note,
200 # this only helps to makes sure temporary files get deleted, but it
201 # does nothing about trying to close files that may still be open. It
202 # is the responsibility of the developer to properly close files even
203 # when exceptional conditions occur.
204 self.tempFiles = []
205
Brett Cannon19691362003-04-29 05:08:06 +0000206 # Create a temporary file.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000207 self.registerFileForCleanUp(support.TESTFN)
Guido van Rossuma0982942007-07-10 08:30:03 +0000208 self.text = b'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000209 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000210 FILE = open(support.TESTFN, 'wb')
Georg Brandl5a650a22005-08-26 08:51:34 +0000211 FILE.write(self.text)
212 FILE.close()
213 finally:
214 try: FILE.close()
215 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000216
217 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000218 # Delete the temporary files.
219 for each in self.tempFiles:
220 try: os.remove(each)
221 except: pass
222
223 def constructLocalFileUrl(self, filePath):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000224 return "file://%s" % urllib.request.pathname2url(
225 os.path.abspath(filePath))
Georg Brandl5a650a22005-08-26 08:51:34 +0000226
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000227 def createNewTempFile(self, data=b""):
Georg Brandl5a650a22005-08-26 08:51:34 +0000228 """Creates a new temporary file containing the specified data,
229 registers the file for deletion during the test fixture tear down, and
230 returns the absolute path of the file."""
231
232 newFd, newFilePath = tempfile.mkstemp()
233 try:
234 self.registerFileForCleanUp(newFilePath)
235 newFile = os.fdopen(newFd, "wb")
236 newFile.write(data)
237 newFile.close()
238 finally:
239 try: newFile.close()
240 except: pass
241 return newFilePath
242
243 def registerFileForCleanUp(self, fileName):
244 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000245
246 def test_basic(self):
247 # Make sure that a local file just gets its own location returned and
248 # a headers value is returned.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000249 result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000250 self.assertEqual(result[0], support.TESTFN)
Ezio Melottie9615932010-01-24 19:26:24 +0000251 self.assertIsInstance(result[1], email.message.Message,
252 "did not get a email.message.Message instance "
253 "as second returned value")
Brett Cannon19691362003-04-29 05:08:06 +0000254
255 def test_copy(self):
256 # Test that setting the filename argument works.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000257 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000258 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000259 result = urllib.request.urlretrieve(self.constructLocalFileUrl(
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000260 support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000261 self.assertEqual(second_temp, result[0])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000262 self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
Brett Cannon19691362003-04-29 05:08:06 +0000263 "made")
Alex Martelli01c77c62006-08-24 02:58:11 +0000264 FILE = open(second_temp, 'rb')
Brett Cannon19691362003-04-29 05:08:06 +0000265 try:
266 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000267 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000268 finally:
269 try: FILE.close()
270 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000271 self.assertEqual(self.text, text)
272
273 def test_reporthook(self):
274 # Make sure that the reporthook works.
275 def hooktester(count, block_size, total_size, count_holder=[0]):
Ezio Melottie9615932010-01-24 19:26:24 +0000276 self.assertIsInstance(count, int)
277 self.assertIsInstance(block_size, int)
278 self.assertIsInstance(total_size, int)
Brett Cannon19691362003-04-29 05:08:06 +0000279 self.assertEqual(count, count_holder[0])
280 count_holder[0] = count_holder[0] + 1
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000281 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000282 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000283 urllib.request.urlretrieve(
284 self.constructLocalFileUrl(support.TESTFN),
Georg Brandl5a650a22005-08-26 08:51:34 +0000285 second_temp, hooktester)
286
287 def test_reporthook_0_bytes(self):
288 # Test on zero length file. Should call reporthook only 1 time.
289 report = []
290 def hooktester(count, block_size, total_size, _report=report):
291 _report.append((count, block_size, total_size))
292 srcFileName = self.createNewTempFile()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000293 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000294 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000295 self.assertEqual(len(report), 1)
296 self.assertEqual(report[0][2], 0)
297
298 def test_reporthook_5_bytes(self):
299 # Test on 5 byte file. Should call reporthook only 2 times (once when
300 # the "network connection" is established and once when the block is
301 # read). Since the block size is 8192 bytes, only one block read is
302 # required to read the entire file.
303 report = []
304 def hooktester(count, block_size, total_size, _report=report):
305 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000306 srcFileName = self.createNewTempFile(b"x" * 5)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000307 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000308 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000309 self.assertEqual(len(report), 2)
310 self.assertEqual(report[0][1], 8192)
311 self.assertEqual(report[0][2], 5)
312
313 def test_reporthook_8193_bytes(self):
314 # Test on 8193 byte file. Should call reporthook only 3 times (once
315 # when the "network connection" is established, once for the next 8192
316 # bytes, and once for the last byte).
317 report = []
318 def hooktester(count, block_size, total_size, _report=report):
319 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000320 srcFileName = self.createNewTempFile(b"x" * 8193)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000321 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000322 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000323 self.assertEqual(len(report), 3)
324 self.assertEqual(report[0][1], 8192)
325 self.assertEqual(report[0][2], 8193)
Skip Montanaro080c9972001-01-28 21:12:22 +0000326
Brett Cannon74bfd702003-04-25 09:39:47 +0000327class QuotingTests(unittest.TestCase):
328 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000329
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000330 According to RFC 2396 (Uniform Resource Identifiers), to escape a
331 character you write it as '%' + <2 character US-ASCII hex value>.
332 The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
333 character properly. Case does not matter on the hex letters.
Brett Cannon74bfd702003-04-25 09:39:47 +0000334
335 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000336
Brett Cannon74bfd702003-04-25 09:39:47 +0000337 Reserved characters : ";/?:@&=+$,"
338 Have special meaning in URIs and must be escaped if not being used for
339 their special meaning
340 Data characters : letters, digits, and "-_.!~*'()"
341 Unreserved and do not need to be escaped; can be, though, if desired
342 Control characters : 0x00 - 0x1F, 0x7F
343 Have no use in URIs so must be escaped
344 space : 0x20
345 Must be escaped
346 Delimiters : '<>#%"'
347 Must be escaped
348 Unwise : "{}|\^[]`"
349 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000350
Brett Cannon74bfd702003-04-25 09:39:47 +0000351 """
352
353 def test_never_quote(self):
354 # Make sure quote() does not quote letters, digits, and "_,.-"
355 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
356 "abcdefghijklmnopqrstuvwxyz",
357 "0123456789",
358 "_.-"])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000359 result = urllib.parse.quote(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000360 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000361 "using quote(): %r != %r" % (do_not_quote, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000362 result = urllib.parse.quote_plus(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000363 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000364 "using quote_plus(): %r != %r" % (do_not_quote, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000365
366 def test_default_safe(self):
367 # Test '/' is default value for 'safe' parameter
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000368 self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
Brett Cannon74bfd702003-04-25 09:39:47 +0000369
370 def test_safe(self):
371 # Test setting 'safe' parameter does what it should do
372 quote_by_default = "<>"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000373 result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000374 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000375 "using quote(): %r != %r" % (quote_by_default, result))
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000376 result = urllib.parse.quote_plus(quote_by_default,
377 safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000378 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000379 "using quote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000380 (quote_by_default, result))
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000381 # Safe expressed as bytes rather than str
382 result = urllib.parse.quote(quote_by_default, safe=b"<>")
383 self.assertEqual(quote_by_default, result,
384 "using quote(): %r != %r" % (quote_by_default, result))
385 # "Safe" non-ASCII characters should have no effect
386 # (Since URIs are not allowed to have non-ASCII characters)
387 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc")
388 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
389 self.assertEqual(expect, result,
390 "using quote(): %r != %r" %
391 (expect, result))
392 # Same as above, but using a bytes rather than str
393 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc")
394 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
395 self.assertEqual(expect, result,
396 "using quote(): %r != %r" %
397 (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000398
399 def test_default_quoting(self):
400 # Make sure all characters that should be quoted are by default sans
401 # space (separate test for that).
402 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
403 should_quote.append('<>#%"{}|\^[]`')
404 should_quote.append(chr(127)) # For 0x7F
405 should_quote = ''.join(should_quote)
406 for char in should_quote:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000407 result = urllib.parse.quote(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000408 self.assertEqual(hexescape(char), result,
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000409 "using quote(): "
410 "%s should be escaped to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000411 (char, hexescape(char), result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000412 result = urllib.parse.quote_plus(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000413 self.assertEqual(hexescape(char), result,
414 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000415 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000416 (char, hexescape(char), result))
417 del should_quote
418 partial_quote = "ab[]cd"
419 expected = "ab%5B%5Dcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000420 result = urllib.parse.quote(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000421 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000422 "using quote(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000423 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000424 "using quote_plus(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000425
426 def test_quoting_space(self):
427 # Make sure quote() and quote_plus() handle spaces as specified in
428 # their unique way
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000429 result = urllib.parse.quote(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000430 self.assertEqual(result, hexescape(' '),
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000431 "using quote(): %r != %r" % (result, hexescape(' ')))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000432 result = urllib.parse.quote_plus(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000433 self.assertEqual(result, '+',
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000434 "using quote_plus(): %r != +" % result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000435 given = "a b cd e f"
436 expect = given.replace(' ', hexescape(' '))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000437 result = urllib.parse.quote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000438 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000439 "using quote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000440 expect = given.replace(' ', '+')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000441 result = urllib.parse.quote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000442 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000443 "using quote_plus(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000444
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000445 def test_quoting_plus(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000446 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000447 'alpha%2Bbeta+gamma')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000448 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000449 'alpha+beta+gamma')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000450 # Test with bytes
451 self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
452 'alpha%2Bbeta+gamma')
453 # Test with safe bytes
454 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
455 'alpha+beta+gamma')
456
457 def test_quote_bytes(self):
458 # Bytes should quote directly to percent-encoded values
459 given = b"\xa2\xd8ab\xff"
460 expect = "%A2%D8ab%FF"
461 result = urllib.parse.quote(given)
462 self.assertEqual(expect, result,
463 "using quote(): %r != %r" % (expect, result))
464 # Encoding argument should raise type error on bytes input
465 self.assertRaises(TypeError, urllib.parse.quote, given,
466 encoding="latin-1")
467 # quote_from_bytes should work the same
468 result = urllib.parse.quote_from_bytes(given)
469 self.assertEqual(expect, result,
470 "using quote_from_bytes(): %r != %r"
471 % (expect, result))
472
473 def test_quote_with_unicode(self):
474 # Characters in Latin-1 range, encoded by default in UTF-8
475 given = "\xa2\xd8ab\xff"
476 expect = "%C2%A2%C3%98ab%C3%BF"
477 result = urllib.parse.quote(given)
478 self.assertEqual(expect, result,
479 "using quote(): %r != %r" % (expect, result))
480 # Characters in Latin-1 range, encoded by with None (default)
481 result = urllib.parse.quote(given, encoding=None, errors=None)
482 self.assertEqual(expect, result,
483 "using quote(): %r != %r" % (expect, result))
484 # Characters in Latin-1 range, encoded with Latin-1
485 given = "\xa2\xd8ab\xff"
486 expect = "%A2%D8ab%FF"
487 result = urllib.parse.quote(given, encoding="latin-1")
488 self.assertEqual(expect, result,
489 "using quote(): %r != %r" % (expect, result))
490 # Characters in BMP, encoded by default in UTF-8
491 given = "\u6f22\u5b57" # "Kanji"
492 expect = "%E6%BC%A2%E5%AD%97"
493 result = urllib.parse.quote(given)
494 self.assertEqual(expect, result,
495 "using quote(): %r != %r" % (expect, result))
496 # Characters in BMP, encoded with Latin-1
497 given = "\u6f22\u5b57"
498 self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
499 encoding="latin-1")
500 # Characters in BMP, encoded with Latin-1, with replace error handling
501 given = "\u6f22\u5b57"
502 expect = "%3F%3F" # "??"
503 result = urllib.parse.quote(given, encoding="latin-1",
504 errors="replace")
505 self.assertEqual(expect, result,
506 "using quote(): %r != %r" % (expect, result))
507 # Characters in BMP, Latin-1, with xmlcharref error handling
508 given = "\u6f22\u5b57"
509 expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;"
510 result = urllib.parse.quote(given, encoding="latin-1",
511 errors="xmlcharrefreplace")
512 self.assertEqual(expect, result,
513 "using quote(): %r != %r" % (expect, result))
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000514
Georg Brandlfaf41492009-05-26 18:31:11 +0000515 def test_quote_plus_with_unicode(self):
516 # Encoding (latin-1) test for quote_plus
517 given = "\xa2\xd8 \xff"
518 expect = "%A2%D8+%FF"
519 result = urllib.parse.quote_plus(given, encoding="latin-1")
520 self.assertEqual(expect, result,
521 "using quote_plus(): %r != %r" % (expect, result))
522 # Errors test for quote_plus
523 given = "ab\u6f22\u5b57 cd"
524 expect = "ab%3F%3F+cd"
525 result = urllib.parse.quote_plus(given, encoding="latin-1",
526 errors="replace")
527 self.assertEqual(expect, result,
528 "using quote_plus(): %r != %r" % (expect, result))
529
Brett Cannon74bfd702003-04-25 09:39:47 +0000530class UnquotingTests(unittest.TestCase):
531 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000532
Brett Cannon74bfd702003-04-25 09:39:47 +0000533 See the doc string for quoting_Tests for details on quoting and such.
534
535 """
536
537 def test_unquoting(self):
538 # Make sure unquoting of all ASCII values works
539 escape_list = []
540 for num in range(128):
541 given = hexescape(chr(num))
542 expect = chr(num)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000543 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000544 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000545 "using unquote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000546 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000547 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000548 "using unquote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000549 (expect, result))
550 escape_list.append(given)
551 escape_string = ''.join(escape_list)
552 del escape_list
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000553 result = urllib.parse.unquote(escape_string)
Brett Cannon74bfd702003-04-25 09:39:47 +0000554 self.assertEqual(result.count('%'), 1,
Brett Cannon74bfd702003-04-25 09:39:47 +0000555 "using unquote(): not all characters escaped: "
556 "%s" % result)
Senthil Kumaran79e17f62010-07-19 18:17:19 +0000557 self.assertRaises(TypeError, urllib.parse.unquote, None)
Brett Cannon74bfd702003-04-25 09:39:47 +0000558
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000559 def test_unquoting_badpercent(self):
560 # Test unquoting on bad percent-escapes
561 given = '%xab'
562 expect = given
563 result = urllib.parse.unquote(given)
564 self.assertEqual(expect, result, "using unquote(): %r != %r"
565 % (expect, result))
566 given = '%x'
567 expect = given
568 result = urllib.parse.unquote(given)
569 self.assertEqual(expect, result, "using unquote(): %r != %r"
570 % (expect, result))
571 given = '%'
572 expect = given
573 result = urllib.parse.unquote(given)
574 self.assertEqual(expect, result, "using unquote(): %r != %r"
575 % (expect, result))
576 # unquote_to_bytes
577 given = '%xab'
578 expect = bytes(given, 'ascii')
579 result = urllib.parse.unquote_to_bytes(given)
580 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
581 % (expect, result))
582 given = '%x'
583 expect = bytes(given, 'ascii')
584 result = urllib.parse.unquote_to_bytes(given)
585 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
586 % (expect, result))
587 given = '%'
588 expect = bytes(given, 'ascii')
589 result = urllib.parse.unquote_to_bytes(given)
590 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
591 % (expect, result))
592
Senthil Kumaran79e17f62010-07-19 18:17:19 +0000593 self.assertRaises(TypeError, urllib.parse.unquote_to_bytes, None)
594
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000595 def test_unquoting_mixed_case(self):
596 # Test unquoting on mixed-case hex digits in the percent-escapes
597 given = '%Ab%eA'
598 expect = b'\xab\xea'
599 result = urllib.parse.unquote_to_bytes(given)
600 self.assertEqual(expect, result,
601 "using unquote_to_bytes(): %r != %r"
602 % (expect, result))
603
Brett Cannon74bfd702003-04-25 09:39:47 +0000604 def test_unquoting_parts(self):
605 # Make sure unquoting works when have non-quoted characters
606 # interspersed
607 given = 'ab%sd' % hexescape('c')
608 expect = "abcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000609 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000610 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000611 "using quote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000612 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000613 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000614 "using unquote_plus(): %r != %r" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000615
Brett Cannon74bfd702003-04-25 09:39:47 +0000616 def test_unquoting_plus(self):
617 # Test difference between unquote() and unquote_plus()
618 given = "are+there+spaces..."
619 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000620 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000621 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000622 "using unquote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000623 expect = given.replace('+', ' ')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000624 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000625 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000626 "using unquote_plus(): %r != %r" % (expect, result))
627
628 def test_unquote_to_bytes(self):
629 given = 'br%C3%BCckner_sapporo_20050930.doc'
630 expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
631 result = urllib.parse.unquote_to_bytes(given)
632 self.assertEqual(expect, result,
633 "using unquote_to_bytes(): %r != %r"
634 % (expect, result))
635 # Test on a string with unescaped non-ASCII characters
636 # (Technically an invalid URI; expect those characters to be UTF-8
637 # encoded).
638 result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
639 expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
640 self.assertEqual(expect, result,
641 "using unquote_to_bytes(): %r != %r"
642 % (expect, result))
643 # Test with a bytes as input
644 given = b'%A2%D8ab%FF'
645 expect = b'\xa2\xd8ab\xff'
646 result = urllib.parse.unquote_to_bytes(given)
647 self.assertEqual(expect, result,
648 "using unquote_to_bytes(): %r != %r"
649 % (expect, result))
650 # Test with a bytes as input, with unescaped non-ASCII bytes
651 # (Technically an invalid URI; expect those bytes to be preserved)
652 given = b'%A2\xd8ab%FF'
653 expect = b'\xa2\xd8ab\xff'
654 result = urllib.parse.unquote_to_bytes(given)
655 self.assertEqual(expect, result,
656 "using unquote_to_bytes(): %r != %r"
657 % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000658
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000659 def test_unquote_with_unicode(self):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000660 # Characters in the Latin-1 range, encoded with UTF-8
661 given = 'br%C3%BCckner_sapporo_20050930.doc'
662 expect = 'br\u00fcckner_sapporo_20050930.doc'
663 result = urllib.parse.unquote(given)
664 self.assertEqual(expect, result,
665 "using unquote(): %r != %r" % (expect, result))
666 # Characters in the Latin-1 range, encoded with None (default)
667 result = urllib.parse.unquote(given, encoding=None, errors=None)
668 self.assertEqual(expect, result,
669 "using unquote(): %r != %r" % (expect, result))
670
671 # Characters in the Latin-1 range, encoded with Latin-1
672 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
673 encoding="latin-1")
674 expect = 'br\u00fcckner_sapporo_20050930.doc'
675 self.assertEqual(expect, result,
676 "using unquote(): %r != %r" % (expect, result))
677
678 # Characters in BMP, encoded with UTF-8
679 given = "%E6%BC%A2%E5%AD%97"
680 expect = "\u6f22\u5b57" # "Kanji"
681 result = urllib.parse.unquote(given)
682 self.assertEqual(expect, result,
683 "using unquote(): %r != %r" % (expect, result))
684
685 # Decode with UTF-8, invalid sequence
686 given = "%F3%B1"
687 expect = "\ufffd" # Replacement character
688 result = urllib.parse.unquote(given)
689 self.assertEqual(expect, result,
690 "using unquote(): %r != %r" % (expect, result))
691
692 # Decode with UTF-8, invalid sequence, replace errors
693 result = urllib.parse.unquote(given, errors="replace")
694 self.assertEqual(expect, result,
695 "using unquote(): %r != %r" % (expect, result))
696
697 # Decode with UTF-8, invalid sequence, ignoring errors
698 given = "%F3%B1"
699 expect = ""
700 result = urllib.parse.unquote(given, errors="ignore")
701 self.assertEqual(expect, result,
702 "using unquote(): %r != %r" % (expect, result))
703
704 # A mix of non-ASCII and percent-encoded characters, UTF-8
705 result = urllib.parse.unquote("\u6f22%C3%BC")
706 expect = '\u6f22\u00fc'
707 self.assertEqual(expect, result,
708 "using unquote(): %r != %r" % (expect, result))
709
710 # A mix of non-ASCII and percent-encoded characters, Latin-1
711 # (Note, the string contains non-Latin-1-representable characters)
712 result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
713 expect = '\u6f22\u00fc'
714 self.assertEqual(expect, result,
715 "using unquote(): %r != %r" % (expect, result))
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000716
Brett Cannon74bfd702003-04-25 09:39:47 +0000717class urlencode_Tests(unittest.TestCase):
718 """Tests for urlencode()"""
719
720 def help_inputtype(self, given, test_type):
721 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000722
Brett Cannon74bfd702003-04-25 09:39:47 +0000723 'given' must lead to only the pairs:
724 * 1st, 1
725 * 2nd, 2
726 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000727
Brett Cannon74bfd702003-04-25 09:39:47 +0000728 Test cannot assume anything about order. Docs make no guarantee and
729 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000730
Brett Cannon74bfd702003-04-25 09:39:47 +0000731 """
732 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000733 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000734 for expected in expect_somewhere:
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000735 self.assertIn(expected, result,
Brett Cannon74bfd702003-04-25 09:39:47 +0000736 "testing %s: %s not found in %s" %
737 (test_type, expected, result))
738 self.assertEqual(result.count('&'), 2,
739 "testing %s: expected 2 '&'s; got %s" %
740 (test_type, result.count('&')))
741 amp_location = result.index('&')
742 on_amp_left = result[amp_location - 1]
743 on_amp_right = result[amp_location + 1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000744 self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000745 "testing %s: '&' not located in proper place in %s" %
746 (test_type, result))
747 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
748 "testing %s: "
749 "unexpected number of characters: %s != %s" %
750 (test_type, len(result), (5 * 3) + 2))
751
752 def test_using_mapping(self):
753 # Test passing in a mapping object as an argument.
754 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
755 "using dict as input type")
756
757 def test_using_sequence(self):
758 # Test passing in a sequence of two-item sequences as an argument.
759 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
760 "using sequence of two-item tuples as input")
761
762 def test_quoting(self):
763 # Make sure keys and values are quoted using quote_plus()
764 given = {"&":"="}
765 expect = "%s=%s" % (hexescape('&'), hexescape('='))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000766 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000767 self.assertEqual(expect, result)
768 given = {"key name":"A bunch of pluses"}
769 expect = "key+name=A+bunch+of+pluses"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000770 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000771 self.assertEqual(expect, result)
772
773 def test_doseq(self):
774 # Test that passing True for 'doseq' parameter works correctly
775 given = {'sequence':['1', '2', '3']}
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000776 expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
777 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000778 self.assertEqual(expect, result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000779 result = urllib.parse.urlencode(given, True)
Brett Cannon74bfd702003-04-25 09:39:47 +0000780 for value in given["sequence"]:
781 expect = "sequence=%s" % value
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000782 self.assertIn(expect, result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000783 self.assertEqual(result.count('&'), 2,
784 "Expected 2 '&'s, got %s" % result.count('&'))
785
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000786 def test_empty_sequence(self):
787 self.assertEqual("", urllib.parse.urlencode({}))
788 self.assertEqual("", urllib.parse.urlencode([]))
789
790 def test_nonstring_values(self):
791 self.assertEqual("a=1", urllib.parse.urlencode({"a": 1}))
792 self.assertEqual("a=None", urllib.parse.urlencode({"a": None}))
793
794 def test_nonstring_seq_values(self):
795 self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True))
796 self.assertEqual("a=None&a=a",
797 urllib.parse.urlencode({"a": [None, "a"]}, True))
798 self.assertEqual("a=a&a=b",
799 urllib.parse.urlencode({"a": {"a": 1, "b": 1}}, True))
800
Senthil Kumarandf022da2010-07-03 17:48:22 +0000801 def test_urlencode_encoding(self):
802 # ASCII encoding. Expect %3F with errors="replace'
803 given = (('\u00a0', '\u00c1'),)
804 expect = '%3F=%3F'
805 result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
806 self.assertEqual(expect, result)
807
808 # Default is UTF-8 encoding.
809 given = (('\u00a0', '\u00c1'),)
810 expect = '%C2%A0=%C3%81'
811 result = urllib.parse.urlencode(given)
812 self.assertEqual(expect, result)
813
814 # Latin-1 encoding.
815 given = (('\u00a0', '\u00c1'),)
816 expect = '%A0=%C1'
817 result = urllib.parse.urlencode(given, encoding="latin-1")
818 self.assertEqual(expect, result)
819
820 def test_urlencode_encoding_doseq(self):
821 # ASCII Encoding. Expect %3F with errors="replace'
822 given = (('\u00a0', '\u00c1'),)
823 expect = '%3F=%3F'
824 result = urllib.parse.urlencode(given, doseq=True,
825 encoding="ASCII", errors="replace")
826 self.assertEqual(expect, result)
827
828 # ASCII Encoding. On a sequence of values.
829 given = (("\u00a0", (1, "\u00c1")),)
830 expect = '%3F=1&%3F=%3F'
831 result = urllib.parse.urlencode(given, True,
832 encoding="ASCII", errors="replace")
833 self.assertEqual(expect, result)
834
835 # Utf-8
836 given = (("\u00a0", "\u00c1"),)
837 expect = '%C2%A0=%C3%81'
838 result = urllib.parse.urlencode(given, True)
839 self.assertEqual(expect, result)
840
841 given = (("\u00a0", (42, "\u00c1")),)
842 expect = '%C2%A0=42&%C2%A0=%C3%81'
843 result = urllib.parse.urlencode(given, True)
844 self.assertEqual(expect, result)
845
846 # latin-1
847 given = (("\u00a0", "\u00c1"),)
848 expect = '%A0=%C1'
849 result = urllib.parse.urlencode(given, True, encoding="latin-1")
850 self.assertEqual(expect, result)
851
852 given = (("\u00a0", (42, "\u00c1")),)
853 expect = '%A0=42&%A0=%C1'
854 result = urllib.parse.urlencode(given, True, encoding="latin-1")
855 self.assertEqual(expect, result)
856
857 def test_urlencode_bytes(self):
858 given = ((b'\xa0\x24', b'\xc1\x24'),)
859 expect = '%A0%24=%C1%24'
860 result = urllib.parse.urlencode(given)
861 self.assertEqual(expect, result)
862 result = urllib.parse.urlencode(given, True)
863 self.assertEqual(expect, result)
864
865 # Sequence of values
866 given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
867 expect = '%A0%24=42&%A0%24=%C1%24'
868 result = urllib.parse.urlencode(given, True)
869 self.assertEqual(expect, result)
870
871 def test_urlencode_encoding_safe_parameter(self):
872
873 # Send '$' (\x24) as safe character
874 # Default utf-8 encoding
875
876 given = ((b'\xa0\x24', b'\xc1\x24'),)
877 result = urllib.parse.urlencode(given, safe=":$")
878 expect = '%A0$=%C1$'
879 self.assertEqual(expect, result)
880
881 given = ((b'\xa0\x24', b'\xc1\x24'),)
882 result = urllib.parse.urlencode(given, doseq=True, safe=":$")
883 expect = '%A0$=%C1$'
884 self.assertEqual(expect, result)
885
886 # Safe parameter in sequence
887 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
888 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
889 result = urllib.parse.urlencode(given, True, safe=":$")
890 self.assertEqual(expect, result)
891
892 # Test all above in latin-1 encoding
893
894 given = ((b'\xa0\x24', b'\xc1\x24'),)
895 result = urllib.parse.urlencode(given, safe=":$",
896 encoding="latin-1")
897 expect = '%A0$=%C1$'
898 self.assertEqual(expect, result)
899
900 given = ((b'\xa0\x24', b'\xc1\x24'),)
901 expect = '%A0$=%C1$'
902 result = urllib.parse.urlencode(given, doseq=True, safe=":$",
903 encoding="latin-1")
904
905 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
906 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
907 result = urllib.parse.urlencode(given, True, safe=":$",
908 encoding="latin-1")
909 self.assertEqual(expect, result)
910
Brett Cannon74bfd702003-04-25 09:39:47 +0000911class Pathname_Tests(unittest.TestCase):
912 """Test pathname2url() and url2pathname()"""
913
914 def test_basic(self):
915 # Make sure simple tests pass
916 expected_path = os.path.join("parts", "of", "a", "path")
917 expected_url = "parts/of/a/path"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000918 result = urllib.request.pathname2url(expected_path)
Brett Cannon74bfd702003-04-25 09:39:47 +0000919 self.assertEqual(expected_url, result,
920 "pathname2url() failed; %s != %s" %
921 (result, expected_url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000922 result = urllib.request.url2pathname(expected_url)
Brett Cannon74bfd702003-04-25 09:39:47 +0000923 self.assertEqual(expected_path, result,
924 "url2pathame() failed; %s != %s" %
925 (result, expected_path))
926
927 def test_quoting(self):
928 # Test automatic quoting and unquoting works for pathnam2url() and
929 # url2pathname() respectively
930 given = os.path.join("needs", "quot=ing", "here")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000931 expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
932 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000933 self.assertEqual(expect, result,
934 "pathname2url() failed; %s != %s" %
935 (expect, result))
936 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000937 result = urllib.request.url2pathname(result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000938 self.assertEqual(expect, result,
939 "url2pathname() failed; %s != %s" %
940 (expect, result))
941 given = os.path.join("make sure", "using_quote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000942 expect = "%s/using_quote" % urllib.parse.quote("make sure")
943 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000944 self.assertEqual(expect, result,
945 "pathname2url() failed; %s != %s" %
946 (expect, result))
947 given = "make+sure/using_unquote"
948 expect = os.path.join("make+sure", "using_unquote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000949 result = urllib.request.url2pathname(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000950 self.assertEqual(expect, result,
951 "url2pathname() failed; %s != %s" %
952 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000953
Senthil Kumaraneaaec272009-03-30 21:54:41 +0000954class Utility_Tests(unittest.TestCase):
955 """Testcase to test the various utility functions in the urllib."""
956
957 def test_splitpasswd(self):
958 """Some of password examples are not sensible, but it is added to
959 confirming to RFC2617 and addressing issue4675.
960 """
961 self.assertEqual(('user', 'ab'),urllib.parse.splitpasswd('user:ab'))
962 self.assertEqual(('user', 'a\nb'),urllib.parse.splitpasswd('user:a\nb'))
963 self.assertEqual(('user', 'a\tb'),urllib.parse.splitpasswd('user:a\tb'))
964 self.assertEqual(('user', 'a\rb'),urllib.parse.splitpasswd('user:a\rb'))
965 self.assertEqual(('user', 'a\fb'),urllib.parse.splitpasswd('user:a\fb'))
966 self.assertEqual(('user', 'a\vb'),urllib.parse.splitpasswd('user:a\vb'))
967 self.assertEqual(('user', 'a:b'),urllib.parse.splitpasswd('user:a:b'))
968
Senthil Kumaran690ce9b2009-05-05 18:41:13 +0000969
970class URLopener_Tests(unittest.TestCase):
971 """Testcase to test the open method of URLopener class."""
972
973 def test_quoted_open(self):
974 class DummyURLopener(urllib.request.URLopener):
975 def open_spam(self, url):
976 return url
977
978 self.assertEqual(DummyURLopener().open(
979 'spam://example/ /'),'//example/%20/')
980
Senthil Kumaran734f0592010-02-20 22:19:04 +0000981 # test the safe characters are not quoted by urlopen
982 self.assertEqual(DummyURLopener().open(
983 "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
984 "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
985
Guido van Rossume7ba4952007-06-06 23:52:48 +0000986# Just commented them out.
987# Can't really tell why keep failing in windows and sparc.
988# Everywhere else they work ok, but on those machines, someteimes
989# fail in one of the tests, sometimes in other. I have a linux, and
990# the tests go ok.
991# If anybody has one of the problematic enviroments, please help!
992# . Facundo
993#
994# def server(evt):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000995# import socket, time
Guido van Rossume7ba4952007-06-06 23:52:48 +0000996# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
997# serv.settimeout(3)
998# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
999# serv.bind(("", 9093))
1000# serv.listen(5)
1001# try:
1002# conn, addr = serv.accept()
1003# conn.send("1 Hola mundo\n")
1004# cantdata = 0
1005# while cantdata < 13:
1006# data = conn.recv(13-cantdata)
1007# cantdata += len(data)
1008# time.sleep(.3)
1009# conn.send("2 No more lines\n")
1010# conn.close()
1011# except socket.timeout:
1012# pass
1013# finally:
1014# serv.close()
1015# evt.set()
1016#
1017# class FTPWrapperTests(unittest.TestCase):
1018#
1019# def setUp(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001020# import ftplib, time, threading
Guido van Rossume7ba4952007-06-06 23:52:48 +00001021# ftplib.FTP.port = 9093
1022# self.evt = threading.Event()
1023# threading.Thread(target=server, args=(self.evt,)).start()
1024# time.sleep(.1)
1025#
1026# def tearDown(self):
1027# self.evt.wait()
1028#
1029# def testBasic(self):
1030# # connects
1031# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Georg Brandlf78e02b2008-06-10 17:40:04 +00001032# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001033#
1034# def testTimeoutNone(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001035# # global default timeout is ignored
1036# import socket
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001037# self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001038# socket.setdefaulttimeout(30)
1039# try:
1040# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
1041# finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001042# socket.setdefaulttimeout(None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001043# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001044# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001045#
Georg Brandlf78e02b2008-06-10 17:40:04 +00001046# def testTimeoutDefault(self):
1047# # global default timeout is used
1048# import socket
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001049# self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001050# socket.setdefaulttimeout(30)
1051# try:
1052# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
1053# finally:
1054# socket.setdefaulttimeout(None)
1055# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
1056# ftp.close()
1057#
1058# def testTimeoutValue(self):
1059# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
1060# timeout=30)
1061# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
1062# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001063
Skip Montanaro080c9972001-01-28 21:12:22 +00001064
1065
Brett Cannon74bfd702003-04-25 09:39:47 +00001066def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001067 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001068 urlopen_FileTests,
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001069 urlopen_HttpTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001070 urlretrieve_FileTests,
Benjamin Peterson9bc93512008-09-22 22:10:59 +00001071 ProxyTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001072 QuotingTests,
1073 UnquotingTests,
1074 urlencode_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001075 Pathname_Tests,
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001076 Utility_Tests,
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001077 URLopener_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001078 #FTPWrapperTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001079 )
Brett Cannon74bfd702003-04-25 09:39:47 +00001080
1081
1082
1083if __name__ == '__main__':
1084 test_main()