blob: 857634762f698c6af34ad3b4233555184071344c [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):
120 unittest.TestCase.setUp(self)
121 # Save all proxy related env vars
122 self._saved_environ = dict([(k, v) for k, v in os.environ.items()
123 if k.lower().find('proxy') >= 0])
124 # Delete all proxy related env vars
125 for k in self._saved_environ:
126 del os.environ[k]
127
128 def tearDown(self):
129 unittest.TestCase.tearDown(self)
130 # Restore all proxy related env vars
131 for k, v in self._saved_environ:
132 os.environ[k] = v
133
134 def test_getproxies_environment_keep_no_proxies(self):
135 os.environ['NO_PROXY'] = 'localhost'
136 proxies = urllib.request.getproxies_environment()
137 # getproxies_environment use lowered case truncated (no '_proxy') keys
138 self.assertEquals('localhost', proxies['no'])
139
140
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000141class urlopen_HttpTests(unittest.TestCase):
142 """Test urlopen() opening a fake http connection."""
143
144 def fakehttp(self, fakedata):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000145 class FakeSocket(io.BytesIO):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000146 def sendall(self, str): pass
147 def makefile(self, mode, name): return self
148 def read(self, amt=None):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000149 if self.closed: return b""
150 return io.BytesIO.read(self, amt)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000151 def readline(self, length=None):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000152 if self.closed: return b""
153 return io.BytesIO.readline(self, length)
Georg Brandl24420152008-05-26 16:32:26 +0000154 class FakeHTTPConnection(http.client.HTTPConnection):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000155 def connect(self):
156 self.sock = FakeSocket(fakedata)
Georg Brandl24420152008-05-26 16:32:26 +0000157 self._connection_class = http.client.HTTPConnection
158 http.client.HTTPConnection = FakeHTTPConnection
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000159
160 def unfakehttp(self):
Georg Brandl24420152008-05-26 16:32:26 +0000161 http.client.HTTPConnection = self._connection_class
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000162
163 def test_read(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000164 self.fakehttp(b"Hello!")
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000165 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000166 fp = urlopen("http://python.org/")
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000167 self.assertEqual(fp.readline(), b"Hello!")
168 self.assertEqual(fp.readline(), b"")
Christian Heimes9bd667a2008-01-20 15:14:11 +0000169 self.assertEqual(fp.geturl(), 'http://python.org/')
170 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000171 finally:
172 self.unfakehttp()
173
Christian Heimes57dddfb2008-01-02 18:30:52 +0000174 def test_read_bogus(self):
175 # urlopen() should raise IOError for many error codes.
176 self.fakehttp(b'''HTTP/1.1 401 Authentication Required
177Date: Wed, 02 Jan 2008 03:03:54 GMT
178Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
179Connection: close
180Content-Type: text/html; charset=iso-8859-1
181''')
182 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000183 self.assertRaises(IOError, urlopen, "http://python.org/")
Christian Heimes57dddfb2008-01-02 18:30:52 +0000184 finally:
185 self.unfakehttp()
186
Guido van Rossumd8faa362007-04-27 19:54:29 +0000187 def test_empty_socket(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000188 # urlopen() raises IOError if the underlying socket does not send any
189 # data. (#1680230)
Christian Heimes57dddfb2008-01-02 18:30:52 +0000190 self.fakehttp(b'')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000191 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000192 self.assertRaises(IOError, urlopen, "http://something")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000193 finally:
194 self.unfakehttp()
195
Brett Cannon19691362003-04-29 05:08:06 +0000196class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000197 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000198
Brett Cannon19691362003-04-29 05:08:06 +0000199 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000200 # Create a list of temporary files. Each item in the list is a file
201 # name (absolute path or relative to the current working directory).
202 # All files in this list will be deleted in the tearDown method. Note,
203 # this only helps to makes sure temporary files get deleted, but it
204 # does nothing about trying to close files that may still be open. It
205 # is the responsibility of the developer to properly close files even
206 # when exceptional conditions occur.
207 self.tempFiles = []
208
Brett Cannon19691362003-04-29 05:08:06 +0000209 # Create a temporary file.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000210 self.registerFileForCleanUp(support.TESTFN)
Guido van Rossuma0982942007-07-10 08:30:03 +0000211 self.text = b'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000212 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000213 FILE = open(support.TESTFN, 'wb')
Georg Brandl5a650a22005-08-26 08:51:34 +0000214 FILE.write(self.text)
215 FILE.close()
216 finally:
217 try: FILE.close()
218 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000219
220 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000221 # Delete the temporary files.
222 for each in self.tempFiles:
223 try: os.remove(each)
224 except: pass
225
226 def constructLocalFileUrl(self, filePath):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000227 return "file://%s" % urllib.request.pathname2url(
228 os.path.abspath(filePath))
Georg Brandl5a650a22005-08-26 08:51:34 +0000229
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000230 def createNewTempFile(self, data=b""):
Georg Brandl5a650a22005-08-26 08:51:34 +0000231 """Creates a new temporary file containing the specified data,
232 registers the file for deletion during the test fixture tear down, and
233 returns the absolute path of the file."""
234
235 newFd, newFilePath = tempfile.mkstemp()
236 try:
237 self.registerFileForCleanUp(newFilePath)
238 newFile = os.fdopen(newFd, "wb")
239 newFile.write(data)
240 newFile.close()
241 finally:
242 try: newFile.close()
243 except: pass
244 return newFilePath
245
246 def registerFileForCleanUp(self, fileName):
247 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000248
249 def test_basic(self):
250 # Make sure that a local file just gets its own location returned and
251 # a headers value is returned.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000252 result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000253 self.assertEqual(result[0], support.TESTFN)
Barry Warsaw820c1202008-06-12 04:06:45 +0000254 self.assert_(isinstance(result[1], email.message.Message),
255 "did not get a email.message.Message instance as second "
Brett Cannon19691362003-04-29 05:08:06 +0000256 "returned value")
257
258 def test_copy(self):
259 # Test that setting the filename argument works.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000260 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000261 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000262 result = urllib.request.urlretrieve(self.constructLocalFileUrl(
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000263 support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000264 self.assertEqual(second_temp, result[0])
265 self.assert_(os.path.exists(second_temp), "copy of the file was not "
266 "made")
Alex Martelli01c77c62006-08-24 02:58:11 +0000267 FILE = open(second_temp, 'rb')
Brett Cannon19691362003-04-29 05:08:06 +0000268 try:
269 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000270 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000271 finally:
272 try: FILE.close()
273 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000274 self.assertEqual(self.text, text)
275
276 def test_reporthook(self):
277 # Make sure that the reporthook works.
278 def hooktester(count, block_size, total_size, count_holder=[0]):
279 self.assert_(isinstance(count, int))
280 self.assert_(isinstance(block_size, int))
281 self.assert_(isinstance(total_size, int))
282 self.assertEqual(count, count_holder[0])
283 count_holder[0] = count_holder[0] + 1
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000284 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000285 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000286 urllib.request.urlretrieve(
287 self.constructLocalFileUrl(support.TESTFN),
Georg Brandl5a650a22005-08-26 08:51:34 +0000288 second_temp, hooktester)
289
290 def test_reporthook_0_bytes(self):
291 # Test on zero length file. Should call reporthook only 1 time.
292 report = []
293 def hooktester(count, block_size, total_size, _report=report):
294 _report.append((count, block_size, total_size))
295 srcFileName = self.createNewTempFile()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000296 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000297 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000298 self.assertEqual(len(report), 1)
299 self.assertEqual(report[0][2], 0)
300
301 def test_reporthook_5_bytes(self):
302 # Test on 5 byte file. Should call reporthook only 2 times (once when
303 # the "network connection" is established and once when the block is
304 # read). Since the block size is 8192 bytes, only one block read is
305 # required to read the entire file.
306 report = []
307 def hooktester(count, block_size, total_size, _report=report):
308 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000309 srcFileName = self.createNewTempFile(b"x" * 5)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000310 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000311 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000312 self.assertEqual(len(report), 2)
313 self.assertEqual(report[0][1], 8192)
314 self.assertEqual(report[0][2], 5)
315
316 def test_reporthook_8193_bytes(self):
317 # Test on 8193 byte file. Should call reporthook only 3 times (once
318 # when the "network connection" is established, once for the next 8192
319 # bytes, and once for the last byte).
320 report = []
321 def hooktester(count, block_size, total_size, _report=report):
322 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000323 srcFileName = self.createNewTempFile(b"x" * 8193)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000324 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000325 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000326 self.assertEqual(len(report), 3)
327 self.assertEqual(report[0][1], 8192)
328 self.assertEqual(report[0][2], 8193)
Skip Montanaro080c9972001-01-28 21:12:22 +0000329
Brett Cannon74bfd702003-04-25 09:39:47 +0000330class QuotingTests(unittest.TestCase):
331 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000332
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000333 According to RFC 2396 (Uniform Resource Identifiers), to escape a
334 character you write it as '%' + <2 character US-ASCII hex value>.
335 The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
336 character properly. Case does not matter on the hex letters.
Brett Cannon74bfd702003-04-25 09:39:47 +0000337
338 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000339
Brett Cannon74bfd702003-04-25 09:39:47 +0000340 Reserved characters : ";/?:@&=+$,"
341 Have special meaning in URIs and must be escaped if not being used for
342 their special meaning
343 Data characters : letters, digits, and "-_.!~*'()"
344 Unreserved and do not need to be escaped; can be, though, if desired
345 Control characters : 0x00 - 0x1F, 0x7F
346 Have no use in URIs so must be escaped
347 space : 0x20
348 Must be escaped
349 Delimiters : '<>#%"'
350 Must be escaped
351 Unwise : "{}|\^[]`"
352 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000353
Brett Cannon74bfd702003-04-25 09:39:47 +0000354 """
355
356 def test_never_quote(self):
357 # Make sure quote() does not quote letters, digits, and "_,.-"
358 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
359 "abcdefghijklmnopqrstuvwxyz",
360 "0123456789",
361 "_.-"])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000362 result = urllib.parse.quote(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(): %r != %r" % (do_not_quote, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000365 result = urllib.parse.quote_plus(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000366 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000367 "using quote_plus(): %r != %r" % (do_not_quote, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000368
369 def test_default_safe(self):
370 # Test '/' is default value for 'safe' parameter
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000371 self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
Brett Cannon74bfd702003-04-25 09:39:47 +0000372
373 def test_safe(self):
374 # Test setting 'safe' parameter does what it should do
375 quote_by_default = "<>"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000376 result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000377 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000378 "using quote(): %r != %r" % (quote_by_default, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000379 result = urllib.parse.quote_plus(quote_by_default, safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000380 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000381 "using quote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000382 (quote_by_default, result))
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000383 # Safe expressed as bytes rather than str
384 result = urllib.parse.quote(quote_by_default, safe=b"<>")
385 self.assertEqual(quote_by_default, result,
386 "using quote(): %r != %r" % (quote_by_default, result))
387 # "Safe" non-ASCII characters should have no effect
388 # (Since URIs are not allowed to have non-ASCII characters)
389 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc")
390 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
391 self.assertEqual(expect, result,
392 "using quote(): %r != %r" %
393 (expect, result))
394 # Same as above, but using a bytes rather than str
395 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc")
396 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
397 self.assertEqual(expect, result,
398 "using quote(): %r != %r" %
399 (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000400
401 def test_default_quoting(self):
402 # Make sure all characters that should be quoted are by default sans
403 # space (separate test for that).
404 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
405 should_quote.append('<>#%"{}|\^[]`')
406 should_quote.append(chr(127)) # For 0x7F
407 should_quote = ''.join(should_quote)
408 for char in should_quote:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000409 result = urllib.parse.quote(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000410 self.assertEqual(hexescape(char), result,
411 "using quote(): %s should be escaped to %s, not %s" %
412 (char, hexescape(char), result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000413 result = urllib.parse.quote_plus(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000414 self.assertEqual(hexescape(char), result,
415 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000416 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000417 (char, hexescape(char), result))
418 del should_quote
419 partial_quote = "ab[]cd"
420 expected = "ab%5B%5Dcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000421 result = urllib.parse.quote(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000422 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000423 "using quote(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000424 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000425 "using quote_plus(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000426
427 def test_quoting_space(self):
428 # Make sure quote() and quote_plus() handle spaces as specified in
429 # their unique way
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000430 result = urllib.parse.quote(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000431 self.assertEqual(result, hexescape(' '),
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000432 "using quote(): %r != %r" % (result, hexescape(' ')))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000433 result = urllib.parse.quote_plus(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000434 self.assertEqual(result, '+',
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000435 "using quote_plus(): %r != +" % result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000436 given = "a b cd e f"
437 expect = given.replace(' ', hexescape(' '))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000438 result = urllib.parse.quote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000439 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000440 "using quote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000441 expect = given.replace(' ', '+')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000442 result = urllib.parse.quote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000443 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000444 "using quote_plus(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000445
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000446 def test_quoting_plus(self):
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%2Bbeta+gamma')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000449 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000450 'alpha+beta+gamma')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000451 # Test with bytes
452 self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
453 'alpha%2Bbeta+gamma')
454 # Test with safe bytes
455 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
456 'alpha+beta+gamma')
457
458 def test_quote_bytes(self):
459 # Bytes should quote directly to percent-encoded values
460 given = b"\xa2\xd8ab\xff"
461 expect = "%A2%D8ab%FF"
462 result = urllib.parse.quote(given)
463 self.assertEqual(expect, result,
464 "using quote(): %r != %r" % (expect, result))
465 # Encoding argument should raise type error on bytes input
466 self.assertRaises(TypeError, urllib.parse.quote, given,
467 encoding="latin-1")
468 # quote_from_bytes should work the same
469 result = urllib.parse.quote_from_bytes(given)
470 self.assertEqual(expect, result,
471 "using quote_from_bytes(): %r != %r"
472 % (expect, result))
473
474 def test_quote_with_unicode(self):
475 # Characters in Latin-1 range, encoded by default in UTF-8
476 given = "\xa2\xd8ab\xff"
477 expect = "%C2%A2%C3%98ab%C3%BF"
478 result = urllib.parse.quote(given)
479 self.assertEqual(expect, result,
480 "using quote(): %r != %r" % (expect, result))
481 # Characters in Latin-1 range, encoded by with None (default)
482 result = urllib.parse.quote(given, encoding=None, errors=None)
483 self.assertEqual(expect, result,
484 "using quote(): %r != %r" % (expect, result))
485 # Characters in Latin-1 range, encoded with Latin-1
486 given = "\xa2\xd8ab\xff"
487 expect = "%A2%D8ab%FF"
488 result = urllib.parse.quote(given, encoding="latin-1")
489 self.assertEqual(expect, result,
490 "using quote(): %r != %r" % (expect, result))
491 # Characters in BMP, encoded by default in UTF-8
492 given = "\u6f22\u5b57" # "Kanji"
493 expect = "%E6%BC%A2%E5%AD%97"
494 result = urllib.parse.quote(given)
495 self.assertEqual(expect, result,
496 "using quote(): %r != %r" % (expect, result))
497 # Characters in BMP, encoded with Latin-1
498 given = "\u6f22\u5b57"
499 self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
500 encoding="latin-1")
501 # Characters in BMP, encoded with Latin-1, with replace error handling
502 given = "\u6f22\u5b57"
503 expect = "%3F%3F" # "??"
504 result = urllib.parse.quote(given, encoding="latin-1",
505 errors="replace")
506 self.assertEqual(expect, result,
507 "using quote(): %r != %r" % (expect, result))
508 # Characters in BMP, Latin-1, with xmlcharref error handling
509 given = "\u6f22\u5b57"
510 expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;"
511 result = urllib.parse.quote(given, encoding="latin-1",
512 errors="xmlcharrefreplace")
513 self.assertEqual(expect, result,
514 "using quote(): %r != %r" % (expect, result))
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000515
Brett Cannon74bfd702003-04-25 09:39:47 +0000516class UnquotingTests(unittest.TestCase):
517 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000518
Brett Cannon74bfd702003-04-25 09:39:47 +0000519 See the doc string for quoting_Tests for details on quoting and such.
520
521 """
522
523 def test_unquoting(self):
524 # Make sure unquoting of all ASCII values works
525 escape_list = []
526 for num in range(128):
527 given = hexescape(chr(num))
528 expect = chr(num)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000529 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000530 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000531 "using unquote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000532 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000533 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000534 "using unquote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000535 (expect, result))
536 escape_list.append(given)
537 escape_string = ''.join(escape_list)
538 del escape_list
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000539 result = urllib.parse.unquote(escape_string)
Brett Cannon74bfd702003-04-25 09:39:47 +0000540 self.assertEqual(result.count('%'), 1,
Brett Cannon74bfd702003-04-25 09:39:47 +0000541 "using unquote(): not all characters escaped: "
542 "%s" % result)
543
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000544 def test_unquoting_badpercent(self):
545 # Test unquoting on bad percent-escapes
546 given = '%xab'
547 expect = given
548 result = urllib.parse.unquote(given)
549 self.assertEqual(expect, result, "using unquote(): %r != %r"
550 % (expect, result))
551 given = '%x'
552 expect = given
553 result = urllib.parse.unquote(given)
554 self.assertEqual(expect, result, "using unquote(): %r != %r"
555 % (expect, result))
556 given = '%'
557 expect = given
558 result = urllib.parse.unquote(given)
559 self.assertEqual(expect, result, "using unquote(): %r != %r"
560 % (expect, result))
561 # unquote_to_bytes
562 given = '%xab'
563 expect = bytes(given, 'ascii')
564 result = urllib.parse.unquote_to_bytes(given)
565 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
566 % (expect, result))
567 given = '%x'
568 expect = bytes(given, 'ascii')
569 result = urllib.parse.unquote_to_bytes(given)
570 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
571 % (expect, result))
572 given = '%'
573 expect = bytes(given, 'ascii')
574 result = urllib.parse.unquote_to_bytes(given)
575 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
576 % (expect, result))
577
578 def test_unquoting_mixed_case(self):
579 # Test unquoting on mixed-case hex digits in the percent-escapes
580 given = '%Ab%eA'
581 expect = b'\xab\xea'
582 result = urllib.parse.unquote_to_bytes(given)
583 self.assertEqual(expect, result,
584 "using unquote_to_bytes(): %r != %r"
585 % (expect, result))
586
Brett Cannon74bfd702003-04-25 09:39:47 +0000587 def test_unquoting_parts(self):
588 # Make sure unquoting works when have non-quoted characters
589 # interspersed
590 given = 'ab%sd' % hexescape('c')
591 expect = "abcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000592 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000593 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000594 "using quote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000595 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000596 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000597 "using unquote_plus(): %r != %r" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000598
Brett Cannon74bfd702003-04-25 09:39:47 +0000599 def test_unquoting_plus(self):
600 # Test difference between unquote() and unquote_plus()
601 given = "are+there+spaces..."
602 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000603 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000604 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000605 "using unquote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000606 expect = given.replace('+', ' ')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000607 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000608 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000609 "using unquote_plus(): %r != %r" % (expect, result))
610
611 def test_unquote_to_bytes(self):
612 given = 'br%C3%BCckner_sapporo_20050930.doc'
613 expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
614 result = urllib.parse.unquote_to_bytes(given)
615 self.assertEqual(expect, result,
616 "using unquote_to_bytes(): %r != %r"
617 % (expect, result))
618 # Test on a string with unescaped non-ASCII characters
619 # (Technically an invalid URI; expect those characters to be UTF-8
620 # encoded).
621 result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
622 expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
623 self.assertEqual(expect, result,
624 "using unquote_to_bytes(): %r != %r"
625 % (expect, result))
626 # Test with a bytes as input
627 given = b'%A2%D8ab%FF'
628 expect = b'\xa2\xd8ab\xff'
629 result = urllib.parse.unquote_to_bytes(given)
630 self.assertEqual(expect, result,
631 "using unquote_to_bytes(): %r != %r"
632 % (expect, result))
633 # Test with a bytes as input, with unescaped non-ASCII bytes
634 # (Technically an invalid URI; expect those bytes to be preserved)
635 given = b'%A2\xd8ab%FF'
636 expect = b'\xa2\xd8ab\xff'
637 result = urllib.parse.unquote_to_bytes(given)
638 self.assertEqual(expect, result,
639 "using unquote_to_bytes(): %r != %r"
640 % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000641
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000642 def test_unquote_with_unicode(self):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000643 # Characters in the Latin-1 range, encoded with UTF-8
644 given = 'br%C3%BCckner_sapporo_20050930.doc'
645 expect = 'br\u00fcckner_sapporo_20050930.doc'
646 result = urllib.parse.unquote(given)
647 self.assertEqual(expect, result,
648 "using unquote(): %r != %r" % (expect, result))
649 # Characters in the Latin-1 range, encoded with None (default)
650 result = urllib.parse.unquote(given, encoding=None, errors=None)
651 self.assertEqual(expect, result,
652 "using unquote(): %r != %r" % (expect, result))
653
654 # Characters in the Latin-1 range, encoded with Latin-1
655 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
656 encoding="latin-1")
657 expect = 'br\u00fcckner_sapporo_20050930.doc'
658 self.assertEqual(expect, result,
659 "using unquote(): %r != %r" % (expect, result))
660
661 # Characters in BMP, encoded with UTF-8
662 given = "%E6%BC%A2%E5%AD%97"
663 expect = "\u6f22\u5b57" # "Kanji"
664 result = urllib.parse.unquote(given)
665 self.assertEqual(expect, result,
666 "using unquote(): %r != %r" % (expect, result))
667
668 # Decode with UTF-8, invalid sequence
669 given = "%F3%B1"
670 expect = "\ufffd" # Replacement character
671 result = urllib.parse.unquote(given)
672 self.assertEqual(expect, result,
673 "using unquote(): %r != %r" % (expect, result))
674
675 # Decode with UTF-8, invalid sequence, replace errors
676 result = urllib.parse.unquote(given, errors="replace")
677 self.assertEqual(expect, result,
678 "using unquote(): %r != %r" % (expect, result))
679
680 # Decode with UTF-8, invalid sequence, ignoring errors
681 given = "%F3%B1"
682 expect = ""
683 result = urllib.parse.unquote(given, errors="ignore")
684 self.assertEqual(expect, result,
685 "using unquote(): %r != %r" % (expect, result))
686
687 # A mix of non-ASCII and percent-encoded characters, UTF-8
688 result = urllib.parse.unquote("\u6f22%C3%BC")
689 expect = '\u6f22\u00fc'
690 self.assertEqual(expect, result,
691 "using unquote(): %r != %r" % (expect, result))
692
693 # A mix of non-ASCII and percent-encoded characters, Latin-1
694 # (Note, the string contains non-Latin-1-representable characters)
695 result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
696 expect = '\u6f22\u00fc'
697 self.assertEqual(expect, result,
698 "using unquote(): %r != %r" % (expect, result))
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000699
Brett Cannon74bfd702003-04-25 09:39:47 +0000700class urlencode_Tests(unittest.TestCase):
701 """Tests for urlencode()"""
702
703 def help_inputtype(self, given, test_type):
704 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000705
Brett Cannon74bfd702003-04-25 09:39:47 +0000706 'given' must lead to only the pairs:
707 * 1st, 1
708 * 2nd, 2
709 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000710
Brett Cannon74bfd702003-04-25 09:39:47 +0000711 Test cannot assume anything about order. Docs make no guarantee and
712 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000713
Brett Cannon74bfd702003-04-25 09:39:47 +0000714 """
715 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000716 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000717 for expected in expect_somewhere:
718 self.assert_(expected in result,
719 "testing %s: %s not found in %s" %
720 (test_type, expected, result))
721 self.assertEqual(result.count('&'), 2,
722 "testing %s: expected 2 '&'s; got %s" %
723 (test_type, result.count('&')))
724 amp_location = result.index('&')
725 on_amp_left = result[amp_location - 1]
726 on_amp_right = result[amp_location + 1]
727 self.assert_(on_amp_left.isdigit() and on_amp_right.isdigit(),
728 "testing %s: '&' not located in proper place in %s" %
729 (test_type, result))
730 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
731 "testing %s: "
732 "unexpected number of characters: %s != %s" %
733 (test_type, len(result), (5 * 3) + 2))
734
735 def test_using_mapping(self):
736 # Test passing in a mapping object as an argument.
737 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
738 "using dict as input type")
739
740 def test_using_sequence(self):
741 # Test passing in a sequence of two-item sequences as an argument.
742 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
743 "using sequence of two-item tuples as input")
744
745 def test_quoting(self):
746 # Make sure keys and values are quoted using quote_plus()
747 given = {"&":"="}
748 expect = "%s=%s" % (hexescape('&'), hexescape('='))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000749 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000750 self.assertEqual(expect, result)
751 given = {"key name":"A bunch of pluses"}
752 expect = "key+name=A+bunch+of+pluses"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000753 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000754 self.assertEqual(expect, result)
755
756 def test_doseq(self):
757 # Test that passing True for 'doseq' parameter works correctly
758 given = {'sequence':['1', '2', '3']}
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000759 expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
760 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000761 self.assertEqual(expect, result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000762 result = urllib.parse.urlencode(given, True)
Brett Cannon74bfd702003-04-25 09:39:47 +0000763 for value in given["sequence"]:
764 expect = "sequence=%s" % value
765 self.assert_(expect in result,
766 "%s not found in %s" % (expect, result))
767 self.assertEqual(result.count('&'), 2,
768 "Expected 2 '&'s, got %s" % result.count('&'))
769
770class Pathname_Tests(unittest.TestCase):
771 """Test pathname2url() and url2pathname()"""
772
773 def test_basic(self):
774 # Make sure simple tests pass
775 expected_path = os.path.join("parts", "of", "a", "path")
776 expected_url = "parts/of/a/path"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000777 result = urllib.request.pathname2url(expected_path)
Brett Cannon74bfd702003-04-25 09:39:47 +0000778 self.assertEqual(expected_url, result,
779 "pathname2url() failed; %s != %s" %
780 (result, expected_url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000781 result = urllib.request.url2pathname(expected_url)
Brett Cannon74bfd702003-04-25 09:39:47 +0000782 self.assertEqual(expected_path, result,
783 "url2pathame() failed; %s != %s" %
784 (result, expected_path))
785
786 def test_quoting(self):
787 # Test automatic quoting and unquoting works for pathnam2url() and
788 # url2pathname() respectively
789 given = os.path.join("needs", "quot=ing", "here")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000790 expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
791 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000792 self.assertEqual(expect, result,
793 "pathname2url() failed; %s != %s" %
794 (expect, result))
795 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000796 result = urllib.request.url2pathname(result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000797 self.assertEqual(expect, result,
798 "url2pathname() failed; %s != %s" %
799 (expect, result))
800 given = os.path.join("make sure", "using_quote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000801 expect = "%s/using_quote" % urllib.parse.quote("make sure")
802 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000803 self.assertEqual(expect, result,
804 "pathname2url() failed; %s != %s" %
805 (expect, result))
806 given = "make+sure/using_unquote"
807 expect = os.path.join("make+sure", "using_unquote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000808 result = urllib.request.url2pathname(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000809 self.assertEqual(expect, result,
810 "url2pathname() failed; %s != %s" %
811 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000812
Guido van Rossume7ba4952007-06-06 23:52:48 +0000813# Just commented them out.
814# Can't really tell why keep failing in windows and sparc.
815# Everywhere else they work ok, but on those machines, someteimes
816# fail in one of the tests, sometimes in other. I have a linux, and
817# the tests go ok.
818# If anybody has one of the problematic enviroments, please help!
819# . Facundo
820#
821# def server(evt):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000822# import socket, time
Guido van Rossume7ba4952007-06-06 23:52:48 +0000823# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
824# serv.settimeout(3)
825# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
826# serv.bind(("", 9093))
827# serv.listen(5)
828# try:
829# conn, addr = serv.accept()
830# conn.send("1 Hola mundo\n")
831# cantdata = 0
832# while cantdata < 13:
833# data = conn.recv(13-cantdata)
834# cantdata += len(data)
835# time.sleep(.3)
836# conn.send("2 No more lines\n")
837# conn.close()
838# except socket.timeout:
839# pass
840# finally:
841# serv.close()
842# evt.set()
843#
844# class FTPWrapperTests(unittest.TestCase):
845#
846# def setUp(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000847# import ftplib, time, threading
Guido van Rossume7ba4952007-06-06 23:52:48 +0000848# ftplib.FTP.port = 9093
849# self.evt = threading.Event()
850# threading.Thread(target=server, args=(self.evt,)).start()
851# time.sleep(.1)
852#
853# def tearDown(self):
854# self.evt.wait()
855#
856# def testBasic(self):
857# # connects
858# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Georg Brandlf78e02b2008-06-10 17:40:04 +0000859# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000860#
861# def testTimeoutNone(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +0000862# # global default timeout is ignored
863# import socket
864# self.assert_(socket.getdefaulttimeout() is None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000865# socket.setdefaulttimeout(30)
866# try:
867# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
868# finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +0000869# socket.setdefaulttimeout(None)
Guido van Rossume7ba4952007-06-06 23:52:48 +0000870# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +0000871# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000872#
Georg Brandlf78e02b2008-06-10 17:40:04 +0000873# def testTimeoutDefault(self):
874# # global default timeout is used
875# import socket
876# self.assert_(socket.getdefaulttimeout() is None)
877# socket.setdefaulttimeout(30)
878# try:
879# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
880# finally:
881# socket.setdefaulttimeout(None)
882# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
883# ftp.close()
884#
885# def testTimeoutValue(self):
886# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
887# timeout=30)
888# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
889# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +0000890
Skip Montanaro080c9972001-01-28 21:12:22 +0000891
892
Brett Cannon74bfd702003-04-25 09:39:47 +0000893def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000894 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +0000895 urlopen_FileTests,
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000896 urlopen_HttpTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000897 urlretrieve_FileTests,
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000898 ProxyTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000899 QuotingTests,
900 UnquotingTests,
901 urlencode_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +0000902 Pathname_Tests,
903 #FTPWrapperTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +0000904 )
Brett Cannon74bfd702003-04-25 09:39:47 +0000905
906
907
908if __name__ == '__main__':
909 test_main()