blob: 401dd5ca0cbc97181bbd50e7cfc9151437d40b9b [file] [log] [blame]
Brett Cannon74bfd702003-04-25 09:39:47 +00001"""Regresssion tests for urllib"""
2
Jeremy Hylton6102e292000-08-31 15:48:10 +00003import urllib
Hye-Shik Chang39aef792004-06-05 13:30:56 +00004import httplib
Brett Cannon74bfd702003-04-25 09:39:47 +00005import unittest
6from test import test_support
7import os
Senthil Kumarana99b7612011-04-14 12:54:35 +08008import sys
Brett Cannon74bfd702003-04-25 09:39:47 +00009import mimetools
Georg Brandl5a650a22005-08-26 08:51:34 +000010import tempfile
Hye-Shik Chang39aef792004-06-05 13:30:56 +000011import StringIO
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
Brett Cannon74bfd702003-04-25 09:39:47 +000020class urlopen_FileTests(unittest.TestCase):
21 """Test urlopen() opening a temporary file.
Jeremy Hylton6102e292000-08-31 15:48:10 +000022
Brett Cannon74bfd702003-04-25 09:39:47 +000023 Try to test as much functionality as possible so as to cut down on reliance
Andrew M. Kuchlingf1a2f9e2004-06-29 13:07:53 +000024 on connecting to the Net for testing.
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000025
Brett Cannon74bfd702003-04-25 09:39:47 +000026 """
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000027
Brett Cannon74bfd702003-04-25 09:39:47 +000028 def setUp(self):
29 """Setup of a temp file to use for testing"""
30 self.text = "test_urllib: %s\n" % self.__class__.__name__
Guido van Rossum51735b02003-04-25 15:01:05 +000031 FILE = file(test_support.TESTFN, 'wb')
Brett Cannon74bfd702003-04-25 09:39:47 +000032 try:
33 FILE.write(self.text)
34 finally:
35 FILE.close()
36 self.pathname = test_support.TESTFN
37 self.returned_obj = urllib.urlopen("file:%s" % self.pathname)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000038
Brett Cannon74bfd702003-04-25 09:39:47 +000039 def tearDown(self):
40 """Shut down the open object"""
41 self.returned_obj.close()
Brett Cannon19691362003-04-29 05:08:06 +000042 os.remove(test_support.TESTFN)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000043
Brett Cannon74bfd702003-04-25 09:39:47 +000044 def test_interface(self):
45 # Make sure object returned by urlopen() has the specified methods
46 for attr in ("read", "readline", "readlines", "fileno",
Georg Brandl9b0d46d2008-01-20 11:43:03 +000047 "close", "info", "geturl", "getcode", "__iter__"):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000048 self.assertTrue(hasattr(self.returned_obj, attr),
Brett Cannon74bfd702003-04-25 09:39:47 +000049 "object returned by urlopen() lacks %s attribute" %
50 attr)
Skip Montanaroe78b92a2001-01-20 20:22:30 +000051
Brett Cannon74bfd702003-04-25 09:39:47 +000052 def test_read(self):
53 self.assertEqual(self.text, self.returned_obj.read())
Skip Montanaro080c9972001-01-28 21:12:22 +000054
Brett Cannon74bfd702003-04-25 09:39:47 +000055 def test_readline(self):
56 self.assertEqual(self.text, self.returned_obj.readline())
57 self.assertEqual('', self.returned_obj.readline(),
58 "calling readline() after exhausting the file did not"
59 " return an empty string")
Skip Montanaro080c9972001-01-28 21:12:22 +000060
Brett Cannon74bfd702003-04-25 09:39:47 +000061 def test_readlines(self):
62 lines_list = self.returned_obj.readlines()
63 self.assertEqual(len(lines_list), 1,
64 "readlines() returned the wrong number of lines")
65 self.assertEqual(lines_list[0], self.text,
66 "readlines() returned improper text")
Skip Montanaro080c9972001-01-28 21:12:22 +000067
Brett Cannon74bfd702003-04-25 09:39:47 +000068 def test_fileno(self):
69 file_num = self.returned_obj.fileno()
Ezio Melottib0f5adc2010-01-24 16:58:36 +000070 self.assertIsInstance(file_num, int, "fileno() did not return an int")
Brett Cannon74bfd702003-04-25 09:39:47 +000071 self.assertEqual(os.read(file_num, len(self.text)), self.text,
72 "Reading on the file descriptor returned by fileno() "
73 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +000074
Brett Cannon74bfd702003-04-25 09:39:47 +000075 def test_close(self):
76 # Test close() by calling it hear and then having it be called again
77 # by the tearDown() method for the test
78 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +000079
Brett Cannon74bfd702003-04-25 09:39:47 +000080 def test_info(self):
Ezio Melottib0f5adc2010-01-24 16:58:36 +000081 self.assertIsInstance(self.returned_obj.info(), mimetools.Message)
Skip Montanaroe78b92a2001-01-20 20:22:30 +000082
Brett Cannon74bfd702003-04-25 09:39:47 +000083 def test_geturl(self):
84 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +000085
Georg Brandl9b0d46d2008-01-20 11:43:03 +000086 def test_getcode(self):
87 self.assertEqual(self.returned_obj.getcode(), None)
88
Brett Cannon74bfd702003-04-25 09:39:47 +000089 def test_iter(self):
90 # Test iterator
91 # Don't need to count number of iterations since test would fail the
92 # instant it returned anything beyond the first line from the
93 # comparison
94 for line in self.returned_obj.__iter__():
95 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +000096
Benjamin Peterson2c7470d2008-09-21 21:27:51 +000097class ProxyTests(unittest.TestCase):
98
99 def setUp(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000100 # Records changes to env vars
101 self.env = test_support.EnvironmentVarGuard()
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000102 # Delete all proxy related env vars
Senthil Kumaran7a2ee0b2010-01-08 19:20:25 +0000103 for k in os.environ.keys():
Walter Dörwald4b965f62009-04-26 20:51:44 +0000104 if 'proxy' in k.lower():
Senthil Kumarandc61ec32009-10-01 01:50:13 +0000105 self.env.unset(k)
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000106
107 def tearDown(self):
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000108 # Restore all proxy related env vars
Walter Dörwald4b965f62009-04-26 20:51:44 +0000109 self.env.__exit__()
110 del self.env
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000111
112 def test_getproxies_environment_keep_no_proxies(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000113 self.env.set('NO_PROXY', 'localhost')
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000114 proxies = urllib.getproxies_environment()
115 # getproxies_environment use lowered case truncated (no '_proxy') keys
Ezio Melotti2623a372010-11-21 13:34:58 +0000116 self.assertEqual('localhost', proxies['no'])
Senthil Kumaranb5bd4c82011-08-06 12:24:33 +0800117 # List of no_proxies with space.
118 self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com')
119 self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com'))
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000120
121
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000122class urlopen_HttpTests(unittest.TestCase):
123 """Test urlopen() opening a fake http connection."""
124
125 def fakehttp(self, fakedata):
126 class FakeSocket(StringIO.StringIO):
127 def sendall(self, str): pass
128 def makefile(self, mode, name): return self
129 def read(self, amt=None):
130 if self.closed: return ''
131 return StringIO.StringIO.read(self, amt)
132 def readline(self, length=None):
133 if self.closed: return ''
134 return StringIO.StringIO.readline(self, length)
135 class FakeHTTPConnection(httplib.HTTPConnection):
136 def connect(self):
137 self.sock = FakeSocket(fakedata)
138 assert httplib.HTTP._connection_class == httplib.HTTPConnection
139 httplib.HTTP._connection_class = FakeHTTPConnection
140
141 def unfakehttp(self):
142 httplib.HTTP._connection_class = httplib.HTTPConnection
143
144 def test_read(self):
145 self.fakehttp('Hello!')
146 try:
147 fp = urllib.urlopen("http://python.org/")
148 self.assertEqual(fp.readline(), 'Hello!')
149 self.assertEqual(fp.readline(), '')
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000150 self.assertEqual(fp.geturl(), 'http://python.org/')
151 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000152 finally:
153 self.unfakehttp()
154
Senthil Kumaran49c44082011-04-13 07:31:45 +0800155 def test_url_fragment(self):
156 # Issue #11703: geturl() omits fragments in the original URL.
157 url = 'http://docs.python.org/library/urllib.html#OK'
158 self.fakehttp('Hello!')
159 try:
160 fp = urllib.urlopen(url)
161 self.assertEqual(fp.geturl(), url)
162 finally:
163 self.unfakehttp()
164
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000165 def test_read_bogus(self):
Kurt B. Kaiser0a112322008-01-02 05:23:38 +0000166 # urlopen() should raise IOError for many error codes.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000167 self.fakehttp('''HTTP/1.1 401 Authentication Required
168Date: Wed, 02 Jan 2008 03:03:54 GMT
169Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
170Connection: close
171Content-Type: text/html; charset=iso-8859-1
172''')
173 try:
174 self.assertRaises(IOError, urllib.urlopen, "http://python.org/")
175 finally:
176 self.unfakehttp()
177
guido@google.comf1509302011-03-28 13:47:01 -0700178 def test_invalid_redirect(self):
179 # urlopen() should raise IOError for many error codes.
180 self.fakehttp("""HTTP/1.1 302 Found
181Date: Wed, 02 Jan 2008 03:03:54 GMT
182Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
183Location: file:README
184Connection: close
185Content-Type: text/html; charset=iso-8859-1
186""")
187 try:
188 self.assertRaises(IOError, urllib.urlopen, "http://python.org/")
189 finally:
190 self.unfakehttp()
191
Georg Brandlf66b6032007-03-14 08:27:52 +0000192 def test_empty_socket(self):
Kurt B. Kaiser0a112322008-01-02 05:23:38 +0000193 # urlopen() raises IOError if the underlying socket does not send any
194 # data. (#1680230)
Georg Brandlf66b6032007-03-14 08:27:52 +0000195 self.fakehttp('')
196 try:
197 self.assertRaises(IOError, urllib.urlopen, 'http://something')
198 finally:
199 self.unfakehttp()
200
Brett Cannon19691362003-04-29 05:08:06 +0000201class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000202 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000203
Brett Cannon19691362003-04-29 05:08:06 +0000204 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000205 # Create a list of temporary files. Each item in the list is a file
206 # name (absolute path or relative to the current working directory).
207 # All files in this list will be deleted in the tearDown method. Note,
208 # this only helps to makes sure temporary files get deleted, but it
209 # does nothing about trying to close files that may still be open. It
210 # is the responsibility of the developer to properly close files even
211 # when exceptional conditions occur.
212 self.tempFiles = []
213
Brett Cannon19691362003-04-29 05:08:06 +0000214 # Create a temporary file.
Georg Brandl5a650a22005-08-26 08:51:34 +0000215 self.registerFileForCleanUp(test_support.TESTFN)
Brett Cannon19691362003-04-29 05:08:06 +0000216 self.text = 'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000217 try:
218 FILE = file(test_support.TESTFN, 'wb')
219 FILE.write(self.text)
220 FILE.close()
221 finally:
222 try: FILE.close()
223 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000224
225 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000226 # Delete the temporary files.
227 for each in self.tempFiles:
228 try: os.remove(each)
229 except: pass
230
231 def constructLocalFileUrl(self, filePath):
232 return "file://%s" % urllib.pathname2url(os.path.abspath(filePath))
233
234 def createNewTempFile(self, data=""):
235 """Creates a new temporary file containing the specified data,
236 registers the file for deletion during the test fixture tear down, and
237 returns the absolute path of the file."""
238
239 newFd, newFilePath = tempfile.mkstemp()
240 try:
241 self.registerFileForCleanUp(newFilePath)
242 newFile = os.fdopen(newFd, "wb")
243 newFile.write(data)
244 newFile.close()
245 finally:
246 try: newFile.close()
247 except: pass
248 return newFilePath
249
250 def registerFileForCleanUp(self, fileName):
251 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000252
253 def test_basic(self):
254 # Make sure that a local file just gets its own location returned and
255 # a headers value is returned.
256 result = urllib.urlretrieve("file:%s" % test_support.TESTFN)
257 self.assertEqual(result[0], test_support.TESTFN)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000258 self.assertIsInstance(result[1], mimetools.Message,
259 "did not get a mimetools.Message instance as "
260 "second returned value")
Brett Cannon19691362003-04-29 05:08:06 +0000261
262 def test_copy(self):
263 # Test that setting the filename argument works.
264 second_temp = "%s.2" % test_support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000265 self.registerFileForCleanUp(second_temp)
266 result = urllib.urlretrieve(self.constructLocalFileUrl(
267 test_support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000268 self.assertEqual(second_temp, result[0])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000269 self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
Brett Cannon19691362003-04-29 05:08:06 +0000270 "made")
271 FILE = file(second_temp, 'rb')
272 try:
273 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000274 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000275 finally:
276 try: FILE.close()
277 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000278 self.assertEqual(self.text, text)
279
280 def test_reporthook(self):
281 # Make sure that the reporthook works.
282 def hooktester(count, block_size, total_size, count_holder=[0]):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000283 self.assertIsInstance(count, int)
284 self.assertIsInstance(block_size, int)
285 self.assertIsInstance(total_size, int)
Brett Cannon19691362003-04-29 05:08:06 +0000286 self.assertEqual(count, count_holder[0])
287 count_holder[0] = count_holder[0] + 1
288 second_temp = "%s.2" % test_support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000289 self.registerFileForCleanUp(second_temp)
290 urllib.urlretrieve(self.constructLocalFileUrl(test_support.TESTFN),
291 second_temp, hooktester)
292
293 def test_reporthook_0_bytes(self):
294 # Test on zero length file. Should call reporthook only 1 time.
295 report = []
296 def hooktester(count, block_size, total_size, _report=report):
297 _report.append((count, block_size, total_size))
298 srcFileName = self.createNewTempFile()
299 urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),
300 test_support.TESTFN, hooktester)
301 self.assertEqual(len(report), 1)
302 self.assertEqual(report[0][2], 0)
303
304 def test_reporthook_5_bytes(self):
305 # Test on 5 byte file. Should call reporthook only 2 times (once when
306 # the "network connection" is established and once when the block is
307 # read). Since the block size is 8192 bytes, only one block read is
308 # required to read the entire file.
309 report = []
310 def hooktester(count, block_size, total_size, _report=report):
311 _report.append((count, block_size, total_size))
312 srcFileName = self.createNewTempFile("x" * 5)
313 urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),
314 test_support.TESTFN, hooktester)
315 self.assertEqual(len(report), 2)
316 self.assertEqual(report[0][1], 8192)
317 self.assertEqual(report[0][2], 5)
318
319 def test_reporthook_8193_bytes(self):
320 # Test on 8193 byte file. Should call reporthook only 3 times (once
321 # when the "network connection" is established, once for the next 8192
322 # bytes, and once for the last byte).
323 report = []
324 def hooktester(count, block_size, total_size, _report=report):
325 _report.append((count, block_size, total_size))
326 srcFileName = self.createNewTempFile("x" * 8193)
327 urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),
328 test_support.TESTFN, hooktester)
329 self.assertEqual(len(report), 3)
330 self.assertEqual(report[0][1], 8192)
331 self.assertEqual(report[0][2], 8193)
Skip Montanaro080c9972001-01-28 21:12:22 +0000332
Brett Cannon74bfd702003-04-25 09:39:47 +0000333class QuotingTests(unittest.TestCase):
334 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000335
Brett Cannon74bfd702003-04-25 09:39:47 +0000336 According to RFC 2396 ("Uniform Resource Identifiers), to escape a
337 character you write it as '%' + <2 character US-ASCII hex value>. The Python
338 code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly.
339 Case does not matter on the hex letters.
340
341 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000342
Brett Cannon74bfd702003-04-25 09:39:47 +0000343 Reserved characters : ";/?:@&=+$,"
344 Have special meaning in URIs and must be escaped if not being used for
345 their special meaning
346 Data characters : letters, digits, and "-_.!~*'()"
347 Unreserved and do not need to be escaped; can be, though, if desired
348 Control characters : 0x00 - 0x1F, 0x7F
349 Have no use in URIs so must be escaped
350 space : 0x20
351 Must be escaped
352 Delimiters : '<>#%"'
353 Must be escaped
354 Unwise : "{}|\^[]`"
355 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000356
Brett Cannon74bfd702003-04-25 09:39:47 +0000357 """
358
359 def test_never_quote(self):
360 # Make sure quote() does not quote letters, digits, and "_,.-"
361 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
362 "abcdefghijklmnopqrstuvwxyz",
363 "0123456789",
364 "_.-"])
365 result = urllib.quote(do_not_quote)
366 self.assertEqual(do_not_quote, result,
367 "using quote(): %s != %s" % (do_not_quote, result))
368 result = urllib.quote_plus(do_not_quote)
369 self.assertEqual(do_not_quote, result,
370 "using quote_plus(): %s != %s" % (do_not_quote, result))
371
372 def test_default_safe(self):
373 # Test '/' is default value for 'safe' parameter
374 self.assertEqual(urllib.quote.func_defaults[0], '/')
375
376 def test_safe(self):
377 # Test setting 'safe' parameter does what it should do
378 quote_by_default = "<>"
379 result = urllib.quote(quote_by_default, safe=quote_by_default)
380 self.assertEqual(quote_by_default, result,
381 "using quote(): %s != %s" % (quote_by_default, result))
382 result = urllib.quote_plus(quote_by_default, safe=quote_by_default)
383 self.assertEqual(quote_by_default, result,
384 "using quote_plus(): %s != %s" %
385 (quote_by_default, result))
386
387 def test_default_quoting(self):
388 # Make sure all characters that should be quoted are by default sans
389 # space (separate test for that).
390 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
391 should_quote.append('<>#%"{}|\^[]`')
392 should_quote.append(chr(127)) # For 0x7F
393 should_quote = ''.join(should_quote)
394 for char in should_quote:
395 result = urllib.quote(char)
396 self.assertEqual(hexescape(char), result,
397 "using quote(): %s should be escaped to %s, not %s" %
398 (char, hexescape(char), result))
399 result = urllib.quote_plus(char)
400 self.assertEqual(hexescape(char), result,
401 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000402 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000403 (char, hexescape(char), result))
404 del should_quote
405 partial_quote = "ab[]cd"
406 expected = "ab%5B%5Dcd"
407 result = urllib.quote(partial_quote)
408 self.assertEqual(expected, result,
409 "using quote(): %s != %s" % (expected, result))
410 self.assertEqual(expected, result,
411 "using quote_plus(): %s != %s" % (expected, result))
Senthil Kumaranc7743aa2010-07-19 17:35:50 +0000412 self.assertRaises(TypeError, urllib.quote, None)
Brett Cannon74bfd702003-04-25 09:39:47 +0000413
414 def test_quoting_space(self):
415 # Make sure quote() and quote_plus() handle spaces as specified in
416 # their unique way
417 result = urllib.quote(' ')
418 self.assertEqual(result, hexescape(' '),
419 "using quote(): %s != %s" % (result, hexescape(' ')))
420 result = urllib.quote_plus(' ')
421 self.assertEqual(result, '+',
422 "using quote_plus(): %s != +" % result)
423 given = "a b cd e f"
424 expect = given.replace(' ', hexescape(' '))
425 result = urllib.quote(given)
426 self.assertEqual(expect, result,
427 "using quote(): %s != %s" % (expect, result))
428 expect = given.replace(' ', '+')
429 result = urllib.quote_plus(given)
430 self.assertEqual(expect, result,
431 "using quote_plus(): %s != %s" % (expect, result))
432
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000433 def test_quoting_plus(self):
434 self.assertEqual(urllib.quote_plus('alpha+beta gamma'),
435 'alpha%2Bbeta+gamma')
436 self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'),
437 'alpha+beta+gamma')
438
Brett Cannon74bfd702003-04-25 09:39:47 +0000439class UnquotingTests(unittest.TestCase):
440 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000441
Brett Cannon74bfd702003-04-25 09:39:47 +0000442 See the doc string for quoting_Tests for details on quoting and such.
443
444 """
445
446 def test_unquoting(self):
447 # Make sure unquoting of all ASCII values works
448 escape_list = []
449 for num in range(128):
450 given = hexescape(chr(num))
451 expect = chr(num)
452 result = urllib.unquote(given)
453 self.assertEqual(expect, result,
454 "using unquote(): %s != %s" % (expect, result))
455 result = urllib.unquote_plus(given)
456 self.assertEqual(expect, result,
457 "using unquote_plus(): %s != %s" %
458 (expect, result))
459 escape_list.append(given)
460 escape_string = ''.join(escape_list)
461 del escape_list
462 result = urllib.unquote(escape_string)
463 self.assertEqual(result.count('%'), 1,
464 "using quote(): not all characters escaped; %s" %
465 result)
466 result = urllib.unquote(escape_string)
467 self.assertEqual(result.count('%'), 1,
468 "using unquote(): not all characters escaped: "
469 "%s" % result)
470
Senthil Kumaranf3e9b2a2010-03-18 12:14:15 +0000471 def test_unquoting_badpercent(self):
472 # Test unquoting on bad percent-escapes
473 given = '%xab'
474 expect = given
475 result = urllib.unquote(given)
476 self.assertEqual(expect, result, "using unquote(): %r != %r"
477 % (expect, result))
478 given = '%x'
479 expect = given
480 result = urllib.unquote(given)
481 self.assertEqual(expect, result, "using unquote(): %r != %r"
482 % (expect, result))
483 given = '%'
484 expect = given
485 result = urllib.unquote(given)
486 self.assertEqual(expect, result, "using unquote(): %r != %r"
487 % (expect, result))
488
489 def test_unquoting_mixed_case(self):
490 # Test unquoting on mixed-case hex digits in the percent-escapes
491 given = '%Ab%eA'
492 expect = '\xab\xea'
493 result = urllib.unquote(given)
494 self.assertEqual(expect, result, "using unquote(): %r != %r"
495 % (expect, result))
496
Brett Cannon74bfd702003-04-25 09:39:47 +0000497 def test_unquoting_parts(self):
498 # Make sure unquoting works when have non-quoted characters
499 # interspersed
500 given = 'ab%sd' % hexescape('c')
501 expect = "abcd"
502 result = urllib.unquote(given)
503 self.assertEqual(expect, result,
504 "using quote(): %s != %s" % (expect, result))
505 result = urllib.unquote_plus(given)
506 self.assertEqual(expect, result,
507 "using unquote_plus(): %s != %s" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000508
Brett Cannon74bfd702003-04-25 09:39:47 +0000509 def test_unquoting_plus(self):
510 # Test difference between unquote() and unquote_plus()
511 given = "are+there+spaces..."
512 expect = given
513 result = urllib.unquote(given)
514 self.assertEqual(expect, result,
515 "using unquote(): %s != %s" % (expect, result))
516 expect = given.replace('+', ' ')
517 result = urllib.unquote_plus(given)
518 self.assertEqual(expect, result,
519 "using unquote_plus(): %s != %s" % (expect, result))
520
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000521 def test_unquote_with_unicode(self):
522 r = urllib.unquote(u'br%C3%BCckner_sapporo_20050930.doc')
523 self.assertEqual(r, u'br\xc3\xbcckner_sapporo_20050930.doc')
524
Brett Cannon74bfd702003-04-25 09:39:47 +0000525class urlencode_Tests(unittest.TestCase):
526 """Tests for urlencode()"""
527
528 def help_inputtype(self, given, test_type):
529 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000530
Brett Cannon74bfd702003-04-25 09:39:47 +0000531 'given' must lead to only the pairs:
532 * 1st, 1
533 * 2nd, 2
534 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000535
Brett Cannon74bfd702003-04-25 09:39:47 +0000536 Test cannot assume anything about order. Docs make no guarantee and
537 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000538
Brett Cannon74bfd702003-04-25 09:39:47 +0000539 """
540 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
541 result = urllib.urlencode(given)
542 for expected in expect_somewhere:
Ezio Melottiaa980582010-01-23 23:04:36 +0000543 self.assertIn(expected, result,
Brett Cannon74bfd702003-04-25 09:39:47 +0000544 "testing %s: %s not found in %s" %
545 (test_type, expected, result))
546 self.assertEqual(result.count('&'), 2,
547 "testing %s: expected 2 '&'s; got %s" %
548 (test_type, result.count('&')))
549 amp_location = result.index('&')
550 on_amp_left = result[amp_location - 1]
551 on_amp_right = result[amp_location + 1]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000552 self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000553 "testing %s: '&' not located in proper place in %s" %
554 (test_type, result))
555 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
556 "testing %s: "
557 "unexpected number of characters: %s != %s" %
558 (test_type, len(result), (5 * 3) + 2))
559
560 def test_using_mapping(self):
561 # Test passing in a mapping object as an argument.
562 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
563 "using dict as input type")
564
565 def test_using_sequence(self):
566 # Test passing in a sequence of two-item sequences as an argument.
567 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
568 "using sequence of two-item tuples as input")
569
570 def test_quoting(self):
571 # Make sure keys and values are quoted using quote_plus()
572 given = {"&":"="}
573 expect = "%s=%s" % (hexescape('&'), hexescape('='))
574 result = urllib.urlencode(given)
575 self.assertEqual(expect, result)
576 given = {"key name":"A bunch of pluses"}
577 expect = "key+name=A+bunch+of+pluses"
578 result = urllib.urlencode(given)
579 self.assertEqual(expect, result)
580
581 def test_doseq(self):
582 # Test that passing True for 'doseq' parameter works correctly
583 given = {'sequence':['1', '2', '3']}
584 expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3']))
585 result = urllib.urlencode(given)
586 self.assertEqual(expect, result)
587 result = urllib.urlencode(given, True)
588 for value in given["sequence"]:
589 expect = "sequence=%s" % value
Ezio Melottiaa980582010-01-23 23:04:36 +0000590 self.assertIn(expect, result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000591 self.assertEqual(result.count('&'), 2,
592 "Expected 2 '&'s, got %s" % result.count('&'))
593
594class Pathname_Tests(unittest.TestCase):
595 """Test pathname2url() and url2pathname()"""
596
597 def test_basic(self):
598 # Make sure simple tests pass
599 expected_path = os.path.join("parts", "of", "a", "path")
600 expected_url = "parts/of/a/path"
601 result = urllib.pathname2url(expected_path)
602 self.assertEqual(expected_url, result,
603 "pathname2url() failed; %s != %s" %
604 (result, expected_url))
605 result = urllib.url2pathname(expected_url)
606 self.assertEqual(expected_path, result,
607 "url2pathame() failed; %s != %s" %
608 (result, expected_path))
609
610 def test_quoting(self):
611 # Test automatic quoting and unquoting works for pathnam2url() and
612 # url2pathname() respectively
613 given = os.path.join("needs", "quot=ing", "here")
614 expect = "needs/%s/here" % urllib.quote("quot=ing")
615 result = urllib.pathname2url(given)
616 self.assertEqual(expect, result,
617 "pathname2url() failed; %s != %s" %
618 (expect, result))
619 expect = given
620 result = urllib.url2pathname(result)
621 self.assertEqual(expect, result,
622 "url2pathname() failed; %s != %s" %
623 (expect, result))
624 given = os.path.join("make sure", "using_quote")
625 expect = "%s/using_quote" % urllib.quote("make sure")
626 result = urllib.pathname2url(given)
627 self.assertEqual(expect, result,
628 "pathname2url() failed; %s != %s" %
629 (expect, result))
630 given = "make+sure/using_unquote"
631 expect = os.path.join("make+sure", "using_unquote")
632 result = urllib.url2pathname(given)
633 self.assertEqual(expect, result,
634 "url2pathname() failed; %s != %s" %
635 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000636
Senthil Kumarana99b7612011-04-14 12:54:35 +0800637 @unittest.skipUnless(sys.platform == 'win32',
638 'test specific to the nturl2path library')
639 def test_ntpath(self):
640 given = ('/C:/', '///C:/', '/C|//')
641 expect = 'C:\\'
642 for url in given:
643 result = urllib.url2pathname(url)
644 self.assertEqual(expect, result,
645 'nturl2path.url2pathname() failed; %s != %s' %
646 (expect, result))
647 given = '///C|/path'
648 expect = 'C:\\path'
649 result = urllib.url2pathname(given)
650 self.assertEqual(expect, result,
651 'nturl2path.url2pathname() failed; %s != %s' %
652 (expect, result))
653
Senthil Kumaran5e95e762009-03-30 21:51:50 +0000654class Utility_Tests(unittest.TestCase):
655 """Testcase to test the various utility functions in the urllib."""
656
657 def test_splitpasswd(self):
658 """Some of the password examples are not sensible, but it is added to
659 confirming to RFC2617 and addressing issue4675.
660 """
661 self.assertEqual(('user', 'ab'),urllib.splitpasswd('user:ab'))
662 self.assertEqual(('user', 'a\nb'),urllib.splitpasswd('user:a\nb'))
663 self.assertEqual(('user', 'a\tb'),urllib.splitpasswd('user:a\tb'))
664 self.assertEqual(('user', 'a\rb'),urllib.splitpasswd('user:a\rb'))
665 self.assertEqual(('user', 'a\fb'),urllib.splitpasswd('user:a\fb'))
666 self.assertEqual(('user', 'a\vb'),urllib.splitpasswd('user:a\vb'))
667 self.assertEqual(('user', 'a:b'),urllib.splitpasswd('user:a:b'))
668
669
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000670class URLopener_Tests(unittest.TestCase):
671 """Testcase to test the open method of URLopener class."""
672
673 def test_quoted_open(self):
674 class DummyURLopener(urllib.URLopener):
675 def open_spam(self, url):
676 return url
677
678 self.assertEqual(DummyURLopener().open(
679 'spam://example/ /'),'//example/%20/')
680
Senthil Kumaran18d5a692010-02-20 22:05:34 +0000681 # test the safe characters are not quoted by urlopen
682 self.assertEqual(DummyURLopener().open(
683 "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
684 "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
685
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000686
Facundo Batistad9880d02007-05-25 04:20:22 +0000687# Just commented them out.
688# Can't really tell why keep failing in windows and sparc.
Ezio Melottic2077b02011-03-16 12:34:31 +0200689# Everywhere else they work ok, but on those machines, sometimes
Facundo Batistad9880d02007-05-25 04:20:22 +0000690# fail in one of the tests, sometimes in other. I have a linux, and
691# the tests go ok.
692# If anybody has one of the problematic enviroments, please help!
693# . Facundo
694#
695# def server(evt):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000696# import socket, time
Facundo Batistad9880d02007-05-25 04:20:22 +0000697# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
698# serv.settimeout(3)
699# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
700# serv.bind(("", 9093))
701# serv.listen(5)
702# try:
703# conn, addr = serv.accept()
704# conn.send("1 Hola mundo\n")
705# cantdata = 0
706# while cantdata < 13:
707# data = conn.recv(13-cantdata)
708# cantdata += len(data)
709# time.sleep(.3)
710# conn.send("2 No more lines\n")
711# conn.close()
712# except socket.timeout:
713# pass
714# finally:
715# serv.close()
716# evt.set()
717#
718# class FTPWrapperTests(unittest.TestCase):
719#
720# def setUp(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000721# import ftplib, time, threading
Facundo Batistad9880d02007-05-25 04:20:22 +0000722# ftplib.FTP.port = 9093
723# self.evt = threading.Event()
724# threading.Thread(target=server, args=(self.evt,)).start()
725# time.sleep(.1)
726#
727# def tearDown(self):
728# self.evt.wait()
729#
730# def testBasic(self):
731# # connects
732# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000733# ftp.close()
Facundo Batistad9880d02007-05-25 04:20:22 +0000734#
735# def testTimeoutNone(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000736# # global default timeout is ignored
737# import socket
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000738# self.assertTrue(socket.getdefaulttimeout() is None)
Facundo Batistad9880d02007-05-25 04:20:22 +0000739# socket.setdefaulttimeout(30)
740# try:
741# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
742# finally:
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000743# socket.setdefaulttimeout(None)
Facundo Batistad9880d02007-05-25 04:20:22 +0000744# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000745# ftp.close()
Facundo Batistad9880d02007-05-25 04:20:22 +0000746#
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000747# def testTimeoutDefault(self):
748# # global default timeout is used
749# import socket
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000750# self.assertTrue(socket.getdefaulttimeout() is None)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000751# socket.setdefaulttimeout(30)
752# try:
753# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
754# finally:
755# socket.setdefaulttimeout(None)
756# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
757# ftp.close()
758#
759# def testTimeoutValue(self):
760# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
761# timeout=30)
762# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
763# ftp.close()
Facundo Batista711a54e2007-05-24 17:50:54 +0000764
Skip Montanaro080c9972001-01-28 21:12:22 +0000765
766
Brett Cannon74bfd702003-04-25 09:39:47 +0000767def test_main():
Brett Cannon8bb8fa52008-07-02 01:57:08 +0000768 import warnings
Brett Cannon672237d2008-09-09 00:49:16 +0000769 with warnings.catch_warnings():
Brett Cannon8bb8fa52008-07-02 01:57:08 +0000770 warnings.filterwarnings('ignore', ".*urllib\.urlopen.*Python 3.0",
771 DeprecationWarning)
772 test_support.run_unittest(
773 urlopen_FileTests,
774 urlopen_HttpTests,
775 urlretrieve_FileTests,
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000776 ProxyTests,
Brett Cannon8bb8fa52008-07-02 01:57:08 +0000777 QuotingTests,
778 UnquotingTests,
779 urlencode_Tests,
780 Pathname_Tests,
Senthil Kumaran5e95e762009-03-30 21:51:50 +0000781 Utility_Tests,
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000782 URLopener_Tests,
Brett Cannon8bb8fa52008-07-02 01:57:08 +0000783 #FTPWrapperTests,
784 )
Brett Cannon74bfd702003-04-25 09:39:47 +0000785
786
787
788if __name__ == '__main__':
789 test_main()