blob: 9cb4dd233b78ade62eb2cd56d7656be9e68c5f9d [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
Brett Cannon74bfd702003-04-25 09:39:47 +00004import unittest
5from test import test_support
6import os
7import mimetools
Jeremy Hylton6102e292000-08-31 15:48:10 +00008
Brett Cannon74bfd702003-04-25 09:39:47 +00009def hexescape(char):
10 """Escape char as RFC 2396 specifies"""
11 hex_repr = hex(ord(char))[2:].upper()
12 if len(hex_repr) == 1:
13 hex_repr = "0%s" % hex_repr
14 return "%" + hex_repr
Jeremy Hylton6102e292000-08-31 15:48:10 +000015
Brett Cannon74bfd702003-04-25 09:39:47 +000016class urlopen_FileTests(unittest.TestCase):
17 """Test urlopen() opening a temporary file.
Jeremy Hylton6102e292000-08-31 15:48:10 +000018
Brett Cannon74bfd702003-04-25 09:39:47 +000019 Try to test as much functionality as possible so as to cut down on reliance
20 on connect to the Net for testing.
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000021
Brett Cannon74bfd702003-04-25 09:39:47 +000022 """
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000023
Brett Cannon74bfd702003-04-25 09:39:47 +000024 def setUp(self):
25 """Setup of a temp file to use for testing"""
26 self.text = "test_urllib: %s\n" % self.__class__.__name__
Guido van Rossum51735b02003-04-25 15:01:05 +000027 FILE = file(test_support.TESTFN, 'wb')
Brett Cannon74bfd702003-04-25 09:39:47 +000028 try:
29 FILE.write(self.text)
30 finally:
31 FILE.close()
32 self.pathname = test_support.TESTFN
33 self.returned_obj = urllib.urlopen("file:%s" % self.pathname)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000034
Brett Cannon74bfd702003-04-25 09:39:47 +000035 def tearDown(self):
36 """Shut down the open object"""
37 self.returned_obj.close()
Brett Cannon19691362003-04-29 05:08:06 +000038 os.remove(test_support.TESTFN)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000039
Brett Cannon74bfd702003-04-25 09:39:47 +000040 def test_interface(self):
41 # Make sure object returned by urlopen() has the specified methods
42 for attr in ("read", "readline", "readlines", "fileno",
43 "close", "info", "geturl", "__iter__"):
44 self.assert_(hasattr(self.returned_obj, attr),
45 "object returned by urlopen() lacks %s attribute" %
46 attr)
Skip Montanaroe78b92a2001-01-20 20:22:30 +000047
Brett Cannon74bfd702003-04-25 09:39:47 +000048 def test_read(self):
49 self.assertEqual(self.text, self.returned_obj.read())
Skip Montanaro080c9972001-01-28 21:12:22 +000050
Brett Cannon74bfd702003-04-25 09:39:47 +000051 def test_readline(self):
52 self.assertEqual(self.text, self.returned_obj.readline())
53 self.assertEqual('', self.returned_obj.readline(),
54 "calling readline() after exhausting the file did not"
55 " return an empty string")
Skip Montanaro080c9972001-01-28 21:12:22 +000056
Brett Cannon74bfd702003-04-25 09:39:47 +000057 def test_readlines(self):
58 lines_list = self.returned_obj.readlines()
59 self.assertEqual(len(lines_list), 1,
60 "readlines() returned the wrong number of lines")
61 self.assertEqual(lines_list[0], self.text,
62 "readlines() returned improper text")
Skip Montanaro080c9972001-01-28 21:12:22 +000063
Brett Cannon74bfd702003-04-25 09:39:47 +000064 def test_fileno(self):
65 file_num = self.returned_obj.fileno()
66 self.assert_(isinstance(file_num, int),
67 "fileno() did not return an int")
68 self.assertEqual(os.read(file_num, len(self.text)), self.text,
69 "Reading on the file descriptor returned by fileno() "
70 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +000071
Brett Cannon74bfd702003-04-25 09:39:47 +000072 def test_close(self):
73 # Test close() by calling it hear and then having it be called again
74 # by the tearDown() method for the test
75 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +000076
Brett Cannon74bfd702003-04-25 09:39:47 +000077 def test_info(self):
78 self.assert_(isinstance(self.returned_obj.info(), mimetools.Message))
Skip Montanaroe78b92a2001-01-20 20:22:30 +000079
Brett Cannon74bfd702003-04-25 09:39:47 +000080 def test_geturl(self):
81 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +000082
Brett Cannon74bfd702003-04-25 09:39:47 +000083 def test_iter(self):
84 # Test iterator
85 # Don't need to count number of iterations since test would fail the
86 # instant it returned anything beyond the first line from the
87 # comparison
88 for line in self.returned_obj.__iter__():
89 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +000090
Brett Cannon19691362003-04-29 05:08:06 +000091class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +000092 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +000093
Brett Cannon19691362003-04-29 05:08:06 +000094 def setUp(self):
95 # Create a temporary file.
96 self.text = 'testing urllib.urlretrieve'
97 FILE = file(test_support.TESTFN, 'wb')
98 FILE.write(self.text)
99 FILE.close()
100
101 def tearDown(self):
102 # Delete the temporary file.
103 os.remove(test_support.TESTFN)
104
105 def test_basic(self):
106 # Make sure that a local file just gets its own location returned and
107 # a headers value is returned.
108 result = urllib.urlretrieve("file:%s" % test_support.TESTFN)
109 self.assertEqual(result[0], test_support.TESTFN)
110 self.assert_(isinstance(result[1], mimetools.Message),
111 "did not get a mimetools.Message instance as second "
112 "returned value")
113
114 def test_copy(self):
115 # Test that setting the filename argument works.
116 second_temp = "%s.2" % test_support.TESTFN
117 result = urllib.urlretrieve("file:%s" % test_support.TESTFN, second_temp)
118 self.assertEqual(second_temp, result[0])
119 self.assert_(os.path.exists(second_temp), "copy of the file was not "
120 "made")
121 FILE = file(second_temp, 'rb')
122 try:
123 text = FILE.read()
124 finally:
125 FILE.close()
126 self.assertEqual(self.text, text)
127
128 def test_reporthook(self):
129 # Make sure that the reporthook works.
130 def hooktester(count, block_size, total_size, count_holder=[0]):
131 self.assert_(isinstance(count, int))
132 self.assert_(isinstance(block_size, int))
133 self.assert_(isinstance(total_size, int))
134 self.assertEqual(count, count_holder[0])
135 count_holder[0] = count_holder[0] + 1
136 second_temp = "%s.2" % test_support.TESTFN
137 urllib.urlretrieve(test_support.TESTFN, second_temp, hooktester)
138 os.remove(second_temp)
Skip Montanaro080c9972001-01-28 21:12:22 +0000139
Brett Cannon74bfd702003-04-25 09:39:47 +0000140class QuotingTests(unittest.TestCase):
141 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000142
Brett Cannon74bfd702003-04-25 09:39:47 +0000143 According to RFC 2396 ("Uniform Resource Identifiers), to escape a
144 character you write it as '%' + <2 character US-ASCII hex value>. The Python
145 code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly.
146 Case does not matter on the hex letters.
147
148 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000149
Brett Cannon74bfd702003-04-25 09:39:47 +0000150 Reserved characters : ";/?:@&=+$,"
151 Have special meaning in URIs and must be escaped if not being used for
152 their special meaning
153 Data characters : letters, digits, and "-_.!~*'()"
154 Unreserved and do not need to be escaped; can be, though, if desired
155 Control characters : 0x00 - 0x1F, 0x7F
156 Have no use in URIs so must be escaped
157 space : 0x20
158 Must be escaped
159 Delimiters : '<>#%"'
160 Must be escaped
161 Unwise : "{}|\^[]`"
162 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000163
Brett Cannon74bfd702003-04-25 09:39:47 +0000164 """
165
166 def test_never_quote(self):
167 # Make sure quote() does not quote letters, digits, and "_,.-"
168 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
169 "abcdefghijklmnopqrstuvwxyz",
170 "0123456789",
171 "_.-"])
172 result = urllib.quote(do_not_quote)
173 self.assertEqual(do_not_quote, result,
174 "using quote(): %s != %s" % (do_not_quote, result))
175 result = urllib.quote_plus(do_not_quote)
176 self.assertEqual(do_not_quote, result,
177 "using quote_plus(): %s != %s" % (do_not_quote, result))
178
179 def test_default_safe(self):
180 # Test '/' is default value for 'safe' parameter
181 self.assertEqual(urllib.quote.func_defaults[0], '/')
182
183 def test_safe(self):
184 # Test setting 'safe' parameter does what it should do
185 quote_by_default = "<>"
186 result = urllib.quote(quote_by_default, safe=quote_by_default)
187 self.assertEqual(quote_by_default, result,
188 "using quote(): %s != %s" % (quote_by_default, result))
189 result = urllib.quote_plus(quote_by_default, safe=quote_by_default)
190 self.assertEqual(quote_by_default, result,
191 "using quote_plus(): %s != %s" %
192 (quote_by_default, result))
193
194 def test_default_quoting(self):
195 # Make sure all characters that should be quoted are by default sans
196 # space (separate test for that).
197 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
198 should_quote.append('<>#%"{}|\^[]`')
199 should_quote.append(chr(127)) # For 0x7F
200 should_quote = ''.join(should_quote)
201 for char in should_quote:
202 result = urllib.quote(char)
203 self.assertEqual(hexescape(char), result,
204 "using quote(): %s should be escaped to %s, not %s" %
205 (char, hexescape(char), result))
206 result = urllib.quote_plus(char)
207 self.assertEqual(hexescape(char), result,
208 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000209 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000210 (char, hexescape(char), result))
211 del should_quote
212 partial_quote = "ab[]cd"
213 expected = "ab%5B%5Dcd"
214 result = urllib.quote(partial_quote)
215 self.assertEqual(expected, result,
216 "using quote(): %s != %s" % (expected, result))
217 self.assertEqual(expected, result,
218 "using quote_plus(): %s != %s" % (expected, result))
219
220 def test_quoting_space(self):
221 # Make sure quote() and quote_plus() handle spaces as specified in
222 # their unique way
223 result = urllib.quote(' ')
224 self.assertEqual(result, hexescape(' '),
225 "using quote(): %s != %s" % (result, hexescape(' ')))
226 result = urllib.quote_plus(' ')
227 self.assertEqual(result, '+',
228 "using quote_plus(): %s != +" % result)
229 given = "a b cd e f"
230 expect = given.replace(' ', hexescape(' '))
231 result = urllib.quote(given)
232 self.assertEqual(expect, result,
233 "using quote(): %s != %s" % (expect, result))
234 expect = given.replace(' ', '+')
235 result = urllib.quote_plus(given)
236 self.assertEqual(expect, result,
237 "using quote_plus(): %s != %s" % (expect, result))
238
239class UnquotingTests(unittest.TestCase):
240 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000241
Brett Cannon74bfd702003-04-25 09:39:47 +0000242 See the doc string for quoting_Tests for details on quoting and such.
243
244 """
245
246 def test_unquoting(self):
247 # Make sure unquoting of all ASCII values works
248 escape_list = []
249 for num in range(128):
250 given = hexescape(chr(num))
251 expect = chr(num)
252 result = urllib.unquote(given)
253 self.assertEqual(expect, result,
254 "using unquote(): %s != %s" % (expect, result))
255 result = urllib.unquote_plus(given)
256 self.assertEqual(expect, result,
257 "using unquote_plus(): %s != %s" %
258 (expect, result))
259 escape_list.append(given)
260 escape_string = ''.join(escape_list)
261 del escape_list
262 result = urllib.unquote(escape_string)
263 self.assertEqual(result.count('%'), 1,
264 "using quote(): not all characters escaped; %s" %
265 result)
266 result = urllib.unquote(escape_string)
267 self.assertEqual(result.count('%'), 1,
268 "using unquote(): not all characters escaped: "
269 "%s" % result)
270
271 def test_unquoting_parts(self):
272 # Make sure unquoting works when have non-quoted characters
273 # interspersed
274 given = 'ab%sd' % hexescape('c')
275 expect = "abcd"
276 result = urllib.unquote(given)
277 self.assertEqual(expect, result,
278 "using quote(): %s != %s" % (expect, result))
279 result = urllib.unquote_plus(given)
280 self.assertEqual(expect, result,
281 "using unquote_plus(): %s != %s" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000282
Brett Cannon74bfd702003-04-25 09:39:47 +0000283 def test_unquoting_plus(self):
284 # Test difference between unquote() and unquote_plus()
285 given = "are+there+spaces..."
286 expect = given
287 result = urllib.unquote(given)
288 self.assertEqual(expect, result,
289 "using unquote(): %s != %s" % (expect, result))
290 expect = given.replace('+', ' ')
291 result = urllib.unquote_plus(given)
292 self.assertEqual(expect, result,
293 "using unquote_plus(): %s != %s" % (expect, result))
294
295class urlencode_Tests(unittest.TestCase):
296 """Tests for urlencode()"""
297
298 def help_inputtype(self, given, test_type):
299 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000300
Brett Cannon74bfd702003-04-25 09:39:47 +0000301 'given' must lead to only the pairs:
302 * 1st, 1
303 * 2nd, 2
304 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000305
Brett Cannon74bfd702003-04-25 09:39:47 +0000306 Test cannot assume anything about order. Docs make no guarantee and
307 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000308
Brett Cannon74bfd702003-04-25 09:39:47 +0000309 """
310 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
311 result = urllib.urlencode(given)
312 for expected in expect_somewhere:
313 self.assert_(expected in result,
314 "testing %s: %s not found in %s" %
315 (test_type, expected, result))
316 self.assertEqual(result.count('&'), 2,
317 "testing %s: expected 2 '&'s; got %s" %
318 (test_type, result.count('&')))
319 amp_location = result.index('&')
320 on_amp_left = result[amp_location - 1]
321 on_amp_right = result[amp_location + 1]
322 self.assert_(on_amp_left.isdigit() and on_amp_right.isdigit(),
323 "testing %s: '&' not located in proper place in %s" %
324 (test_type, result))
325 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
326 "testing %s: "
327 "unexpected number of characters: %s != %s" %
328 (test_type, len(result), (5 * 3) + 2))
329
330 def test_using_mapping(self):
331 # Test passing in a mapping object as an argument.
332 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
333 "using dict as input type")
334
335 def test_using_sequence(self):
336 # Test passing in a sequence of two-item sequences as an argument.
337 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
338 "using sequence of two-item tuples as input")
339
340 def test_quoting(self):
341 # Make sure keys and values are quoted using quote_plus()
342 given = {"&":"="}
343 expect = "%s=%s" % (hexescape('&'), hexescape('='))
344 result = urllib.urlencode(given)
345 self.assertEqual(expect, result)
346 given = {"key name":"A bunch of pluses"}
347 expect = "key+name=A+bunch+of+pluses"
348 result = urllib.urlencode(given)
349 self.assertEqual(expect, result)
350
351 def test_doseq(self):
352 # Test that passing True for 'doseq' parameter works correctly
353 given = {'sequence':['1', '2', '3']}
354 expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3']))
355 result = urllib.urlencode(given)
356 self.assertEqual(expect, result)
357 result = urllib.urlencode(given, True)
358 for value in given["sequence"]:
359 expect = "sequence=%s" % value
360 self.assert_(expect in result,
361 "%s not found in %s" % (expect, result))
362 self.assertEqual(result.count('&'), 2,
363 "Expected 2 '&'s, got %s" % result.count('&'))
364
365class Pathname_Tests(unittest.TestCase):
366 """Test pathname2url() and url2pathname()"""
367
368 def test_basic(self):
369 # Make sure simple tests pass
370 expected_path = os.path.join("parts", "of", "a", "path")
371 expected_url = "parts/of/a/path"
372 result = urllib.pathname2url(expected_path)
373 self.assertEqual(expected_url, result,
374 "pathname2url() failed; %s != %s" %
375 (result, expected_url))
376 result = urllib.url2pathname(expected_url)
377 self.assertEqual(expected_path, result,
378 "url2pathame() failed; %s != %s" %
379 (result, expected_path))
380
381 def test_quoting(self):
382 # Test automatic quoting and unquoting works for pathnam2url() and
383 # url2pathname() respectively
384 given = os.path.join("needs", "quot=ing", "here")
385 expect = "needs/%s/here" % urllib.quote("quot=ing")
386 result = urllib.pathname2url(given)
387 self.assertEqual(expect, result,
388 "pathname2url() failed; %s != %s" %
389 (expect, result))
390 expect = given
391 result = urllib.url2pathname(result)
392 self.assertEqual(expect, result,
393 "url2pathname() failed; %s != %s" %
394 (expect, result))
395 given = os.path.join("make sure", "using_quote")
396 expect = "%s/using_quote" % urllib.quote("make sure")
397 result = urllib.pathname2url(given)
398 self.assertEqual(expect, result,
399 "pathname2url() failed; %s != %s" %
400 (expect, result))
401 given = "make+sure/using_unquote"
402 expect = os.path.join("make+sure", "using_unquote")
403 result = urllib.url2pathname(given)
404 self.assertEqual(expect, result,
405 "url2pathname() failed; %s != %s" %
406 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000407
Skip Montanaro080c9972001-01-28 21:12:22 +0000408
409
Brett Cannon74bfd702003-04-25 09:39:47 +0000410def test_main():
Walter Dörwald21d3a322003-05-01 17:45:56 +0000411 test_support.run_unittest(
412 urlopen_FileTests,
413 urlretrieve_FileTests,
414 QuotingTests,
415 UnquotingTests,
416 urlencode_Tests,
417 Pathname_Tests
418 )
Brett Cannon74bfd702003-04-25 09:39:47 +0000419
420
421
422if __name__ == '__main__':
423 test_main()