blob: 65687323cf64f4bcd3b095e2c4b9d0961e6d7aa5 [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__"):
Brett Cannon74bfd702003-04-25 09:39:47 +000066 self.assert_(hasattr(self.returned_obj, attr),
67 "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()
88 self.assert_(isinstance(file_num, int),
89 "fileno() did not return an int")
90 self.assertEqual(os.read(file_num, len(self.text)), self.text,
91 "Reading on the file descriptor returned by fileno() "
92 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +000093
Brett Cannon74bfd702003-04-25 09:39:47 +000094 def test_close(self):
95 # Test close() by calling it hear and then having it be called again
96 # by the tearDown() method for the test
97 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +000098
Brett Cannon74bfd702003-04-25 09:39:47 +000099 def test_info(self):
Barry Warsaw820c1202008-06-12 04:06:45 +0000100 self.assert_(isinstance(self.returned_obj.info(), email.message.Message))
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000101
Brett Cannon74bfd702003-04-25 09:39:47 +0000102 def test_geturl(self):
103 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +0000104
Christian Heimes9bd667a2008-01-20 15:14:11 +0000105 def test_getcode(self):
106 self.assertEqual(self.returned_obj.getcode(), None)
107
Brett Cannon74bfd702003-04-25 09:39:47 +0000108 def test_iter(self):
109 # Test iterator
110 # Don't need to count number of iterations since test would fail the
111 # instant it returned anything beyond the first line from the
112 # comparison
113 for line in self.returned_obj.__iter__():
114 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +0000115
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000116
117class ProxyTests(unittest.TestCase):
118
119 def setUp(self):
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000120 # Save all proxy related env vars
121 self._saved_environ = dict([(k, v) for k, v in os.environ.items()
122 if k.lower().find('proxy') >= 0])
123 # Delete all proxy related env vars
124 for k in self._saved_environ:
125 del os.environ[k]
126
127 def tearDown(self):
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000128 # Restore all proxy related env vars
Benjamin Peterson1a6e0d02008-10-25 15:49:17 +0000129 for k, v in self._saved_environ.items():
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000130 os.environ[k] = v
131
132 def test_getproxies_environment_keep_no_proxies(self):
133 os.environ['NO_PROXY'] = 'localhost'
134 proxies = urllib.request.getproxies_environment()
135 # getproxies_environment use lowered case truncated (no '_proxy') keys
136 self.assertEquals('localhost', proxies['no'])
137
138
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000139class urlopen_HttpTests(unittest.TestCase):
140 """Test urlopen() opening a fake http connection."""
141
142 def fakehttp(self, fakedata):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000143 class FakeSocket(io.BytesIO):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000144 def sendall(self, str): pass
145 def makefile(self, mode, name): return self
146 def read(self, amt=None):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000147 if self.closed: return b""
148 return io.BytesIO.read(self, amt)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000149 def readline(self, length=None):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000150 if self.closed: return b""
151 return io.BytesIO.readline(self, length)
Georg Brandl24420152008-05-26 16:32:26 +0000152 class FakeHTTPConnection(http.client.HTTPConnection):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000153 def connect(self):
154 self.sock = FakeSocket(fakedata)
Georg Brandl24420152008-05-26 16:32:26 +0000155 self._connection_class = http.client.HTTPConnection
156 http.client.HTTPConnection = FakeHTTPConnection
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000157
158 def unfakehttp(self):
Georg Brandl24420152008-05-26 16:32:26 +0000159 http.client.HTTPConnection = self._connection_class
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000160
161 def test_read(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000162 self.fakehttp(b"Hello!")
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000163 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000164 fp = urlopen("http://python.org/")
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000165 self.assertEqual(fp.readline(), b"Hello!")
166 self.assertEqual(fp.readline(), b"")
Christian Heimes9bd667a2008-01-20 15:14:11 +0000167 self.assertEqual(fp.geturl(), 'http://python.org/')
168 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000169 finally:
170 self.unfakehttp()
171
Christian Heimes57dddfb2008-01-02 18:30:52 +0000172 def test_read_bogus(self):
173 # urlopen() should raise IOError for many error codes.
174 self.fakehttp(b'''HTTP/1.1 401 Authentication Required
175Date: Wed, 02 Jan 2008 03:03:54 GMT
176Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
177Connection: close
178Content-Type: text/html; charset=iso-8859-1
179''')
180 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000181 self.assertRaises(IOError, urlopen, "http://python.org/")
Christian Heimes57dddfb2008-01-02 18:30:52 +0000182 finally:
183 self.unfakehttp()
184
Guido van Rossumd8faa362007-04-27 19:54:29 +0000185 def test_empty_socket(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000186 # urlopen() raises IOError if the underlying socket does not send any
187 # data. (#1680230)
Christian Heimes57dddfb2008-01-02 18:30:52 +0000188 self.fakehttp(b'')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000189 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000190 self.assertRaises(IOError, urlopen, "http://something")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000191 finally:
192 self.unfakehttp()
193
Brett Cannon19691362003-04-29 05:08:06 +0000194class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000195 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000196
Brett Cannon19691362003-04-29 05:08:06 +0000197 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000198 # Create a list of temporary files. Each item in the list is a file
199 # name (absolute path or relative to the current working directory).
200 # All files in this list will be deleted in the tearDown method. Note,
201 # this only helps to makes sure temporary files get deleted, but it
202 # does nothing about trying to close files that may still be open. It
203 # is the responsibility of the developer to properly close files even
204 # when exceptional conditions occur.
205 self.tempFiles = []
206
Brett Cannon19691362003-04-29 05:08:06 +0000207 # Create a temporary file.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000208 self.registerFileForCleanUp(support.TESTFN)
Guido van Rossuma0982942007-07-10 08:30:03 +0000209 self.text = b'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000210 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000211 FILE = open(support.TESTFN, 'wb')
Georg Brandl5a650a22005-08-26 08:51:34 +0000212 FILE.write(self.text)
213 FILE.close()
214 finally:
215 try: FILE.close()
216 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000217
218 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000219 # Delete the temporary files.
220 for each in self.tempFiles:
221 try: os.remove(each)
222 except: pass
223
224 def constructLocalFileUrl(self, filePath):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000225 return "file://%s" % urllib.request.pathname2url(
226 os.path.abspath(filePath))
Georg Brandl5a650a22005-08-26 08:51:34 +0000227
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000228 def createNewTempFile(self, data=b""):
Georg Brandl5a650a22005-08-26 08:51:34 +0000229 """Creates a new temporary file containing the specified data,
230 registers the file for deletion during the test fixture tear down, and
231 returns the absolute path of the file."""
232
233 newFd, newFilePath = tempfile.mkstemp()
234 try:
235 self.registerFileForCleanUp(newFilePath)
236 newFile = os.fdopen(newFd, "wb")
237 newFile.write(data)
238 newFile.close()
239 finally:
240 try: newFile.close()
241 except: pass
242 return newFilePath
243
244 def registerFileForCleanUp(self, fileName):
245 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000246
247 def test_basic(self):
248 # Make sure that a local file just gets its own location returned and
249 # a headers value is returned.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000250 result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000251 self.assertEqual(result[0], support.TESTFN)
Barry Warsaw820c1202008-06-12 04:06:45 +0000252 self.assert_(isinstance(result[1], email.message.Message),
253 "did not get a email.message.Message instance as second "
Brett Cannon19691362003-04-29 05:08:06 +0000254 "returned value")
255
256 def test_copy(self):
257 # Test that setting the filename argument works.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000258 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000259 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000260 result = urllib.request.urlretrieve(self.constructLocalFileUrl(
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000261 support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000262 self.assertEqual(second_temp, result[0])
263 self.assert_(os.path.exists(second_temp), "copy of the file was not "
264 "made")
Alex Martelli01c77c62006-08-24 02:58:11 +0000265 FILE = open(second_temp, 'rb')
Brett Cannon19691362003-04-29 05:08:06 +0000266 try:
267 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000268 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000269 finally:
270 try: FILE.close()
271 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000272 self.assertEqual(self.text, text)
273
274 def test_reporthook(self):
275 # Make sure that the reporthook works.
276 def hooktester(count, block_size, total_size, count_holder=[0]):
277 self.assert_(isinstance(count, int))
278 self.assert_(isinstance(block_size, int))
279 self.assert_(isinstance(total_size, int))
280 self.assertEqual(count, count_holder[0])
281 count_holder[0] = count_holder[0] + 1
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000282 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000283 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000284 urllib.request.urlretrieve(
285 self.constructLocalFileUrl(support.TESTFN),
Georg Brandl5a650a22005-08-26 08:51:34 +0000286 second_temp, hooktester)
287
288 def test_reporthook_0_bytes(self):
289 # Test on zero length file. Should call reporthook only 1 time.
290 report = []
291 def hooktester(count, block_size, total_size, _report=report):
292 _report.append((count, block_size, total_size))
293 srcFileName = self.createNewTempFile()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000294 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000295 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000296 self.assertEqual(len(report), 1)
297 self.assertEqual(report[0][2], 0)
298
299 def test_reporthook_5_bytes(self):
300 # Test on 5 byte file. Should call reporthook only 2 times (once when
301 # the "network connection" is established and once when the block is
302 # read). Since the block size is 8192 bytes, only one block read is
303 # required to read the entire file.
304 report = []
305 def hooktester(count, block_size, total_size, _report=report):
306 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000307 srcFileName = self.createNewTempFile(b"x" * 5)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000308 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000309 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000310 self.assertEqual(len(report), 2)
311 self.assertEqual(report[0][1], 8192)
312 self.assertEqual(report[0][2], 5)
313
314 def test_reporthook_8193_bytes(self):
315 # Test on 8193 byte file. Should call reporthook only 3 times (once
316 # when the "network connection" is established, once for the next 8192
317 # bytes, and once for the last byte).
318 report = []
319 def hooktester(count, block_size, total_size, _report=report):
320 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000321 srcFileName = self.createNewTempFile(b"x" * 8193)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000322 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000323 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000324 self.assertEqual(len(report), 3)
325 self.assertEqual(report[0][1], 8192)
326 self.assertEqual(report[0][2], 8193)
Skip Montanaro080c9972001-01-28 21:12:22 +0000327
Brett Cannon74bfd702003-04-25 09:39:47 +0000328class QuotingTests(unittest.TestCase):
329 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000330
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000331 According to RFC 2396 (Uniform Resource Identifiers), to escape a
332 character you write it as '%' + <2 character US-ASCII hex value>.
333 The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
334 character properly. Case does not matter on the hex letters.
Brett Cannon74bfd702003-04-25 09:39:47 +0000335
336 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000337
Brett Cannon74bfd702003-04-25 09:39:47 +0000338 Reserved characters : ";/?:@&=+$,"
339 Have special meaning in URIs and must be escaped if not being used for
340 their special meaning
341 Data characters : letters, digits, and "-_.!~*'()"
342 Unreserved and do not need to be escaped; can be, though, if desired
343 Control characters : 0x00 - 0x1F, 0x7F
344 Have no use in URIs so must be escaped
345 space : 0x20
346 Must be escaped
347 Delimiters : '<>#%"'
348 Must be escaped
349 Unwise : "{}|\^[]`"
350 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000351
Brett Cannon74bfd702003-04-25 09:39:47 +0000352 """
353
354 def test_never_quote(self):
355 # Make sure quote() does not quote letters, digits, and "_,.-"
356 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
357 "abcdefghijklmnopqrstuvwxyz",
358 "0123456789",
359 "_.-"])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000360 result = urllib.parse.quote(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000361 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000362 "using quote(): %r != %r" % (do_not_quote, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000363 result = urllib.parse.quote_plus(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000364 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000365 "using quote_plus(): %r != %r" % (do_not_quote, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000366
367 def test_default_safe(self):
368 # Test '/' is default value for 'safe' parameter
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000369 self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
Brett Cannon74bfd702003-04-25 09:39:47 +0000370
371 def test_safe(self):
372 # Test setting 'safe' parameter does what it should do
373 quote_by_default = "<>"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000374 result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000375 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000376 "using quote(): %r != %r" % (quote_by_default, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000377 result = urllib.parse.quote_plus(quote_by_default, 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,
409 "using quote(): %s should be escaped to %s, not %s" %
410 (char, hexescape(char), result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000411 result = urllib.parse.quote_plus(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000412 self.assertEqual(hexescape(char), result,
413 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000414 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000415 (char, hexescape(char), result))
416 del should_quote
417 partial_quote = "ab[]cd"
418 expected = "ab%5B%5Dcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000419 result = urllib.parse.quote(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000420 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000421 "using quote(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000422 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000423 "using quote_plus(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000424
425 def test_quoting_space(self):
426 # Make sure quote() and quote_plus() handle spaces as specified in
427 # their unique way
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000428 result = urllib.parse.quote(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000429 self.assertEqual(result, hexescape(' '),
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000430 "using quote(): %r != %r" % (result, hexescape(' ')))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000431 result = urllib.parse.quote_plus(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000432 self.assertEqual(result, '+',
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000433 "using quote_plus(): %r != +" % result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000434 given = "a b cd e f"
435 expect = given.replace(' ', hexescape(' '))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000436 result = urllib.parse.quote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000437 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000438 "using quote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000439 expect = given.replace(' ', '+')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000440 result = urllib.parse.quote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000441 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000442 "using quote_plus(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000443
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000444 def test_quoting_plus(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000445 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000446 'alpha%2Bbeta+gamma')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000447 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000448 'alpha+beta+gamma')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000449 # Test with bytes
450 self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
451 'alpha%2Bbeta+gamma')
452 # Test with safe bytes
453 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
454 'alpha+beta+gamma')
455
456 def test_quote_bytes(self):
457 # Bytes should quote directly to percent-encoded values
458 given = b"\xa2\xd8ab\xff"
459 expect = "%A2%D8ab%FF"
460 result = urllib.parse.quote(given)
461 self.assertEqual(expect, result,
462 "using quote(): %r != %r" % (expect, result))
463 # Encoding argument should raise type error on bytes input
464 self.assertRaises(TypeError, urllib.parse.quote, given,
465 encoding="latin-1")
466 # quote_from_bytes should work the same
467 result = urllib.parse.quote_from_bytes(given)
468 self.assertEqual(expect, result,
469 "using quote_from_bytes(): %r != %r"
470 % (expect, result))
471
472 def test_quote_with_unicode(self):
473 # Characters in Latin-1 range, encoded by default in UTF-8
474 given = "\xa2\xd8ab\xff"
475 expect = "%C2%A2%C3%98ab%C3%BF"
476 result = urllib.parse.quote(given)
477 self.assertEqual(expect, result,
478 "using quote(): %r != %r" % (expect, result))
479 # Characters in Latin-1 range, encoded by with None (default)
480 result = urllib.parse.quote(given, encoding=None, errors=None)
481 self.assertEqual(expect, result,
482 "using quote(): %r != %r" % (expect, result))
483 # Characters in Latin-1 range, encoded with Latin-1
484 given = "\xa2\xd8ab\xff"
485 expect = "%A2%D8ab%FF"
486 result = urllib.parse.quote(given, encoding="latin-1")
487 self.assertEqual(expect, result,
488 "using quote(): %r != %r" % (expect, result))
489 # Characters in BMP, encoded by default in UTF-8
490 given = "\u6f22\u5b57" # "Kanji"
491 expect = "%E6%BC%A2%E5%AD%97"
492 result = urllib.parse.quote(given)
493 self.assertEqual(expect, result,
494 "using quote(): %r != %r" % (expect, result))
495 # Characters in BMP, encoded with Latin-1
496 given = "\u6f22\u5b57"
497 self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
498 encoding="latin-1")
499 # Characters in BMP, encoded with Latin-1, with replace error handling
500 given = "\u6f22\u5b57"
501 expect = "%3F%3F" # "??"
502 result = urllib.parse.quote(given, encoding="latin-1",
503 errors="replace")
504 self.assertEqual(expect, result,
505 "using quote(): %r != %r" % (expect, result))
506 # Characters in BMP, Latin-1, with xmlcharref error handling
507 given = "\u6f22\u5b57"
508 expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;"
509 result = urllib.parse.quote(given, encoding="latin-1",
510 errors="xmlcharrefreplace")
511 self.assertEqual(expect, result,
512 "using quote(): %r != %r" % (expect, result))
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000513
Brett Cannon74bfd702003-04-25 09:39:47 +0000514class UnquotingTests(unittest.TestCase):
515 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000516
Brett Cannon74bfd702003-04-25 09:39:47 +0000517 See the doc string for quoting_Tests for details on quoting and such.
518
519 """
520
521 def test_unquoting(self):
522 # Make sure unquoting of all ASCII values works
523 escape_list = []
524 for num in range(128):
525 given = hexescape(chr(num))
526 expect = chr(num)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000527 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000528 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000529 "using unquote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000530 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000531 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000532 "using unquote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000533 (expect, result))
534 escape_list.append(given)
535 escape_string = ''.join(escape_list)
536 del escape_list
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000537 result = urllib.parse.unquote(escape_string)
Brett Cannon74bfd702003-04-25 09:39:47 +0000538 self.assertEqual(result.count('%'), 1,
Brett Cannon74bfd702003-04-25 09:39:47 +0000539 "using unquote(): not all characters escaped: "
540 "%s" % result)
541
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000542 def test_unquoting_badpercent(self):
543 # Test unquoting on bad percent-escapes
544 given = '%xab'
545 expect = given
546 result = urllib.parse.unquote(given)
547 self.assertEqual(expect, result, "using unquote(): %r != %r"
548 % (expect, result))
549 given = '%x'
550 expect = given
551 result = urllib.parse.unquote(given)
552 self.assertEqual(expect, result, "using unquote(): %r != %r"
553 % (expect, result))
554 given = '%'
555 expect = given
556 result = urllib.parse.unquote(given)
557 self.assertEqual(expect, result, "using unquote(): %r != %r"
558 % (expect, result))
559 # unquote_to_bytes
560 given = '%xab'
561 expect = bytes(given, 'ascii')
562 result = urllib.parse.unquote_to_bytes(given)
563 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
564 % (expect, result))
565 given = '%x'
566 expect = bytes(given, 'ascii')
567 result = urllib.parse.unquote_to_bytes(given)
568 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
569 % (expect, result))
570 given = '%'
571 expect = bytes(given, 'ascii')
572 result = urllib.parse.unquote_to_bytes(given)
573 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
574 % (expect, result))
575
576 def test_unquoting_mixed_case(self):
577 # Test unquoting on mixed-case hex digits in the percent-escapes
578 given = '%Ab%eA'
579 expect = b'\xab\xea'
580 result = urllib.parse.unquote_to_bytes(given)
581 self.assertEqual(expect, result,
582 "using unquote_to_bytes(): %r != %r"
583 % (expect, result))
584
Brett Cannon74bfd702003-04-25 09:39:47 +0000585 def test_unquoting_parts(self):
586 # Make sure unquoting works when have non-quoted characters
587 # interspersed
588 given = 'ab%sd' % hexescape('c')
589 expect = "abcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000590 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000591 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000592 "using quote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000593 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000594 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000595 "using unquote_plus(): %r != %r" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000596
Brett Cannon74bfd702003-04-25 09:39:47 +0000597 def test_unquoting_plus(self):
598 # Test difference between unquote() and unquote_plus()
599 given = "are+there+spaces..."
600 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000601 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000602 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000603 "using unquote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000604 expect = given.replace('+', ' ')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000605 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000606 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000607 "using unquote_plus(): %r != %r" % (expect, result))
608
609 def test_unquote_to_bytes(self):
610 given = 'br%C3%BCckner_sapporo_20050930.doc'
611 expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
612 result = urllib.parse.unquote_to_bytes(given)
613 self.assertEqual(expect, result,
614 "using unquote_to_bytes(): %r != %r"
615 % (expect, result))
616 # Test on a string with unescaped non-ASCII characters
617 # (Technically an invalid URI; expect those characters to be UTF-8
618 # encoded).
619 result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
620 expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
621 self.assertEqual(expect, result,
622 "using unquote_to_bytes(): %r != %r"
623 % (expect, result))
624 # Test with a bytes as input
625 given = b'%A2%D8ab%FF'
626 expect = b'\xa2\xd8ab\xff'
627 result = urllib.parse.unquote_to_bytes(given)
628 self.assertEqual(expect, result,
629 "using unquote_to_bytes(): %r != %r"
630 % (expect, result))
631 # Test with a bytes as input, with unescaped non-ASCII bytes
632 # (Technically an invalid URI; expect those bytes to be preserved)
633 given = b'%A2\xd8ab%FF'
634 expect = b'\xa2\xd8ab\xff'
635 result = urllib.parse.unquote_to_bytes(given)
636 self.assertEqual(expect, result,
637 "using unquote_to_bytes(): %r != %r"
638 % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000639
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000640 def test_unquote_with_unicode(self):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000641 # Characters in the Latin-1 range, encoded with UTF-8
642 given = 'br%C3%BCckner_sapporo_20050930.doc'
643 expect = 'br\u00fcckner_sapporo_20050930.doc'
644 result = urllib.parse.unquote(given)
645 self.assertEqual(expect, result,
646 "using unquote(): %r != %r" % (expect, result))
647 # Characters in the Latin-1 range, encoded with None (default)
648 result = urllib.parse.unquote(given, encoding=None, errors=None)
649 self.assertEqual(expect, result,
650 "using unquote(): %r != %r" % (expect, result))
651
652 # Characters in the Latin-1 range, encoded with Latin-1
653 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
654 encoding="latin-1")
655 expect = 'br\u00fcckner_sapporo_20050930.doc'
656 self.assertEqual(expect, result,
657 "using unquote(): %r != %r" % (expect, result))
658
659 # Characters in BMP, encoded with UTF-8
660 given = "%E6%BC%A2%E5%AD%97"
661 expect = "\u6f22\u5b57" # "Kanji"
662 result = urllib.parse.unquote(given)
663 self.assertEqual(expect, result,
664 "using unquote(): %r != %r" % (expect, result))
665
666 # Decode with UTF-8, invalid sequence
667 given = "%F3%B1"
668 expect = "\ufffd" # Replacement character
669 result = urllib.parse.unquote(given)
670 self.assertEqual(expect, result,
671 "using unquote(): %r != %r" % (expect, result))
672
673 # Decode with UTF-8, invalid sequence, replace errors
674 result = urllib.parse.unquote(given, errors="replace")
675 self.assertEqual(expect, result,
676 "using unquote(): %r != %r" % (expect, result))
677
678 # Decode with UTF-8, invalid sequence, ignoring errors
679 given = "%F3%B1"
680 expect = ""
681 result = urllib.parse.unquote(given, errors="ignore")
682 self.assertEqual(expect, result,
683 "using unquote(): %r != %r" % (expect, result))
684
685 # A mix of non-ASCII and percent-encoded characters, UTF-8
686 result = urllib.parse.unquote("\u6f22%C3%BC")
687 expect = '\u6f22\u00fc'
688 self.assertEqual(expect, result,
689 "using unquote(): %r != %r" % (expect, result))
690
691 # A mix of non-ASCII and percent-encoded characters, Latin-1
692 # (Note, the string contains non-Latin-1-representable characters)
693 result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
694 expect = '\u6f22\u00fc'
695 self.assertEqual(expect, result,
696 "using unquote(): %r != %r" % (expect, result))
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000697
Brett Cannon74bfd702003-04-25 09:39:47 +0000698class urlencode_Tests(unittest.TestCase):
699 """Tests for urlencode()"""
700
701 def help_inputtype(self, given, test_type):
702 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000703
Brett Cannon74bfd702003-04-25 09:39:47 +0000704 'given' must lead to only the pairs:
705 * 1st, 1
706 * 2nd, 2
707 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000708
Brett Cannon74bfd702003-04-25 09:39:47 +0000709 Test cannot assume anything about order. Docs make no guarantee and
710 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000711
Brett Cannon74bfd702003-04-25 09:39:47 +0000712 """
713 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000714 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000715 for expected in expect_somewhere:
716 self.assert_(expected in result,
717 "testing %s: %s not found in %s" %
718 (test_type, expected, result))
719 self.assertEqual(result.count('&'), 2,
720 "testing %s: expected 2 '&'s; got %s" %
721 (test_type, result.count('&')))
722 amp_location = result.index('&')
723 on_amp_left = result[amp_location - 1]
724 on_amp_right = result[amp_location + 1]
725 self.assert_(on_amp_left.isdigit() and on_amp_right.isdigit(),
726 "testing %s: '&' not located in proper place in %s" %
727 (test_type, result))
728 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
729 "testing %s: "
730 "unexpected number of characters: %s != %s" %
731 (test_type, len(result), (5 * 3) + 2))
732
733 def test_using_mapping(self):
734 # Test passing in a mapping object as an argument.
735 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
736 "using dict as input type")
737
738 def test_using_sequence(self):
739 # Test passing in a sequence of two-item sequences as an argument.
740 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
741 "using sequence of two-item tuples as input")
742
743 def test_quoting(self):
744 # Make sure keys and values are quoted using quote_plus()
745 given = {"&":"="}
746 expect = "%s=%s" % (hexescape('&'), hexescape('='))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000747 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000748 self.assertEqual(expect, result)
749 given = {"key name":"A bunch of pluses"}
750 expect = "key+name=A+bunch+of+pluses"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000751 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000752 self.assertEqual(expect, result)
753
754 def test_doseq(self):
755 # Test that passing True for 'doseq' parameter works correctly
756 given = {'sequence':['1', '2', '3']}
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000757 expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
758 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000759 self.assertEqual(expect, result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000760 result = urllib.parse.urlencode(given, True)
Brett Cannon74bfd702003-04-25 09:39:47 +0000761 for value in given["sequence"]:
762 expect = "sequence=%s" % value
763 self.assert_(expect in result,
764 "%s not found in %s" % (expect, result))
765 self.assertEqual(result.count('&'), 2,
766 "Expected 2 '&'s, got %s" % result.count('&'))
767
768class Pathname_Tests(unittest.TestCase):
769 """Test pathname2url() and url2pathname()"""
770
771 def test_basic(self):
772 # Make sure simple tests pass
773 expected_path = os.path.join("parts", "of", "a", "path")
774 expected_url = "parts/of/a/path"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000775 result = urllib.request.pathname2url(expected_path)
Brett Cannon74bfd702003-04-25 09:39:47 +0000776 self.assertEqual(expected_url, result,
777 "pathname2url() failed; %s != %s" %
778 (result, expected_url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000779 result = urllib.request.url2pathname(expected_url)
Brett Cannon74bfd702003-04-25 09:39:47 +0000780 self.assertEqual(expected_path, result,
781 "url2pathame() failed; %s != %s" %
782 (result, expected_path))
783
784 def test_quoting(self):
785 # Test automatic quoting and unquoting works for pathnam2url() and
786 # url2pathname() respectively
787 given = os.path.join("needs", "quot=ing", "here")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000788 expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
789 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000790 self.assertEqual(expect, result,
791 "pathname2url() failed; %s != %s" %
792 (expect, result))
793 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000794 result = urllib.request.url2pathname(result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000795 self.assertEqual(expect, result,
796 "url2pathname() failed; %s != %s" %
797 (expect, result))
798 given = os.path.join("make sure", "using_quote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000799 expect = "%s/using_quote" % urllib.parse.quote("make sure")
800 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000801 self.assertEqual(expect, result,
802 "pathname2url() failed; %s != %s" %
803 (expect, result))
804 given = "make+sure/using_unquote"
805 expect = os.path.join("make+sure", "using_unquote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000806 result = urllib.request.url2pathname(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000807 self.assertEqual(expect, result,
808 "url2pathname() failed; %s != %s" %
809 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000810
Guido van Rossume7ba4952007-06-06 23:52:48 +0000811# Just commented them out.
812# Can't really tell why keep failing in windows and sparc.
813# Everywhere else they work ok, but on those machines, someteimes
814# fail in one of the tests, sometimes in other. I have a linux, and
815# the tests go ok.
816# If anybody has one of the problematic enviroments, please help!
817# . Facundo
818#
819# def server(evt):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000820# import socket, time
Guido van Rossume7ba4952007-06-06 23:52:48 +0000821# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
822# serv.settimeout(3)
823# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
824# serv.bind(("", 9093))
825# serv.listen(5)
826# try:
827# conn, addr = serv.accept()
828# conn.send("1 Hola mundo\n")
829# cantdata = 0
830# while cantdata < 13:
831# data = conn.recv(13-cantdata)
832# cantdata += len(data)
833# time.sleep(.3)
834# conn.send("2 No more lines\n")
835# conn.close()
836# except socket.timeout:
837# pass
838# finally:
839# serv.close()
840# evt.set()
841#
842# class FTPWrapperTests(unittest.TestCase):
843#
844# def setUp(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000845# import ftplib, time, threading
Guido van Rossume7ba4952007-06-06 23:52:48 +0000846# ftplib.FTP.port = 9093
847# self.evt = threading.Event()
848# threading.Thread(target=server, args=(self.evt,)).start()
849# time.sleep(.1)
850#
851# def tearDown(self):
852# self.evt.wait()
853#
854# def testBasic(self):
855# # connects
856# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Georg Brandlf78e02b2008-06-10 17:40:04 +0000857# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000858#
859# def testTimeoutNone(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000860# # global default timeout is ignored
861# import socket
862# self.assert_(socket.getdefaulttimeout() is None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000863# socket.setdefaulttimeout(30)
864# try:
865# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
866# finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000867# socket.setdefaulttimeout(None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000868# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000869# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000870#
Georg Brandlf78e02b2008-06-10 17:40:04 +0000871# def testTimeoutDefault(self):
872# # global default timeout is used
873# import socket
874# self.assert_(socket.getdefaulttimeout() is None)
875# socket.setdefaulttimeout(30)
876# try:
877# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
878# finally:
879# socket.setdefaulttimeout(None)
880# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
881# ftp.close()
882#
883# def testTimeoutValue(self):
884# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
885# timeout=30)
886# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
887# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000888
Skip Montanaro080c9972001-01-28 21:12:22 +0000889
890
Brett Cannon74bfd702003-04-25 09:39:47 +0000891def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000892 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000893 urlopen_FileTests,
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000894 urlopen_HttpTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000895 urlretrieve_FileTests,
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000896 ProxyTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000897 QuotingTests,
898 UnquotingTests,
899 urlencode_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000900 Pathname_Tests,
901 #FTPWrapperTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000902 )
Brett Cannon74bfd702003-04-25 09:39:47 +0000903
904
905
906if __name__ == '__main__':
907 test_main()