blob: e403bbf167683845c32ae53d7c768648216e05e1 [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
guido@google.coma119df92011-03-29 11:41:02 -07005import urllib.error
Georg Brandl24420152008-05-26 16:32:26 +00006import http.client
Barry Warsaw820c1202008-06-12 04:06:45 +00007import email.message
Jeremy Hylton66dc8c52007-08-04 03:42:26 +00008import io
Brett Cannon74bfd702003-04-25 09:39:47 +00009import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000010from test import support
Brett Cannon74bfd702003-04-25 09:39:47 +000011import os
Senthil Kumaran2d2ea1b2011-04-14 13:16:30 +080012import sys
Georg Brandl5a650a22005-08-26 08:51:34 +000013import tempfile
Jeremy Hylton6102e292000-08-31 15:48:10 +000014
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080015from base64 import b64encode
16
Brett Cannon74bfd702003-04-25 09:39:47 +000017def hexescape(char):
18 """Escape char as RFC 2396 specifies"""
19 hex_repr = hex(ord(char))[2:].upper()
20 if len(hex_repr) == 1:
21 hex_repr = "0%s" % hex_repr
22 return "%" + hex_repr
Jeremy Hylton6102e292000-08-31 15:48:10 +000023
Jeremy Hylton1afc1692008-06-18 20:49:58 +000024# Shortcut for testing FancyURLopener
25_urlopener = None
26def urlopen(url, data=None, proxies=None):
27 """urlopen(url [, data]) -> open file-like object"""
28 global _urlopener
29 if proxies is not None:
30 opener = urllib.request.FancyURLopener(proxies=proxies)
31 elif not _urlopener:
32 opener = urllib.request.FancyURLopener()
33 _urlopener = opener
34 else:
35 opener = _urlopener
36 if data is None:
37 return opener.open(url)
38 else:
39 return opener.open(url, data)
40
Senthil Kumarance260142011-11-01 01:35:17 +080041
42class FakeHTTPMixin(object):
43 def fakehttp(self, fakedata):
44 class FakeSocket(io.BytesIO):
45 io_refs = 1
46
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080047 def sendall(self, data):
48 FakeHTTPConnection.buf = data
Senthil Kumarance260142011-11-01 01:35:17 +080049
50 def makefile(self, *args, **kwds):
51 self.io_refs += 1
52 return self
53
54 def read(self, amt=None):
55 if self.closed:
56 return b""
57 return io.BytesIO.read(self, amt)
58
59 def readline(self, length=None):
60 if self.closed:
61 return b""
62 return io.BytesIO.readline(self, length)
63
64 def close(self):
65 self.io_refs -= 1
66 if self.io_refs == 0:
67 io.BytesIO.close(self)
68
69 class FakeHTTPConnection(http.client.HTTPConnection):
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080070
71 # buffer to store data for verification in urlopen tests.
72 buf = None
73
Senthil Kumarance260142011-11-01 01:35:17 +080074 def connect(self):
75 self.sock = FakeSocket(fakedata)
Senthil Kumaranc5c5a142012-01-14 19:09:04 +080076
Senthil Kumarance260142011-11-01 01:35:17 +080077 self._connection_class = http.client.HTTPConnection
78 http.client.HTTPConnection = FakeHTTPConnection
79
80 def unfakehttp(self):
81 http.client.HTTPConnection = self._connection_class
82
83
Brett Cannon74bfd702003-04-25 09:39:47 +000084class urlopen_FileTests(unittest.TestCase):
85 """Test urlopen() opening a temporary file.
Jeremy Hylton6102e292000-08-31 15:48:10 +000086
Brett Cannon74bfd702003-04-25 09:39:47 +000087 Try to test as much functionality as possible so as to cut down on reliance
Andrew M. Kuchlingf1a2f9e2004-06-29 13:07:53 +000088 on connecting to the Net for testing.
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000089
Brett Cannon74bfd702003-04-25 09:39:47 +000090 """
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000091
Brett Cannon74bfd702003-04-25 09:39:47 +000092 def setUp(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +000093 # Create a temp file to use for testing
94 self.text = bytes("test_urllib: %s\n" % self.__class__.__name__,
95 "ascii")
96 f = open(support.TESTFN, 'wb')
Brett Cannon74bfd702003-04-25 09:39:47 +000097 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +000098 f.write(self.text)
Brett Cannon74bfd702003-04-25 09:39:47 +000099 finally:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000100 f.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000101 self.pathname = support.TESTFN
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000102 self.returned_obj = urlopen("file:%s" % self.pathname)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +0000103
Brett Cannon74bfd702003-04-25 09:39:47 +0000104 def tearDown(self):
105 """Shut down the open object"""
106 self.returned_obj.close()
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000107 os.remove(support.TESTFN)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +0000108
Brett Cannon74bfd702003-04-25 09:39:47 +0000109 def test_interface(self):
110 # Make sure object returned by urlopen() has the specified methods
111 for attr in ("read", "readline", "readlines", "fileno",
Christian Heimes9bd667a2008-01-20 15:14:11 +0000112 "close", "info", "geturl", "getcode", "__iter__"):
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000113 self.assertTrue(hasattr(self.returned_obj, attr),
Brett Cannon74bfd702003-04-25 09:39:47 +0000114 "object returned by urlopen() lacks %s attribute" %
115 attr)
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000116
Brett Cannon74bfd702003-04-25 09:39:47 +0000117 def test_read(self):
118 self.assertEqual(self.text, self.returned_obj.read())
Skip Montanaro080c9972001-01-28 21:12:22 +0000119
Brett Cannon74bfd702003-04-25 09:39:47 +0000120 def test_readline(self):
121 self.assertEqual(self.text, self.returned_obj.readline())
Guido van Rossuma0982942007-07-10 08:30:03 +0000122 self.assertEqual(b'', self.returned_obj.readline(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000123 "calling readline() after exhausting the file did not"
124 " return an empty string")
Skip Montanaro080c9972001-01-28 21:12:22 +0000125
Brett Cannon74bfd702003-04-25 09:39:47 +0000126 def test_readlines(self):
127 lines_list = self.returned_obj.readlines()
128 self.assertEqual(len(lines_list), 1,
129 "readlines() returned the wrong number of lines")
130 self.assertEqual(lines_list[0], self.text,
131 "readlines() returned improper text")
Skip Montanaro080c9972001-01-28 21:12:22 +0000132
Brett Cannon74bfd702003-04-25 09:39:47 +0000133 def test_fileno(self):
134 file_num = self.returned_obj.fileno()
Ezio Melottie9615932010-01-24 19:26:24 +0000135 self.assertIsInstance(file_num, int, "fileno() did not return an int")
Brett Cannon74bfd702003-04-25 09:39:47 +0000136 self.assertEqual(os.read(file_num, len(self.text)), self.text,
137 "Reading on the file descriptor returned by fileno() "
138 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000139
Brett Cannon74bfd702003-04-25 09:39:47 +0000140 def test_close(self):
Senthil Kumarand91ffca2011-03-19 17:25:27 +0800141 # Test close() by calling it here and then having it be called again
Brett Cannon74bfd702003-04-25 09:39:47 +0000142 # by the tearDown() method for the test
143 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +0000144
Brett Cannon74bfd702003-04-25 09:39:47 +0000145 def test_info(self):
Ezio Melottie9615932010-01-24 19:26:24 +0000146 self.assertIsInstance(self.returned_obj.info(), email.message.Message)
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000147
Brett Cannon74bfd702003-04-25 09:39:47 +0000148 def test_geturl(self):
149 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +0000150
Christian Heimes9bd667a2008-01-20 15:14:11 +0000151 def test_getcode(self):
Florent Xicluna419e3842010-08-08 16:16:07 +0000152 self.assertIsNone(self.returned_obj.getcode())
Christian Heimes9bd667a2008-01-20 15:14:11 +0000153
Brett Cannon74bfd702003-04-25 09:39:47 +0000154 def test_iter(self):
155 # Test iterator
156 # Don't need to count number of iterations since test would fail the
157 # instant it returned anything beyond the first line from the
Raymond Hettinger038018a2011-06-26 14:29:35 +0200158 # comparison.
159 # Use the iterator in the usual implicit way to test for ticket #4608.
160 for line in self.returned_obj:
Brett Cannon74bfd702003-04-25 09:39:47 +0000161 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +0000162
Senthil Kumaran3800ea92012-01-21 11:52:48 +0800163 def test_relativelocalfile(self):
164 self.assertRaises(ValueError,urllib.request.urlopen,'./' + self.pathname)
165
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000166class ProxyTests(unittest.TestCase):
167
168 def setUp(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +0000169 # Records changes to env vars
170 self.env = support.EnvironmentVarGuard()
Benjamin Peterson46a99002010-01-09 18:45:30 +0000171 # Delete all proxy related env vars
Antoine Pitroub3a88b52010-10-14 18:31:39 +0000172 for k in list(os.environ):
Antoine Pitrou8c8f1ac2010-10-14 18:32:54 +0000173 if 'proxy' in k.lower():
Benjamin Peterson46a99002010-01-09 18:45:30 +0000174 self.env.unset(k)
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000175
176 def tearDown(self):
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000177 # Restore all proxy related env vars
Walter Dörwaldb525e182009-04-26 21:39:21 +0000178 self.env.__exit__()
179 del self.env
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000180
181 def test_getproxies_environment_keep_no_proxies(self):
Walter Dörwaldb525e182009-04-26 21:39:21 +0000182 self.env.set('NO_PROXY', 'localhost')
183 proxies = urllib.request.getproxies_environment()
184 # getproxies_environment use lowered case truncated (no '_proxy') keys
Florent Xicluna419e3842010-08-08 16:16:07 +0000185 self.assertEqual('localhost', proxies['no'])
Senthil Kumaran89976f12011-08-06 12:27:40 +0800186 # List of no_proxies with space.
187 self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com')
188 self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com'))
Benjamin Peterson9bc93512008-09-22 22:10:59 +0000189
Senthil Kumarance260142011-11-01 01:35:17 +0800190class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000191 """Test urlopen() opening a fake http connection."""
192
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000193 def check_read(self, ver):
194 self.fakehttp(b"HTTP/" + ver + b" 200 OK\r\n\r\nHello!")
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000195 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000196 fp = urlopen("http://python.org/")
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000197 self.assertEqual(fp.readline(), b"Hello!")
198 self.assertEqual(fp.readline(), b"")
Christian Heimes9bd667a2008-01-20 15:14:11 +0000199 self.assertEqual(fp.geturl(), 'http://python.org/')
200 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000201 finally:
202 self.unfakehttp()
203
Senthil Kumaran26430412011-04-13 07:01:19 +0800204 def test_url_fragment(self):
205 # Issue #11703: geturl() omits fragments in the original URL.
206 url = 'http://docs.python.org/library/urllib.html#OK'
Senthil Kumaranb17abb12011-04-13 07:22:29 +0800207 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
Senthil Kumaran26430412011-04-13 07:01:19 +0800208 try:
209 fp = urllib.request.urlopen(url)
210 self.assertEqual(fp.geturl(), url)
211 finally:
212 self.unfakehttp()
213
Senthil Kumarand91ffca2011-03-19 17:25:27 +0800214 def test_willclose(self):
215 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
Senthil Kumaranacbaa922011-03-20 05:30:16 +0800216 try:
217 resp = urlopen("http://www.python.org")
218 self.assertTrue(resp.fp.will_close)
219 finally:
220 self.unfakehttp()
Senthil Kumarand91ffca2011-03-19 17:25:27 +0800221
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000222 def test_read_0_9(self):
223 # "0.9" response accepted (but not "simple responses" without
224 # a status line)
225 self.check_read(b"0.9")
226
227 def test_read_1_0(self):
228 self.check_read(b"1.0")
229
230 def test_read_1_1(self):
231 self.check_read(b"1.1")
232
Christian Heimes57dddfb2008-01-02 18:30:52 +0000233 def test_read_bogus(self):
234 # urlopen() should raise IOError for many error codes.
235 self.fakehttp(b'''HTTP/1.1 401 Authentication Required
236Date: Wed, 02 Jan 2008 03:03:54 GMT
237Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
238Connection: close
239Content-Type: text/html; charset=iso-8859-1
240''')
241 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000242 self.assertRaises(IOError, urlopen, "http://python.org/")
Christian Heimes57dddfb2008-01-02 18:30:52 +0000243 finally:
244 self.unfakehttp()
245
guido@google.coma119df92011-03-29 11:41:02 -0700246 def test_invalid_redirect(self):
247 # urlopen() should raise IOError for many error codes.
248 self.fakehttp(b'''HTTP/1.1 302 Found
249Date: Wed, 02 Jan 2008 03:03:54 GMT
250Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
251Location: file://guidocomputer.athome.com:/python/license
252Connection: close
253Content-Type: text/html; charset=iso-8859-1
254''')
255 try:
256 self.assertRaises(urllib.error.HTTPError, urlopen,
257 "http://python.org/")
258 finally:
259 self.unfakehttp()
260
Guido van Rossumd8faa362007-04-27 19:54:29 +0000261 def test_empty_socket(self):
Jeremy Hylton66dc8c52007-08-04 03:42:26 +0000262 # urlopen() raises IOError if the underlying socket does not send any
263 # data. (#1680230)
Christian Heimes57dddfb2008-01-02 18:30:52 +0000264 self.fakehttp(b'')
Guido van Rossumd8faa362007-04-27 19:54:29 +0000265 try:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000266 self.assertRaises(IOError, urlopen, "http://something")
Guido van Rossumd8faa362007-04-27 19:54:29 +0000267 finally:
268 self.unfakehttp()
269
Senthil Kumarande0eb242010-08-01 17:53:37 +0000270 def test_userpass_inurl(self):
Antoine Pitrou988dbd72010-12-17 17:35:56 +0000271 self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
Senthil Kumarande0eb242010-08-01 17:53:37 +0000272 try:
273 fp = urlopen("http://user:pass@python.org/")
274 self.assertEqual(fp.readline(), b"Hello!")
275 self.assertEqual(fp.readline(), b"")
276 self.assertEqual(fp.geturl(), 'http://user:pass@python.org/')
277 self.assertEqual(fp.getcode(), 200)
278 finally:
279 self.unfakehttp()
280
Senthil Kumaranc5c5a142012-01-14 19:09:04 +0800281 def test_userpass_inurl_w_spaces(self):
282 self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
283 try:
284 userpass = "a b:c d"
285 url = "http://{}@python.org/".format(userpass)
286 fakehttp_wrapper = http.client.HTTPConnection
287 authorization = ("Authorization: Basic %s\r\n" %
288 b64encode(userpass.encode("ASCII")).decode("ASCII"))
289 fp = urlopen(url)
290 # The authorization header must be in place
291 self.assertIn(authorization, fakehttp_wrapper.buf.decode("UTF-8"))
292 self.assertEqual(fp.readline(), b"Hello!")
293 self.assertEqual(fp.readline(), b"")
294 # the spaces are quoted in URL so no match
295 self.assertNotEqual(fp.geturl(), url)
296 self.assertEqual(fp.getcode(), 200)
297 finally:
298 self.unfakehttp()
299
Brett Cannon19691362003-04-29 05:08:06 +0000300class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000301 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000302
Brett Cannon19691362003-04-29 05:08:06 +0000303 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000304 # Create a list of temporary files. Each item in the list is a file
305 # name (absolute path or relative to the current working directory).
306 # All files in this list will be deleted in the tearDown method. Note,
307 # this only helps to makes sure temporary files get deleted, but it
308 # does nothing about trying to close files that may still be open. It
309 # is the responsibility of the developer to properly close files even
310 # when exceptional conditions occur.
311 self.tempFiles = []
312
Brett Cannon19691362003-04-29 05:08:06 +0000313 # Create a temporary file.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000314 self.registerFileForCleanUp(support.TESTFN)
Guido van Rossuma0982942007-07-10 08:30:03 +0000315 self.text = b'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000316 try:
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000317 FILE = open(support.TESTFN, 'wb')
Georg Brandl5a650a22005-08-26 08:51:34 +0000318 FILE.write(self.text)
319 FILE.close()
320 finally:
321 try: FILE.close()
322 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000323
324 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000325 # Delete the temporary files.
326 for each in self.tempFiles:
327 try: os.remove(each)
328 except: pass
329
330 def constructLocalFileUrl(self, filePath):
Victor Stinner6c6f8512010-08-07 10:09:35 +0000331 filePath = os.path.abspath(filePath)
332 try:
Marc-André Lemburg8f36af72011-02-25 15:42:01 +0000333 filePath.encode("utf-8")
Victor Stinner6c6f8512010-08-07 10:09:35 +0000334 except UnicodeEncodeError:
335 raise unittest.SkipTest("filePath is not encodable to utf8")
336 return "file://%s" % urllib.request.pathname2url(filePath)
Georg Brandl5a650a22005-08-26 08:51:34 +0000337
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000338 def createNewTempFile(self, data=b""):
Georg Brandl5a650a22005-08-26 08:51:34 +0000339 """Creates a new temporary file containing the specified data,
340 registers the file for deletion during the test fixture tear down, and
341 returns the absolute path of the file."""
342
343 newFd, newFilePath = tempfile.mkstemp()
344 try:
345 self.registerFileForCleanUp(newFilePath)
346 newFile = os.fdopen(newFd, "wb")
347 newFile.write(data)
348 newFile.close()
349 finally:
350 try: newFile.close()
351 except: pass
352 return newFilePath
353
354 def registerFileForCleanUp(self, fileName):
355 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000356
357 def test_basic(self):
358 # Make sure that a local file just gets its own location returned and
359 # a headers value is returned.
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000360 result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000361 self.assertEqual(result[0], support.TESTFN)
Ezio Melottie9615932010-01-24 19:26:24 +0000362 self.assertIsInstance(result[1], email.message.Message,
363 "did not get a email.message.Message instance "
364 "as second returned value")
Brett Cannon19691362003-04-29 05:08:06 +0000365
366 def test_copy(self):
367 # Test that setting the filename argument works.
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000368 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000369 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000370 result = urllib.request.urlretrieve(self.constructLocalFileUrl(
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000371 support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000372 self.assertEqual(second_temp, result[0])
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000373 self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
Brett Cannon19691362003-04-29 05:08:06 +0000374 "made")
Alex Martelli01c77c62006-08-24 02:58:11 +0000375 FILE = open(second_temp, 'rb')
Brett Cannon19691362003-04-29 05:08:06 +0000376 try:
377 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000378 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000379 finally:
380 try: FILE.close()
381 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000382 self.assertEqual(self.text, text)
383
384 def test_reporthook(self):
385 # Make sure that the reporthook works.
386 def hooktester(count, block_size, total_size, count_holder=[0]):
Ezio Melottie9615932010-01-24 19:26:24 +0000387 self.assertIsInstance(count, int)
388 self.assertIsInstance(block_size, int)
389 self.assertIsInstance(total_size, int)
Brett Cannon19691362003-04-29 05:08:06 +0000390 self.assertEqual(count, count_holder[0])
391 count_holder[0] = count_holder[0] + 1
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000392 second_temp = "%s.2" % support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000393 self.registerFileForCleanUp(second_temp)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000394 urllib.request.urlretrieve(
395 self.constructLocalFileUrl(support.TESTFN),
Georg Brandl5a650a22005-08-26 08:51:34 +0000396 second_temp, hooktester)
397
398 def test_reporthook_0_bytes(self):
399 # Test on zero length file. Should call reporthook only 1 time.
400 report = []
401 def hooktester(count, block_size, total_size, _report=report):
402 _report.append((count, block_size, total_size))
403 srcFileName = self.createNewTempFile()
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000404 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000405 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000406 self.assertEqual(len(report), 1)
407 self.assertEqual(report[0][2], 0)
408
409 def test_reporthook_5_bytes(self):
410 # Test on 5 byte file. Should call reporthook only 2 times (once when
411 # the "network connection" is established and once when the block is
412 # read). Since the block size is 8192 bytes, only one block read is
413 # required to read the entire file.
414 report = []
415 def hooktester(count, block_size, total_size, _report=report):
416 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000417 srcFileName = self.createNewTempFile(b"x" * 5)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000418 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000419 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000420 self.assertEqual(len(report), 2)
421 self.assertEqual(report[0][1], 8192)
422 self.assertEqual(report[0][2], 5)
423
424 def test_reporthook_8193_bytes(self):
425 # Test on 8193 byte file. Should call reporthook only 3 times (once
426 # when the "network connection" is established, once for the next 8192
427 # bytes, and once for the last byte).
428 report = []
429 def hooktester(count, block_size, total_size, _report=report):
430 _report.append((count, block_size, total_size))
Guido van Rossum70d0dda2007-08-29 01:53:26 +0000431 srcFileName = self.createNewTempFile(b"x" * 8193)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000432 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000433 support.TESTFN, hooktester)
Georg Brandl5a650a22005-08-26 08:51:34 +0000434 self.assertEqual(len(report), 3)
435 self.assertEqual(report[0][1], 8192)
436 self.assertEqual(report[0][2], 8193)
Skip Montanaro080c9972001-01-28 21:12:22 +0000437
Senthil Kumarance260142011-11-01 01:35:17 +0800438
439class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin):
440 """Test urllib.urlretrieve() using fake http connections"""
441
442 def test_short_content_raises_ContentTooShortError(self):
443 self.fakehttp(b'''HTTP/1.1 200 OK
444Date: Wed, 02 Jan 2008 03:03:54 GMT
445Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
446Connection: close
447Content-Length: 100
448Content-Type: text/html; charset=iso-8859-1
449
450FF
451''')
452
453 def _reporthook(par1, par2, par3):
454 pass
455
456 with self.assertRaises(urllib.error.ContentTooShortError):
457 try:
458 urllib.request.urlretrieve('http://example.com/',
459 reporthook=_reporthook)
460 finally:
461 self.unfakehttp()
462
463 def test_short_content_raises_ContentTooShortError_without_reporthook(self):
464 self.fakehttp(b'''HTTP/1.1 200 OK
465Date: Wed, 02 Jan 2008 03:03:54 GMT
466Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
467Connection: close
468Content-Length: 100
469Content-Type: text/html; charset=iso-8859-1
470
471FF
472''')
473 with self.assertRaises(urllib.error.ContentTooShortError):
474 try:
475 urllib.request.urlretrieve('http://example.com/')
476 finally:
477 self.unfakehttp()
478
479
Brett Cannon74bfd702003-04-25 09:39:47 +0000480class QuotingTests(unittest.TestCase):
481 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000482
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000483 According to RFC 2396 (Uniform Resource Identifiers), to escape a
484 character you write it as '%' + <2 character US-ASCII hex value>.
485 The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
486 character properly. Case does not matter on the hex letters.
Brett Cannon74bfd702003-04-25 09:39:47 +0000487
488 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000489
Brett Cannon74bfd702003-04-25 09:39:47 +0000490 Reserved characters : ";/?:@&=+$,"
491 Have special meaning in URIs and must be escaped if not being used for
492 their special meaning
493 Data characters : letters, digits, and "-_.!~*'()"
494 Unreserved and do not need to be escaped; can be, though, if desired
495 Control characters : 0x00 - 0x1F, 0x7F
496 Have no use in URIs so must be escaped
497 space : 0x20
498 Must be escaped
499 Delimiters : '<>#%"'
500 Must be escaped
501 Unwise : "{}|\^[]`"
502 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000503
Brett Cannon74bfd702003-04-25 09:39:47 +0000504 """
505
506 def test_never_quote(self):
507 # Make sure quote() does not quote letters, digits, and "_,.-"
508 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
509 "abcdefghijklmnopqrstuvwxyz",
510 "0123456789",
511 "_.-"])
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000512 result = urllib.parse.quote(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000513 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000514 "using quote(): %r != %r" % (do_not_quote, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000515 result = urllib.parse.quote_plus(do_not_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000516 self.assertEqual(do_not_quote, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000517 "using quote_plus(): %r != %r" % (do_not_quote, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000518
519 def test_default_safe(self):
520 # Test '/' is default value for 'safe' parameter
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000521 self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
Brett Cannon74bfd702003-04-25 09:39:47 +0000522
523 def test_safe(self):
524 # Test setting 'safe' parameter does what it should do
525 quote_by_default = "<>"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000526 result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000527 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000528 "using quote(): %r != %r" % (quote_by_default, result))
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000529 result = urllib.parse.quote_plus(quote_by_default,
530 safe=quote_by_default)
Brett Cannon74bfd702003-04-25 09:39:47 +0000531 self.assertEqual(quote_by_default, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000532 "using quote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000533 (quote_by_default, result))
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000534 # Safe expressed as bytes rather than str
535 result = urllib.parse.quote(quote_by_default, safe=b"<>")
536 self.assertEqual(quote_by_default, result,
537 "using quote(): %r != %r" % (quote_by_default, result))
538 # "Safe" non-ASCII characters should have no effect
539 # (Since URIs are not allowed to have non-ASCII characters)
540 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc")
541 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
542 self.assertEqual(expect, result,
543 "using quote(): %r != %r" %
544 (expect, result))
545 # Same as above, but using a bytes rather than str
546 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc")
547 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
548 self.assertEqual(expect, result,
549 "using quote(): %r != %r" %
550 (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000551
552 def test_default_quoting(self):
553 # Make sure all characters that should be quoted are by default sans
554 # space (separate test for that).
555 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
556 should_quote.append('<>#%"{}|\^[]`')
557 should_quote.append(chr(127)) # For 0x7F
558 should_quote = ''.join(should_quote)
559 for char in should_quote:
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000560 result = urllib.parse.quote(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000561 self.assertEqual(hexescape(char), result,
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000562 "using quote(): "
563 "%s should be escaped to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000564 (char, hexescape(char), result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000565 result = urllib.parse.quote_plus(char)
Brett Cannon74bfd702003-04-25 09:39:47 +0000566 self.assertEqual(hexescape(char), result,
567 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000568 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000569 (char, hexescape(char), result))
570 del should_quote
571 partial_quote = "ab[]cd"
572 expected = "ab%5B%5Dcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000573 result = urllib.parse.quote(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000574 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000575 "using quote(): %r != %r" % (expected, result))
Senthil Kumaran305a68e2011-09-13 06:40:27 +0800576 result = urllib.parse.quote_plus(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000577 self.assertEqual(expected, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000578 "using quote_plus(): %r != %r" % (expected, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000579
580 def test_quoting_space(self):
581 # Make sure quote() and quote_plus() handle spaces as specified in
582 # their unique way
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000583 result = urllib.parse.quote(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000584 self.assertEqual(result, hexescape(' '),
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000585 "using quote(): %r != %r" % (result, hexescape(' ')))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000586 result = urllib.parse.quote_plus(' ')
Brett Cannon74bfd702003-04-25 09:39:47 +0000587 self.assertEqual(result, '+',
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000588 "using quote_plus(): %r != +" % result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000589 given = "a b cd e f"
590 expect = given.replace(' ', hexescape(' '))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000591 result = urllib.parse.quote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000592 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000593 "using quote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000594 expect = given.replace(' ', '+')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000595 result = urllib.parse.quote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000596 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000597 "using quote_plus(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000598
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000599 def test_quoting_plus(self):
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000600 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000601 'alpha%2Bbeta+gamma')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000602 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000603 'alpha+beta+gamma')
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000604 # Test with bytes
605 self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
606 'alpha%2Bbeta+gamma')
607 # Test with safe bytes
608 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
609 'alpha+beta+gamma')
610
611 def test_quote_bytes(self):
612 # Bytes should quote directly to percent-encoded values
613 given = b"\xa2\xd8ab\xff"
614 expect = "%A2%D8ab%FF"
615 result = urllib.parse.quote(given)
616 self.assertEqual(expect, result,
617 "using quote(): %r != %r" % (expect, result))
618 # Encoding argument should raise type error on bytes input
619 self.assertRaises(TypeError, urllib.parse.quote, given,
620 encoding="latin-1")
621 # quote_from_bytes should work the same
622 result = urllib.parse.quote_from_bytes(given)
623 self.assertEqual(expect, result,
624 "using quote_from_bytes(): %r != %r"
625 % (expect, result))
626
627 def test_quote_with_unicode(self):
628 # Characters in Latin-1 range, encoded by default in UTF-8
629 given = "\xa2\xd8ab\xff"
630 expect = "%C2%A2%C3%98ab%C3%BF"
631 result = urllib.parse.quote(given)
632 self.assertEqual(expect, result,
633 "using quote(): %r != %r" % (expect, result))
634 # Characters in Latin-1 range, encoded by with None (default)
635 result = urllib.parse.quote(given, encoding=None, errors=None)
636 self.assertEqual(expect, result,
637 "using quote(): %r != %r" % (expect, result))
638 # Characters in Latin-1 range, encoded with Latin-1
639 given = "\xa2\xd8ab\xff"
640 expect = "%A2%D8ab%FF"
641 result = urllib.parse.quote(given, encoding="latin-1")
642 self.assertEqual(expect, result,
643 "using quote(): %r != %r" % (expect, result))
644 # Characters in BMP, encoded by default in UTF-8
645 given = "\u6f22\u5b57" # "Kanji"
646 expect = "%E6%BC%A2%E5%AD%97"
647 result = urllib.parse.quote(given)
648 self.assertEqual(expect, result,
649 "using quote(): %r != %r" % (expect, result))
650 # Characters in BMP, encoded with Latin-1
651 given = "\u6f22\u5b57"
652 self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
653 encoding="latin-1")
654 # Characters in BMP, encoded with Latin-1, with replace error handling
655 given = "\u6f22\u5b57"
656 expect = "%3F%3F" # "??"
657 result = urllib.parse.quote(given, encoding="latin-1",
658 errors="replace")
659 self.assertEqual(expect, result,
660 "using quote(): %r != %r" % (expect, result))
661 # Characters in BMP, Latin-1, with xmlcharref error handling
662 given = "\u6f22\u5b57"
663 expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;"
664 result = urllib.parse.quote(given, encoding="latin-1",
665 errors="xmlcharrefreplace")
666 self.assertEqual(expect, result,
667 "using quote(): %r != %r" % (expect, result))
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000668
Georg Brandlfaf41492009-05-26 18:31:11 +0000669 def test_quote_plus_with_unicode(self):
670 # Encoding (latin-1) test for quote_plus
671 given = "\xa2\xd8 \xff"
672 expect = "%A2%D8+%FF"
673 result = urllib.parse.quote_plus(given, encoding="latin-1")
674 self.assertEqual(expect, result,
675 "using quote_plus(): %r != %r" % (expect, result))
676 # Errors test for quote_plus
677 given = "ab\u6f22\u5b57 cd"
678 expect = "ab%3F%3F+cd"
679 result = urllib.parse.quote_plus(given, encoding="latin-1",
680 errors="replace")
681 self.assertEqual(expect, result,
682 "using quote_plus(): %r != %r" % (expect, result))
683
Senthil Kumarand496c4c2010-07-30 19:34:36 +0000684
Brett Cannon74bfd702003-04-25 09:39:47 +0000685class UnquotingTests(unittest.TestCase):
686 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000687
Brett Cannon74bfd702003-04-25 09:39:47 +0000688 See the doc string for quoting_Tests for details on quoting and such.
689
690 """
691
692 def test_unquoting(self):
693 # Make sure unquoting of all ASCII values works
694 escape_list = []
695 for num in range(128):
696 given = hexescape(chr(num))
697 expect = chr(num)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000698 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000699 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000700 "using unquote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000701 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000702 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000703 "using unquote_plus(): %r != %r" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000704 (expect, result))
705 escape_list.append(given)
706 escape_string = ''.join(escape_list)
707 del escape_list
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000708 result = urllib.parse.unquote(escape_string)
Brett Cannon74bfd702003-04-25 09:39:47 +0000709 self.assertEqual(result.count('%'), 1,
Brett Cannon74bfd702003-04-25 09:39:47 +0000710 "using unquote(): not all characters escaped: "
711 "%s" % result)
Georg Brandl604ef372010-07-31 08:20:02 +0000712 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
713 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
Florent Xicluna62829dc2010-08-14 20:51:58 +0000714 with support.check_warnings(('', BytesWarning), quiet=True):
715 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, b'')
Brett Cannon74bfd702003-04-25 09:39:47 +0000716
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000717 def test_unquoting_badpercent(self):
718 # Test unquoting on bad percent-escapes
719 given = '%xab'
720 expect = given
721 result = urllib.parse.unquote(given)
722 self.assertEqual(expect, result, "using unquote(): %r != %r"
723 % (expect, result))
724 given = '%x'
725 expect = given
726 result = urllib.parse.unquote(given)
727 self.assertEqual(expect, result, "using unquote(): %r != %r"
728 % (expect, result))
729 given = '%'
730 expect = given
731 result = urllib.parse.unquote(given)
732 self.assertEqual(expect, result, "using unquote(): %r != %r"
733 % (expect, result))
734 # unquote_to_bytes
735 given = '%xab'
736 expect = bytes(given, 'ascii')
737 result = urllib.parse.unquote_to_bytes(given)
738 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
739 % (expect, result))
740 given = '%x'
741 expect = bytes(given, 'ascii')
742 result = urllib.parse.unquote_to_bytes(given)
743 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
744 % (expect, result))
745 given = '%'
746 expect = bytes(given, 'ascii')
747 result = urllib.parse.unquote_to_bytes(given)
748 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
749 % (expect, result))
Georg Brandl604ef372010-07-31 08:20:02 +0000750 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None)
751 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ())
Senthil Kumaran79e17f62010-07-19 18:17:19 +0000752
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000753 def test_unquoting_mixed_case(self):
754 # Test unquoting on mixed-case hex digits in the percent-escapes
755 given = '%Ab%eA'
756 expect = b'\xab\xea'
757 result = urllib.parse.unquote_to_bytes(given)
758 self.assertEqual(expect, result,
759 "using unquote_to_bytes(): %r != %r"
760 % (expect, result))
761
Brett Cannon74bfd702003-04-25 09:39:47 +0000762 def test_unquoting_parts(self):
763 # Make sure unquoting works when have non-quoted characters
764 # interspersed
765 given = 'ab%sd' % hexescape('c')
766 expect = "abcd"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000767 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000768 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000769 "using quote(): %r != %r" % (expect, result))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000770 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000771 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000772 "using unquote_plus(): %r != %r" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000773
Brett Cannon74bfd702003-04-25 09:39:47 +0000774 def test_unquoting_plus(self):
775 # Test difference between unquote() and unquote_plus()
776 given = "are+there+spaces..."
777 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000778 result = urllib.parse.unquote(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000779 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000780 "using unquote(): %r != %r" % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000781 expect = given.replace('+', ' ')
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000782 result = urllib.parse.unquote_plus(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000783 self.assertEqual(expect, result,
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000784 "using unquote_plus(): %r != %r" % (expect, result))
785
786 def test_unquote_to_bytes(self):
787 given = 'br%C3%BCckner_sapporo_20050930.doc'
788 expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
789 result = urllib.parse.unquote_to_bytes(given)
790 self.assertEqual(expect, result,
791 "using unquote_to_bytes(): %r != %r"
792 % (expect, result))
793 # Test on a string with unescaped non-ASCII characters
794 # (Technically an invalid URI; expect those characters to be UTF-8
795 # encoded).
796 result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
797 expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
798 self.assertEqual(expect, result,
799 "using unquote_to_bytes(): %r != %r"
800 % (expect, result))
801 # Test with a bytes as input
802 given = b'%A2%D8ab%FF'
803 expect = b'\xa2\xd8ab\xff'
804 result = urllib.parse.unquote_to_bytes(given)
805 self.assertEqual(expect, result,
806 "using unquote_to_bytes(): %r != %r"
807 % (expect, result))
808 # Test with a bytes as input, with unescaped non-ASCII bytes
809 # (Technically an invalid URI; expect those bytes to be preserved)
810 given = b'%A2\xd8ab%FF'
811 expect = b'\xa2\xd8ab\xff'
812 result = urllib.parse.unquote_to_bytes(given)
813 self.assertEqual(expect, result,
814 "using unquote_to_bytes(): %r != %r"
815 % (expect, result))
Brett Cannon74bfd702003-04-25 09:39:47 +0000816
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000817 def test_unquote_with_unicode(self):
Guido van Rossum52dbbb92008-08-18 21:44:30 +0000818 # Characters in the Latin-1 range, encoded with UTF-8
819 given = 'br%C3%BCckner_sapporo_20050930.doc'
820 expect = 'br\u00fcckner_sapporo_20050930.doc'
821 result = urllib.parse.unquote(given)
822 self.assertEqual(expect, result,
823 "using unquote(): %r != %r" % (expect, result))
824 # Characters in the Latin-1 range, encoded with None (default)
825 result = urllib.parse.unquote(given, encoding=None, errors=None)
826 self.assertEqual(expect, result,
827 "using unquote(): %r != %r" % (expect, result))
828
829 # Characters in the Latin-1 range, encoded with Latin-1
830 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
831 encoding="latin-1")
832 expect = 'br\u00fcckner_sapporo_20050930.doc'
833 self.assertEqual(expect, result,
834 "using unquote(): %r != %r" % (expect, result))
835
836 # Characters in BMP, encoded with UTF-8
837 given = "%E6%BC%A2%E5%AD%97"
838 expect = "\u6f22\u5b57" # "Kanji"
839 result = urllib.parse.unquote(given)
840 self.assertEqual(expect, result,
841 "using unquote(): %r != %r" % (expect, result))
842
843 # Decode with UTF-8, invalid sequence
844 given = "%F3%B1"
845 expect = "\ufffd" # Replacement character
846 result = urllib.parse.unquote(given)
847 self.assertEqual(expect, result,
848 "using unquote(): %r != %r" % (expect, result))
849
850 # Decode with UTF-8, invalid sequence, replace errors
851 result = urllib.parse.unquote(given, errors="replace")
852 self.assertEqual(expect, result,
853 "using unquote(): %r != %r" % (expect, result))
854
855 # Decode with UTF-8, invalid sequence, ignoring errors
856 given = "%F3%B1"
857 expect = ""
858 result = urllib.parse.unquote(given, errors="ignore")
859 self.assertEqual(expect, result,
860 "using unquote(): %r != %r" % (expect, result))
861
862 # A mix of non-ASCII and percent-encoded characters, UTF-8
863 result = urllib.parse.unquote("\u6f22%C3%BC")
864 expect = '\u6f22\u00fc'
865 self.assertEqual(expect, result,
866 "using unquote(): %r != %r" % (expect, result))
867
868 # A mix of non-ASCII and percent-encoded characters, Latin-1
869 # (Note, the string contains non-Latin-1-representable characters)
870 result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
871 expect = '\u6f22\u00fc'
872 self.assertEqual(expect, result,
873 "using unquote(): %r != %r" % (expect, result))
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000874
Brett Cannon74bfd702003-04-25 09:39:47 +0000875class urlencode_Tests(unittest.TestCase):
876 """Tests for urlencode()"""
877
878 def help_inputtype(self, given, test_type):
879 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000880
Brett Cannon74bfd702003-04-25 09:39:47 +0000881 'given' must lead to only the pairs:
882 * 1st, 1
883 * 2nd, 2
884 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000885
Brett Cannon74bfd702003-04-25 09:39:47 +0000886 Test cannot assume anything about order. Docs make no guarantee and
887 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000888
Brett Cannon74bfd702003-04-25 09:39:47 +0000889 """
890 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000891 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000892 for expected in expect_somewhere:
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000893 self.assertIn(expected, result,
Brett Cannon74bfd702003-04-25 09:39:47 +0000894 "testing %s: %s not found in %s" %
895 (test_type, expected, result))
896 self.assertEqual(result.count('&'), 2,
897 "testing %s: expected 2 '&'s; got %s" %
898 (test_type, result.count('&')))
899 amp_location = result.index('&')
900 on_amp_left = result[amp_location - 1]
901 on_amp_right = result[amp_location + 1]
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000902 self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000903 "testing %s: '&' not located in proper place in %s" %
904 (test_type, result))
905 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
906 "testing %s: "
907 "unexpected number of characters: %s != %s" %
908 (test_type, len(result), (5 * 3) + 2))
909
910 def test_using_mapping(self):
911 # Test passing in a mapping object as an argument.
912 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
913 "using dict as input type")
914
915 def test_using_sequence(self):
916 # Test passing in a sequence of two-item sequences as an argument.
917 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
918 "using sequence of two-item tuples as input")
919
920 def test_quoting(self):
921 # Make sure keys and values are quoted using quote_plus()
922 given = {"&":"="}
923 expect = "%s=%s" % (hexescape('&'), hexescape('='))
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000924 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000925 self.assertEqual(expect, result)
926 given = {"key name":"A bunch of pluses"}
927 expect = "key+name=A+bunch+of+pluses"
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000928 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000929 self.assertEqual(expect, result)
930
931 def test_doseq(self):
932 # Test that passing True for 'doseq' parameter works correctly
933 given = {'sequence':['1', '2', '3']}
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000934 expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
935 result = urllib.parse.urlencode(given)
Brett Cannon74bfd702003-04-25 09:39:47 +0000936 self.assertEqual(expect, result)
Jeremy Hylton1afc1692008-06-18 20:49:58 +0000937 result = urllib.parse.urlencode(given, True)
Brett Cannon74bfd702003-04-25 09:39:47 +0000938 for value in given["sequence"]:
939 expect = "sequence=%s" % value
Ezio Melottib58e0bd2010-01-23 15:40:09 +0000940 self.assertIn(expect, result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000941 self.assertEqual(result.count('&'), 2,
942 "Expected 2 '&'s, got %s" % result.count('&'))
943
Jeremy Hylton1ef7c6b2009-03-26 16:57:30 +0000944 def test_empty_sequence(self):
945 self.assertEqual("", urllib.parse.urlencode({}))
946 self.assertEqual("", urllib.parse.urlencode([]))
947
948 def test_nonstring_values(self):
949 self.assertEqual("a=1", urllib.parse.urlencode({"a": 1}))
950 self.assertEqual("a=None", urllib.parse.urlencode({"a": None}))
951
952 def test_nonstring_seq_values(self):
953 self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True))
954 self.assertEqual("a=None&a=a",
955 urllib.parse.urlencode({"a": [None, "a"]}, True))
956 self.assertEqual("a=a&a=b",
957 urllib.parse.urlencode({"a": {"a": 1, "b": 1}}, True))
958
Senthil Kumarandf022da2010-07-03 17:48:22 +0000959 def test_urlencode_encoding(self):
960 # ASCII encoding. Expect %3F with errors="replace'
961 given = (('\u00a0', '\u00c1'),)
962 expect = '%3F=%3F'
963 result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
964 self.assertEqual(expect, result)
965
966 # Default is UTF-8 encoding.
967 given = (('\u00a0', '\u00c1'),)
968 expect = '%C2%A0=%C3%81'
969 result = urllib.parse.urlencode(given)
970 self.assertEqual(expect, result)
971
972 # Latin-1 encoding.
973 given = (('\u00a0', '\u00c1'),)
974 expect = '%A0=%C1'
975 result = urllib.parse.urlencode(given, encoding="latin-1")
976 self.assertEqual(expect, result)
977
978 def test_urlencode_encoding_doseq(self):
979 # ASCII Encoding. Expect %3F with errors="replace'
980 given = (('\u00a0', '\u00c1'),)
981 expect = '%3F=%3F'
982 result = urllib.parse.urlencode(given, doseq=True,
983 encoding="ASCII", errors="replace")
984 self.assertEqual(expect, result)
985
986 # ASCII Encoding. On a sequence of values.
987 given = (("\u00a0", (1, "\u00c1")),)
988 expect = '%3F=1&%3F=%3F'
989 result = urllib.parse.urlencode(given, True,
990 encoding="ASCII", errors="replace")
991 self.assertEqual(expect, result)
992
993 # Utf-8
994 given = (("\u00a0", "\u00c1"),)
995 expect = '%C2%A0=%C3%81'
996 result = urllib.parse.urlencode(given, True)
997 self.assertEqual(expect, result)
998
999 given = (("\u00a0", (42, "\u00c1")),)
1000 expect = '%C2%A0=42&%C2%A0=%C3%81'
1001 result = urllib.parse.urlencode(given, True)
1002 self.assertEqual(expect, result)
1003
1004 # latin-1
1005 given = (("\u00a0", "\u00c1"),)
1006 expect = '%A0=%C1'
1007 result = urllib.parse.urlencode(given, True, encoding="latin-1")
1008 self.assertEqual(expect, result)
1009
1010 given = (("\u00a0", (42, "\u00c1")),)
1011 expect = '%A0=42&%A0=%C1'
1012 result = urllib.parse.urlencode(given, True, encoding="latin-1")
1013 self.assertEqual(expect, result)
1014
1015 def test_urlencode_bytes(self):
1016 given = ((b'\xa0\x24', b'\xc1\x24'),)
1017 expect = '%A0%24=%C1%24'
1018 result = urllib.parse.urlencode(given)
1019 self.assertEqual(expect, result)
1020 result = urllib.parse.urlencode(given, True)
1021 self.assertEqual(expect, result)
1022
1023 # Sequence of values
1024 given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
1025 expect = '%A0%24=42&%A0%24=%C1%24'
1026 result = urllib.parse.urlencode(given, True)
1027 self.assertEqual(expect, result)
1028
1029 def test_urlencode_encoding_safe_parameter(self):
1030
1031 # Send '$' (\x24) as safe character
1032 # Default utf-8 encoding
1033
1034 given = ((b'\xa0\x24', b'\xc1\x24'),)
1035 result = urllib.parse.urlencode(given, safe=":$")
1036 expect = '%A0$=%C1$'
1037 self.assertEqual(expect, result)
1038
1039 given = ((b'\xa0\x24', b'\xc1\x24'),)
1040 result = urllib.parse.urlencode(given, doseq=True, safe=":$")
1041 expect = '%A0$=%C1$'
1042 self.assertEqual(expect, result)
1043
1044 # Safe parameter in sequence
1045 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
1046 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
1047 result = urllib.parse.urlencode(given, True, safe=":$")
1048 self.assertEqual(expect, result)
1049
1050 # Test all above in latin-1 encoding
1051
1052 given = ((b'\xa0\x24', b'\xc1\x24'),)
1053 result = urllib.parse.urlencode(given, safe=":$",
1054 encoding="latin-1")
1055 expect = '%A0$=%C1$'
1056 self.assertEqual(expect, result)
1057
1058 given = ((b'\xa0\x24', b'\xc1\x24'),)
1059 expect = '%A0$=%C1$'
1060 result = urllib.parse.urlencode(given, doseq=True, safe=":$",
1061 encoding="latin-1")
1062
1063 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
1064 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
1065 result = urllib.parse.urlencode(given, True, safe=":$",
1066 encoding="latin-1")
1067 self.assertEqual(expect, result)
1068
Brett Cannon74bfd702003-04-25 09:39:47 +00001069class Pathname_Tests(unittest.TestCase):
1070 """Test pathname2url() and url2pathname()"""
1071
1072 def test_basic(self):
1073 # Make sure simple tests pass
1074 expected_path = os.path.join("parts", "of", "a", "path")
1075 expected_url = "parts/of/a/path"
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001076 result = urllib.request.pathname2url(expected_path)
Brett Cannon74bfd702003-04-25 09:39:47 +00001077 self.assertEqual(expected_url, result,
1078 "pathname2url() failed; %s != %s" %
1079 (result, expected_url))
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001080 result = urllib.request.url2pathname(expected_url)
Brett Cannon74bfd702003-04-25 09:39:47 +00001081 self.assertEqual(expected_path, result,
1082 "url2pathame() failed; %s != %s" %
1083 (result, expected_path))
1084
1085 def test_quoting(self):
1086 # Test automatic quoting and unquoting works for pathnam2url() and
1087 # url2pathname() respectively
1088 given = os.path.join("needs", "quot=ing", "here")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001089 expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
1090 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +00001091 self.assertEqual(expect, result,
1092 "pathname2url() failed; %s != %s" %
1093 (expect, result))
1094 expect = given
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001095 result = urllib.request.url2pathname(result)
Brett Cannon74bfd702003-04-25 09:39:47 +00001096 self.assertEqual(expect, result,
1097 "url2pathname() failed; %s != %s" %
1098 (expect, result))
1099 given = os.path.join("make sure", "using_quote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001100 expect = "%s/using_quote" % urllib.parse.quote("make sure")
1101 result = urllib.request.pathname2url(given)
Brett Cannon74bfd702003-04-25 09:39:47 +00001102 self.assertEqual(expect, result,
1103 "pathname2url() failed; %s != %s" %
1104 (expect, result))
1105 given = "make+sure/using_unquote"
1106 expect = os.path.join("make+sure", "using_unquote")
Jeremy Hylton1afc1692008-06-18 20:49:58 +00001107 result = urllib.request.url2pathname(given)
Brett Cannon74bfd702003-04-25 09:39:47 +00001108 self.assertEqual(expect, result,
1109 "url2pathname() failed; %s != %s" %
1110 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +00001111
Senthil Kumaran2d2ea1b2011-04-14 13:16:30 +08001112 @unittest.skipUnless(sys.platform == 'win32',
1113 'test specific to the urllib.url2path function.')
1114 def test_ntpath(self):
1115 given = ('/C:/', '///C:/', '/C|//')
1116 expect = 'C:\\'
1117 for url in given:
1118 result = urllib.request.url2pathname(url)
1119 self.assertEqual(expect, result,
1120 'urllib.request..url2pathname() failed; %s != %s' %
1121 (expect, result))
1122 given = '///C|/path'
1123 expect = 'C:\\path'
1124 result = urllib.request.url2pathname(given)
1125 self.assertEqual(expect, result,
1126 'urllib.request.url2pathname() failed; %s != %s' %
1127 (expect, result))
1128
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001129class Utility_Tests(unittest.TestCase):
1130 """Testcase to test the various utility functions in the urllib."""
1131
1132 def test_splitpasswd(self):
1133 """Some of password examples are not sensible, but it is added to
1134 confirming to RFC2617 and addressing issue4675.
1135 """
1136 self.assertEqual(('user', 'ab'),urllib.parse.splitpasswd('user:ab'))
1137 self.assertEqual(('user', 'a\nb'),urllib.parse.splitpasswd('user:a\nb'))
1138 self.assertEqual(('user', 'a\tb'),urllib.parse.splitpasswd('user:a\tb'))
1139 self.assertEqual(('user', 'a\rb'),urllib.parse.splitpasswd('user:a\rb'))
1140 self.assertEqual(('user', 'a\fb'),urllib.parse.splitpasswd('user:a\fb'))
1141 self.assertEqual(('user', 'a\vb'),urllib.parse.splitpasswd('user:a\vb'))
1142 self.assertEqual(('user', 'a:b'),urllib.parse.splitpasswd('user:a:b'))
Senthil Kumaranc5c5a142012-01-14 19:09:04 +08001143 self.assertEqual(('user', 'a b'),urllib.parse.splitpasswd('user:a b'))
1144 self.assertEqual(('user 2', 'ab'),urllib.parse.splitpasswd('user 2:ab'))
1145 self.assertEqual(('user+1', 'a+b'),urllib.parse.splitpasswd('user+1:a+b'))
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001146
Senthil Kumaran1b7da512011-10-06 00:32:02 +08001147 def test_thishost(self):
1148 """Test the urllib.request.thishost utility function returns a tuple"""
1149 self.assertIsInstance(urllib.request.thishost(), tuple)
1150
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001151
1152class URLopener_Tests(unittest.TestCase):
1153 """Testcase to test the open method of URLopener class."""
1154
1155 def test_quoted_open(self):
1156 class DummyURLopener(urllib.request.URLopener):
1157 def open_spam(self, url):
1158 return url
1159
1160 self.assertEqual(DummyURLopener().open(
1161 'spam://example/ /'),'//example/%20/')
1162
Senthil Kumaran734f0592010-02-20 22:19:04 +00001163 # test the safe characters are not quoted by urlopen
1164 self.assertEqual(DummyURLopener().open(
1165 "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
1166 "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
1167
Guido van Rossume7ba4952007-06-06 23:52:48 +00001168# Just commented them out.
1169# Can't really tell why keep failing in windows and sparc.
Ezio Melotti13925002011-03-16 11:05:33 +02001170# Everywhere else they work ok, but on those machines, sometimes
Guido van Rossume7ba4952007-06-06 23:52:48 +00001171# fail in one of the tests, sometimes in other. I have a linux, and
1172# the tests go ok.
1173# If anybody has one of the problematic enviroments, please help!
1174# . Facundo
1175#
1176# def server(evt):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001177# import socket, time
Guido van Rossume7ba4952007-06-06 23:52:48 +00001178# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1179# serv.settimeout(3)
1180# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1181# serv.bind(("", 9093))
1182# serv.listen(5)
1183# try:
1184# conn, addr = serv.accept()
1185# conn.send("1 Hola mundo\n")
1186# cantdata = 0
1187# while cantdata < 13:
1188# data = conn.recv(13-cantdata)
1189# cantdata += len(data)
1190# time.sleep(.3)
1191# conn.send("2 No more lines\n")
1192# conn.close()
1193# except socket.timeout:
1194# pass
1195# finally:
1196# serv.close()
1197# evt.set()
1198#
1199# class FTPWrapperTests(unittest.TestCase):
1200#
1201# def setUp(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001202# import ftplib, time, threading
Guido van Rossume7ba4952007-06-06 23:52:48 +00001203# ftplib.FTP.port = 9093
1204# self.evt = threading.Event()
1205# threading.Thread(target=server, args=(self.evt,)).start()
1206# time.sleep(.1)
1207#
1208# def tearDown(self):
1209# self.evt.wait()
1210#
1211# def testBasic(self):
1212# # connects
1213# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Georg Brandlf78e02b2008-06-10 17:40:04 +00001214# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001215#
1216# def testTimeoutNone(self):
Georg Brandlf78e02b2008-06-10 17:40:04 +00001217# # global default timeout is ignored
1218# import socket
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001219# self.assertTrue(socket.getdefaulttimeout() is None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001220# socket.setdefaulttimeout(30)
1221# try:
1222# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
1223# finally:
Georg Brandlf78e02b2008-06-10 17:40:04 +00001224# socket.setdefaulttimeout(None)
Guido van Rossume7ba4952007-06-06 23:52:48 +00001225# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001226# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001227#
Georg Brandlf78e02b2008-06-10 17:40:04 +00001228# def testTimeoutDefault(self):
1229# # global default timeout is used
1230# import socket
Benjamin Petersonc9c0f202009-06-30 23:06:06 +00001231# self.assertTrue(socket.getdefaulttimeout() is None)
Georg Brandlf78e02b2008-06-10 17:40:04 +00001232# socket.setdefaulttimeout(30)
1233# try:
1234# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
1235# finally:
1236# socket.setdefaulttimeout(None)
1237# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
1238# ftp.close()
1239#
1240# def testTimeoutValue(self):
1241# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
1242# timeout=30)
1243# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
1244# ftp.close()
Guido van Rossume7ba4952007-06-06 23:52:48 +00001245
Senthil Kumarande49d642011-10-16 23:54:44 +08001246class RequestTests(unittest.TestCase):
1247 """Unit tests for urllib.request.Request."""
1248
1249 def test_default_values(self):
1250 Request = urllib.request.Request
1251 request = Request("http://www.python.org")
1252 self.assertEqual(request.get_method(), 'GET')
1253 request = Request("http://www.python.org", {})
1254 self.assertEqual(request.get_method(), 'POST')
1255
1256 def test_with_method_arg(self):
1257 Request = urllib.request.Request
1258 request = Request("http://www.python.org", method='HEAD')
1259 self.assertEqual(request.method, 'HEAD')
1260 self.assertEqual(request.get_method(), 'HEAD')
1261 request = Request("http://www.python.org", {}, method='HEAD')
1262 self.assertEqual(request.method, 'HEAD')
1263 self.assertEqual(request.get_method(), 'HEAD')
1264 request = Request("http://www.python.org", method='GET')
1265 self.assertEqual(request.get_method(), 'GET')
1266 request.method = 'HEAD'
1267 self.assertEqual(request.get_method(), 'HEAD')
Skip Montanaro080c9972001-01-28 21:12:22 +00001268
1269
Brett Cannon74bfd702003-04-25 09:39:47 +00001270def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001271 support.run_unittest(
Walter Dörwald21d3a322003-05-01 17:45:56 +00001272 urlopen_FileTests,
Hye-Shik Chang39aef792004-06-05 13:30:56 +00001273 urlopen_HttpTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001274 urlretrieve_FileTests,
Senthil Kumarance260142011-11-01 01:35:17 +08001275 urlretrieve_HttpTests,
Benjamin Peterson9bc93512008-09-22 22:10:59 +00001276 ProxyTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001277 QuotingTests,
1278 UnquotingTests,
1279 urlencode_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001280 Pathname_Tests,
Senthil Kumaraneaaec272009-03-30 21:54:41 +00001281 Utility_Tests,
Senthil Kumaran690ce9b2009-05-05 18:41:13 +00001282 URLopener_Tests,
Guido van Rossume7ba4952007-06-06 23:52:48 +00001283 #FTPWrapperTests,
Senthil Kumarande49d642011-10-16 23:54:44 +08001284 RequestTests,
Walter Dörwald21d3a322003-05-01 17:45:56 +00001285 )
Brett Cannon74bfd702003-04-25 09:39:47 +00001286
1287
1288
1289if __name__ == '__main__':
1290 test_main()