blob: adffb5731f046228bd45635480c9fbd4251559b2 [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
Brett Cannon74bfd702003-04-25 09:39:47 +00006import os
Senthil Kumarana99b7612011-04-14 12:54:35 +08007import sys
Brett Cannon74bfd702003-04-25 09:39:47 +00008import mimetools
Georg Brandl5a650a22005-08-26 08:51:34 +00009import tempfile
Hye-Shik Chang39aef792004-06-05 13:30:56 +000010import StringIO
Jeremy Hylton6102e292000-08-31 15:48:10 +000011
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080012from test import test_support
13from base64 import b64encode
14
15
Brett Cannon74bfd702003-04-25 09:39:47 +000016def hexescape(char):
17 """Escape char as RFC 2396 specifies"""
18 hex_repr = hex(ord(char))[2:].upper()
19 if len(hex_repr) == 1:
20 hex_repr = "0%s" % hex_repr
21 return "%" + hex_repr
Jeremy Hylton6102e292000-08-31 15:48:10 +000022
Senthil Kumaran87e58552011-11-01 02:44:45 +080023
24class FakeHTTPMixin(object):
25 def fakehttp(self, fakedata):
26 class FakeSocket(StringIO.StringIO):
27
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080028 def sendall(self, data):
29 FakeHTTPConnection.buf = data
30
Senthil Kumaran87e58552011-11-01 02:44:45 +080031 def makefile(self, *args, **kwds):
32 return self
33
34 def read(self, amt=None):
35 if self.closed:
36 return ""
37 return StringIO.StringIO.read(self, amt)
38
39 def readline(self, length=None):
40 if self.closed:
41 return ""
42 return StringIO.StringIO.readline(self, length)
43
44 class FakeHTTPConnection(httplib.HTTPConnection):
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080045
46 # buffer to store data for verification in urlopen tests.
47 buf = ""
48
Senthil Kumaran87e58552011-11-01 02:44:45 +080049 def connect(self):
50 self.sock = FakeSocket(fakedata)
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080051
Senthil Kumaran87e58552011-11-01 02:44:45 +080052 assert httplib.HTTP._connection_class == httplib.HTTPConnection
Senthil Kumaranbcd833f2012-01-11 00:09:24 +080053
Senthil Kumaran87e58552011-11-01 02:44:45 +080054 httplib.HTTP._connection_class = FakeHTTPConnection
55
56 def unfakehttp(self):
57 httplib.HTTP._connection_class = httplib.HTTPConnection
58
59
Brett Cannon74bfd702003-04-25 09:39:47 +000060class urlopen_FileTests(unittest.TestCase):
61 """Test urlopen() opening a temporary file.
Jeremy Hylton6102e292000-08-31 15:48:10 +000062
Brett Cannon74bfd702003-04-25 09:39:47 +000063 Try to test as much functionality as possible so as to cut down on reliance
Andrew M. Kuchlingf1a2f9e2004-06-29 13:07:53 +000064 on connecting to the Net for testing.
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000065
Brett Cannon74bfd702003-04-25 09:39:47 +000066 """
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000067
Brett Cannon74bfd702003-04-25 09:39:47 +000068 def setUp(self):
69 """Setup of a temp file to use for testing"""
70 self.text = "test_urllib: %s\n" % self.__class__.__name__
Guido van Rossum51735b02003-04-25 15:01:05 +000071 FILE = file(test_support.TESTFN, 'wb')
Brett Cannon74bfd702003-04-25 09:39:47 +000072 try:
73 FILE.write(self.text)
74 finally:
75 FILE.close()
76 self.pathname = test_support.TESTFN
77 self.returned_obj = urllib.urlopen("file:%s" % self.pathname)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000078
Brett Cannon74bfd702003-04-25 09:39:47 +000079 def tearDown(self):
80 """Shut down the open object"""
81 self.returned_obj.close()
Brett Cannon19691362003-04-29 05:08:06 +000082 os.remove(test_support.TESTFN)
Jeremy Hylton7ae51bf2000-09-14 16:59:07 +000083
Brett Cannon74bfd702003-04-25 09:39:47 +000084 def test_interface(self):
85 # Make sure object returned by urlopen() has the specified methods
86 for attr in ("read", "readline", "readlines", "fileno",
Georg Brandl9b0d46d2008-01-20 11:43:03 +000087 "close", "info", "geturl", "getcode", "__iter__"):
Benjamin Peterson5c8da862009-06-30 22:57:08 +000088 self.assertTrue(hasattr(self.returned_obj, attr),
Brett Cannon74bfd702003-04-25 09:39:47 +000089 "object returned by urlopen() lacks %s attribute" %
90 attr)
Skip Montanaroe78b92a2001-01-20 20:22:30 +000091
Brett Cannon74bfd702003-04-25 09:39:47 +000092 def test_read(self):
93 self.assertEqual(self.text, self.returned_obj.read())
Skip Montanaro080c9972001-01-28 21:12:22 +000094
Brett Cannon74bfd702003-04-25 09:39:47 +000095 def test_readline(self):
96 self.assertEqual(self.text, self.returned_obj.readline())
97 self.assertEqual('', self.returned_obj.readline(),
98 "calling readline() after exhausting the file did not"
99 " return an empty string")
Skip Montanaro080c9972001-01-28 21:12:22 +0000100
Brett Cannon74bfd702003-04-25 09:39:47 +0000101 def test_readlines(self):
102 lines_list = self.returned_obj.readlines()
103 self.assertEqual(len(lines_list), 1,
104 "readlines() returned the wrong number of lines")
105 self.assertEqual(lines_list[0], self.text,
106 "readlines() returned improper text")
Skip Montanaro080c9972001-01-28 21:12:22 +0000107
Brett Cannon74bfd702003-04-25 09:39:47 +0000108 def test_fileno(self):
109 file_num = self.returned_obj.fileno()
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000110 self.assertIsInstance(file_num, int, "fileno() did not return an int")
Brett Cannon74bfd702003-04-25 09:39:47 +0000111 self.assertEqual(os.read(file_num, len(self.text)), self.text,
112 "Reading on the file descriptor returned by fileno() "
113 "did not return the expected text")
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000114
Brett Cannon74bfd702003-04-25 09:39:47 +0000115 def test_close(self):
116 # Test close() by calling it hear and then having it be called again
117 # by the tearDown() method for the test
118 self.returned_obj.close()
Skip Montanaro080c9972001-01-28 21:12:22 +0000119
Brett Cannon74bfd702003-04-25 09:39:47 +0000120 def test_info(self):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000121 self.assertIsInstance(self.returned_obj.info(), mimetools.Message)
Skip Montanaroe78b92a2001-01-20 20:22:30 +0000122
Brett Cannon74bfd702003-04-25 09:39:47 +0000123 def test_geturl(self):
124 self.assertEqual(self.returned_obj.geturl(), self.pathname)
Skip Montanaro080c9972001-01-28 21:12:22 +0000125
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000126 def test_getcode(self):
127 self.assertEqual(self.returned_obj.getcode(), None)
128
Brett Cannon74bfd702003-04-25 09:39:47 +0000129 def test_iter(self):
130 # Test iterator
131 # Don't need to count number of iterations since test would fail the
132 # instant it returned anything beyond the first line from the
133 # comparison
134 for line in self.returned_obj.__iter__():
135 self.assertEqual(line, self.text)
Skip Montanaro080c9972001-01-28 21:12:22 +0000136
Senthil Kumaran58c60622012-01-21 11:43:02 +0800137 def test_relativelocalfile(self):
138 self.assertRaises(ValueError,urllib.urlopen,'./' + self.pathname)
139
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000140class ProxyTests(unittest.TestCase):
141
142 def setUp(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000143 # Records changes to env vars
144 self.env = test_support.EnvironmentVarGuard()
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000145 # Delete all proxy related env vars
Senthil Kumaran7a2ee0b2010-01-08 19:20:25 +0000146 for k in os.environ.keys():
Walter Dörwald4b965f62009-04-26 20:51:44 +0000147 if 'proxy' in k.lower():
Senthil Kumarandc61ec32009-10-01 01:50:13 +0000148 self.env.unset(k)
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000149
150 def tearDown(self):
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000151 # Restore all proxy related env vars
Walter Dörwald4b965f62009-04-26 20:51:44 +0000152 self.env.__exit__()
153 del self.env
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000154
155 def test_getproxies_environment_keep_no_proxies(self):
Walter Dörwald4b965f62009-04-26 20:51:44 +0000156 self.env.set('NO_PROXY', 'localhost')
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000157 proxies = urllib.getproxies_environment()
158 # getproxies_environment use lowered case truncated (no '_proxy') keys
Ezio Melotti2623a372010-11-21 13:34:58 +0000159 self.assertEqual('localhost', proxies['no'])
Senthil Kumaranb5bd4c82011-08-06 12:24:33 +0800160 # List of no_proxies with space.
161 self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com')
162 self.assertTrue(urllib.proxy_bypass_environment('anotherdomain.com'))
Benjamin Peterson2c7470d2008-09-21 21:27:51 +0000163
164
Senthil Kumaran87e58552011-11-01 02:44:45 +0800165class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin):
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000166 """Test urlopen() opening a fake http connection."""
167
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000168 def test_read(self):
169 self.fakehttp('Hello!')
170 try:
171 fp = urllib.urlopen("http://python.org/")
172 self.assertEqual(fp.readline(), 'Hello!')
173 self.assertEqual(fp.readline(), '')
Georg Brandl9b0d46d2008-01-20 11:43:03 +0000174 self.assertEqual(fp.geturl(), 'http://python.org/')
175 self.assertEqual(fp.getcode(), 200)
Hye-Shik Chang39aef792004-06-05 13:30:56 +0000176 finally:
177 self.unfakehttp()
178
Senthil Kumaran49c44082011-04-13 07:31:45 +0800179 def test_url_fragment(self):
180 # Issue #11703: geturl() omits fragments in the original URL.
181 url = 'http://docs.python.org/library/urllib.html#OK'
182 self.fakehttp('Hello!')
183 try:
184 fp = urllib.urlopen(url)
185 self.assertEqual(fp.geturl(), url)
186 finally:
187 self.unfakehttp()
188
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000189 def test_read_bogus(self):
Kurt B. Kaiser0a112322008-01-02 05:23:38 +0000190 # urlopen() should raise IOError for many error codes.
Kurt B. Kaiser0f7c25d2008-01-02 04:11:28 +0000191 self.fakehttp('''HTTP/1.1 401 Authentication Required
192Date: Wed, 02 Jan 2008 03:03:54 GMT
193Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
194Connection: close
195Content-Type: text/html; charset=iso-8859-1
196''')
197 try:
198 self.assertRaises(IOError, urllib.urlopen, "http://python.org/")
199 finally:
200 self.unfakehttp()
201
guido@google.comf1509302011-03-28 13:47:01 -0700202 def test_invalid_redirect(self):
203 # urlopen() should raise IOError for many error codes.
204 self.fakehttp("""HTTP/1.1 302 Found
205Date: Wed, 02 Jan 2008 03:03:54 GMT
206Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
207Location: file:README
208Connection: close
209Content-Type: text/html; charset=iso-8859-1
210""")
211 try:
212 self.assertRaises(IOError, urllib.urlopen, "http://python.org/")
213 finally:
214 self.unfakehttp()
215
Georg Brandlf66b6032007-03-14 08:27:52 +0000216 def test_empty_socket(self):
Kurt B. Kaiser0a112322008-01-02 05:23:38 +0000217 # urlopen() raises IOError if the underlying socket does not send any
218 # data. (#1680230)
Georg Brandlf66b6032007-03-14 08:27:52 +0000219 self.fakehttp('')
220 try:
221 self.assertRaises(IOError, urllib.urlopen, 'http://something')
222 finally:
223 self.unfakehttp()
224
Senthil Kumaranf8d370e2012-10-27 03:48:40 -0700225 def test_missing_localfile(self):
226 self.assertRaises(IOError, urllib.urlopen,
227 'file://localhost/a/missing/file.py')
228 fd, tmp_file = tempfile.mkstemp()
229 tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/')
Senthil Kumarana085f002013-06-01 07:59:10 -0700230 self.assertTrue(os.path.exists(tmp_file))
Senthil Kumaranf8d370e2012-10-27 03:48:40 -0700231 try:
Senthil Kumaranf8d370e2012-10-27 03:48:40 -0700232 fp = urllib.urlopen(tmp_fileurl)
Senthil Kumarana085f002013-06-01 07:59:10 -0700233 fp.close()
Senthil Kumaranf8d370e2012-10-27 03:48:40 -0700234 finally:
235 os.close(fd)
Senthil Kumarana085f002013-06-01 07:59:10 -0700236 os.unlink(tmp_file)
Senthil Kumaranf8d370e2012-10-27 03:48:40 -0700237
238 self.assertFalse(os.path.exists(tmp_file))
239 self.assertRaises(IOError, urllib.urlopen, tmp_fileurl)
240
241 def test_ftp_nonexisting(self):
242 self.assertRaises(IOError, urllib.urlopen,
243 'ftp://localhost/not/existing/file.py')
244
245
Senthil Kumaranbcd833f2012-01-11 00:09:24 +0800246 def test_userpass_inurl(self):
247 self.fakehttp('Hello!')
248 try:
249 fakehttp_wrapper = httplib.HTTP._connection_class
250 fp = urllib.urlopen("http://user:pass@python.org/")
251 authorization = ("Authorization: Basic %s\r\n" %
252 b64encode('user:pass'))
253 # The authorization header must be in place
254 self.assertIn(authorization, fakehttp_wrapper.buf)
255 self.assertEqual(fp.readline(), "Hello!")
256 self.assertEqual(fp.readline(), "")
257 self.assertEqual(fp.geturl(), 'http://user:pass@python.org/')
258 self.assertEqual(fp.getcode(), 200)
259 finally:
260 self.unfakehttp()
261
262 def test_userpass_with_spaces_inurl(self):
263 self.fakehttp('Hello!')
264 try:
265 url = "http://a b:c d@python.org/"
266 fakehttp_wrapper = httplib.HTTP._connection_class
267 authorization = ("Authorization: Basic %s\r\n" %
268 b64encode('a b:c d'))
269 fp = urllib.urlopen(url)
270 # The authorization header must be in place
271 self.assertIn(authorization, fakehttp_wrapper.buf)
272 self.assertEqual(fp.readline(), "Hello!")
273 self.assertEqual(fp.readline(), "")
274 # the spaces are quoted in URL so no match
275 self.assertNotEqual(fp.geturl(), url)
276 self.assertEqual(fp.getcode(), 200)
277 finally:
278 self.unfakehttp()
279
280
Brett Cannon19691362003-04-29 05:08:06 +0000281class urlretrieve_FileTests(unittest.TestCase):
Brett Cannon74bfd702003-04-25 09:39:47 +0000282 """Test urllib.urlretrieve() on local files"""
Skip Montanaro080c9972001-01-28 21:12:22 +0000283
Brett Cannon19691362003-04-29 05:08:06 +0000284 def setUp(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000285 # Create a list of temporary files. Each item in the list is a file
286 # name (absolute path or relative to the current working directory).
287 # All files in this list will be deleted in the tearDown method. Note,
288 # this only helps to makes sure temporary files get deleted, but it
289 # does nothing about trying to close files that may still be open. It
290 # is the responsibility of the developer to properly close files even
291 # when exceptional conditions occur.
292 self.tempFiles = []
293
Brett Cannon19691362003-04-29 05:08:06 +0000294 # Create a temporary file.
Georg Brandl5a650a22005-08-26 08:51:34 +0000295 self.registerFileForCleanUp(test_support.TESTFN)
Brett Cannon19691362003-04-29 05:08:06 +0000296 self.text = 'testing urllib.urlretrieve'
Georg Brandl5a650a22005-08-26 08:51:34 +0000297 try:
298 FILE = file(test_support.TESTFN, 'wb')
299 FILE.write(self.text)
300 FILE.close()
301 finally:
302 try: FILE.close()
303 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000304
305 def tearDown(self):
Georg Brandl5a650a22005-08-26 08:51:34 +0000306 # Delete the temporary files.
307 for each in self.tempFiles:
308 try: os.remove(each)
309 except: pass
310
311 def constructLocalFileUrl(self, filePath):
312 return "file://%s" % urllib.pathname2url(os.path.abspath(filePath))
313
314 def createNewTempFile(self, data=""):
315 """Creates a new temporary file containing the specified data,
316 registers the file for deletion during the test fixture tear down, and
317 returns the absolute path of the file."""
318
319 newFd, newFilePath = tempfile.mkstemp()
320 try:
321 self.registerFileForCleanUp(newFilePath)
322 newFile = os.fdopen(newFd, "wb")
323 newFile.write(data)
324 newFile.close()
325 finally:
326 try: newFile.close()
327 except: pass
328 return newFilePath
329
330 def registerFileForCleanUp(self, fileName):
331 self.tempFiles.append(fileName)
Brett Cannon19691362003-04-29 05:08:06 +0000332
333 def test_basic(self):
334 # Make sure that a local file just gets its own location returned and
335 # a headers value is returned.
336 result = urllib.urlretrieve("file:%s" % test_support.TESTFN)
337 self.assertEqual(result[0], test_support.TESTFN)
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000338 self.assertIsInstance(result[1], mimetools.Message,
339 "did not get a mimetools.Message instance as "
340 "second returned value")
Brett Cannon19691362003-04-29 05:08:06 +0000341
342 def test_copy(self):
343 # Test that setting the filename argument works.
344 second_temp = "%s.2" % test_support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000345 self.registerFileForCleanUp(second_temp)
346 result = urllib.urlretrieve(self.constructLocalFileUrl(
347 test_support.TESTFN), second_temp)
Brett Cannon19691362003-04-29 05:08:06 +0000348 self.assertEqual(second_temp, result[0])
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000349 self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
Brett Cannon19691362003-04-29 05:08:06 +0000350 "made")
351 FILE = file(second_temp, 'rb')
352 try:
353 text = FILE.read()
Brett Cannon19691362003-04-29 05:08:06 +0000354 FILE.close()
Georg Brandl5a650a22005-08-26 08:51:34 +0000355 finally:
356 try: FILE.close()
357 except: pass
Brett Cannon19691362003-04-29 05:08:06 +0000358 self.assertEqual(self.text, text)
359
360 def test_reporthook(self):
361 # Make sure that the reporthook works.
362 def hooktester(count, block_size, total_size, count_holder=[0]):
Ezio Melottib0f5adc2010-01-24 16:58:36 +0000363 self.assertIsInstance(count, int)
364 self.assertIsInstance(block_size, int)
365 self.assertIsInstance(total_size, int)
Brett Cannon19691362003-04-29 05:08:06 +0000366 self.assertEqual(count, count_holder[0])
367 count_holder[0] = count_holder[0] + 1
368 second_temp = "%s.2" % test_support.TESTFN
Georg Brandl5a650a22005-08-26 08:51:34 +0000369 self.registerFileForCleanUp(second_temp)
370 urllib.urlretrieve(self.constructLocalFileUrl(test_support.TESTFN),
371 second_temp, hooktester)
372
373 def test_reporthook_0_bytes(self):
374 # Test on zero length file. Should call reporthook only 1 time.
375 report = []
376 def hooktester(count, block_size, total_size, _report=report):
377 _report.append((count, block_size, total_size))
378 srcFileName = self.createNewTempFile()
379 urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),
380 test_support.TESTFN, hooktester)
381 self.assertEqual(len(report), 1)
382 self.assertEqual(report[0][2], 0)
383
384 def test_reporthook_5_bytes(self):
385 # Test on 5 byte file. Should call reporthook only 2 times (once when
386 # the "network connection" is established and once when the block is
387 # read). Since the block size is 8192 bytes, only one block read is
388 # required to read the entire file.
389 report = []
390 def hooktester(count, block_size, total_size, _report=report):
391 _report.append((count, block_size, total_size))
392 srcFileName = self.createNewTempFile("x" * 5)
393 urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),
394 test_support.TESTFN, hooktester)
395 self.assertEqual(len(report), 2)
396 self.assertEqual(report[0][1], 8192)
397 self.assertEqual(report[0][2], 5)
398
399 def test_reporthook_8193_bytes(self):
400 # Test on 8193 byte file. Should call reporthook only 3 times (once
401 # when the "network connection" is established, once for the next 8192
402 # bytes, and once for the last byte).
403 report = []
404 def hooktester(count, block_size, total_size, _report=report):
405 _report.append((count, block_size, total_size))
406 srcFileName = self.createNewTempFile("x" * 8193)
407 urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),
408 test_support.TESTFN, hooktester)
409 self.assertEqual(len(report), 3)
410 self.assertEqual(report[0][1], 8192)
411 self.assertEqual(report[0][2], 8193)
Skip Montanaro080c9972001-01-28 21:12:22 +0000412
Senthil Kumaran87e58552011-11-01 02:44:45 +0800413
414class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin):
415 """Test urllib.urlretrieve() using fake http connections"""
416
417 def test_short_content_raises_ContentTooShortError(self):
418 self.fakehttp('''HTTP/1.1 200 OK
419Date: Wed, 02 Jan 2008 03:03:54 GMT
420Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
421Connection: close
422Content-Length: 100
423Content-Type: text/html; charset=iso-8859-1
424
425FF
426''')
427
428 def _reporthook(par1, par2, par3):
429 pass
430
431 try:
432 self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve,
433 'http://example.com', reporthook=_reporthook)
434 finally:
435 self.unfakehttp()
436
437 def test_short_content_raises_ContentTooShortError_without_reporthook(self):
438 self.fakehttp('''HTTP/1.1 200 OK
439Date: Wed, 02 Jan 2008 03:03:54 GMT
440Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
441Connection: close
442Content-Length: 100
443Content-Type: text/html; charset=iso-8859-1
444
445FF
446''')
447 try:
448 self.assertRaises(urllib.ContentTooShortError, urllib.urlretrieve, 'http://example.com/')
449 finally:
450 self.unfakehttp()
451
Brett Cannon74bfd702003-04-25 09:39:47 +0000452class QuotingTests(unittest.TestCase):
453 """Tests for urllib.quote() and urllib.quote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000454
Brett Cannon74bfd702003-04-25 09:39:47 +0000455 According to RFC 2396 ("Uniform Resource Identifiers), to escape a
456 character you write it as '%' + <2 character US-ASCII hex value>. The Python
457 code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly.
458 Case does not matter on the hex letters.
459
460 The various character sets specified are:
Tim Petersc2659cf2003-05-12 20:19:37 +0000461
Brett Cannon74bfd702003-04-25 09:39:47 +0000462 Reserved characters : ";/?:@&=+$,"
463 Have special meaning in URIs and must be escaped if not being used for
464 their special meaning
465 Data characters : letters, digits, and "-_.!~*'()"
466 Unreserved and do not need to be escaped; can be, though, if desired
467 Control characters : 0x00 - 0x1F, 0x7F
468 Have no use in URIs so must be escaped
469 space : 0x20
470 Must be escaped
471 Delimiters : '<>#%"'
472 Must be escaped
473 Unwise : "{}|\^[]`"
474 Must be escaped
Tim Petersc2659cf2003-05-12 20:19:37 +0000475
Brett Cannon74bfd702003-04-25 09:39:47 +0000476 """
477
478 def test_never_quote(self):
479 # Make sure quote() does not quote letters, digits, and "_,.-"
480 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
481 "abcdefghijklmnopqrstuvwxyz",
482 "0123456789",
483 "_.-"])
484 result = urllib.quote(do_not_quote)
485 self.assertEqual(do_not_quote, result,
486 "using quote(): %s != %s" % (do_not_quote, result))
487 result = urllib.quote_plus(do_not_quote)
488 self.assertEqual(do_not_quote, result,
489 "using quote_plus(): %s != %s" % (do_not_quote, result))
490
491 def test_default_safe(self):
492 # Test '/' is default value for 'safe' parameter
493 self.assertEqual(urllib.quote.func_defaults[0], '/')
494
495 def test_safe(self):
496 # Test setting 'safe' parameter does what it should do
497 quote_by_default = "<>"
498 result = urllib.quote(quote_by_default, safe=quote_by_default)
499 self.assertEqual(quote_by_default, result,
500 "using quote(): %s != %s" % (quote_by_default, result))
501 result = urllib.quote_plus(quote_by_default, safe=quote_by_default)
502 self.assertEqual(quote_by_default, result,
503 "using quote_plus(): %s != %s" %
504 (quote_by_default, result))
505
506 def test_default_quoting(self):
507 # Make sure all characters that should be quoted are by default sans
508 # space (separate test for that).
509 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
510 should_quote.append('<>#%"{}|\^[]`')
511 should_quote.append(chr(127)) # For 0x7F
512 should_quote = ''.join(should_quote)
513 for char in should_quote:
514 result = urllib.quote(char)
515 self.assertEqual(hexescape(char), result,
516 "using quote(): %s should be escaped to %s, not %s" %
517 (char, hexescape(char), result))
518 result = urllib.quote_plus(char)
519 self.assertEqual(hexescape(char), result,
520 "using quote_plus(): "
Tim Petersc2659cf2003-05-12 20:19:37 +0000521 "%s should be escapes to %s, not %s" %
Brett Cannon74bfd702003-04-25 09:39:47 +0000522 (char, hexescape(char), result))
523 del should_quote
524 partial_quote = "ab[]cd"
525 expected = "ab%5B%5Dcd"
526 result = urllib.quote(partial_quote)
527 self.assertEqual(expected, result,
528 "using quote(): %s != %s" % (expected, result))
Senthil Kumaran0d4c34c2011-09-13 06:42:21 +0800529 result = urllib.quote_plus(partial_quote)
Brett Cannon74bfd702003-04-25 09:39:47 +0000530 self.assertEqual(expected, result,
531 "using quote_plus(): %s != %s" % (expected, result))
Senthil Kumaranc7743aa2010-07-19 17:35:50 +0000532 self.assertRaises(TypeError, urllib.quote, None)
Brett Cannon74bfd702003-04-25 09:39:47 +0000533
534 def test_quoting_space(self):
535 # Make sure quote() and quote_plus() handle spaces as specified in
536 # their unique way
537 result = urllib.quote(' ')
538 self.assertEqual(result, hexescape(' '),
539 "using quote(): %s != %s" % (result, hexescape(' ')))
540 result = urllib.quote_plus(' ')
541 self.assertEqual(result, '+',
542 "using quote_plus(): %s != +" % result)
543 given = "a b cd e f"
544 expect = given.replace(' ', hexescape(' '))
545 result = urllib.quote(given)
546 self.assertEqual(expect, result,
547 "using quote(): %s != %s" % (expect, result))
548 expect = given.replace(' ', '+')
549 result = urllib.quote_plus(given)
550 self.assertEqual(expect, result,
551 "using quote_plus(): %s != %s" % (expect, result))
552
Raymond Hettinger2bdec7b2005-09-10 14:30:09 +0000553 def test_quoting_plus(self):
554 self.assertEqual(urllib.quote_plus('alpha+beta gamma'),
555 'alpha%2Bbeta+gamma')
556 self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'),
557 'alpha+beta+gamma')
558
Brett Cannon74bfd702003-04-25 09:39:47 +0000559class UnquotingTests(unittest.TestCase):
560 """Tests for unquote() and unquote_plus()
Tim Petersc2659cf2003-05-12 20:19:37 +0000561
Brett Cannon74bfd702003-04-25 09:39:47 +0000562 See the doc string for quoting_Tests for details on quoting and such.
563
564 """
565
566 def test_unquoting(self):
567 # Make sure unquoting of all ASCII values works
568 escape_list = []
569 for num in range(128):
570 given = hexescape(chr(num))
571 expect = chr(num)
572 result = urllib.unquote(given)
573 self.assertEqual(expect, result,
574 "using unquote(): %s != %s" % (expect, result))
575 result = urllib.unquote_plus(given)
576 self.assertEqual(expect, result,
577 "using unquote_plus(): %s != %s" %
578 (expect, result))
579 escape_list.append(given)
580 escape_string = ''.join(escape_list)
581 del escape_list
582 result = urllib.unquote(escape_string)
583 self.assertEqual(result.count('%'), 1,
584 "using quote(): not all characters escaped; %s" %
585 result)
586 result = urllib.unquote(escape_string)
587 self.assertEqual(result.count('%'), 1,
588 "using unquote(): not all characters escaped: "
589 "%s" % result)
590
Senthil Kumaranf3e9b2a2010-03-18 12:14:15 +0000591 def test_unquoting_badpercent(self):
592 # Test unquoting on bad percent-escapes
593 given = '%xab'
594 expect = given
595 result = urllib.unquote(given)
596 self.assertEqual(expect, result, "using unquote(): %r != %r"
597 % (expect, result))
598 given = '%x'
599 expect = given
600 result = urllib.unquote(given)
601 self.assertEqual(expect, result, "using unquote(): %r != %r"
602 % (expect, result))
603 given = '%'
604 expect = given
605 result = urllib.unquote(given)
606 self.assertEqual(expect, result, "using unquote(): %r != %r"
607 % (expect, result))
608
609 def test_unquoting_mixed_case(self):
610 # Test unquoting on mixed-case hex digits in the percent-escapes
611 given = '%Ab%eA'
612 expect = '\xab\xea'
613 result = urllib.unquote(given)
614 self.assertEqual(expect, result, "using unquote(): %r != %r"
615 % (expect, result))
616
Brett Cannon74bfd702003-04-25 09:39:47 +0000617 def test_unquoting_parts(self):
618 # Make sure unquoting works when have non-quoted characters
619 # interspersed
620 given = 'ab%sd' % hexescape('c')
621 expect = "abcd"
622 result = urllib.unquote(given)
623 self.assertEqual(expect, result,
624 "using quote(): %s != %s" % (expect, result))
625 result = urllib.unquote_plus(given)
626 self.assertEqual(expect, result,
627 "using unquote_plus(): %s != %s" % (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000628
Brett Cannon74bfd702003-04-25 09:39:47 +0000629 def test_unquoting_plus(self):
630 # Test difference between unquote() and unquote_plus()
631 given = "are+there+spaces..."
632 expect = given
633 result = urllib.unquote(given)
634 self.assertEqual(expect, result,
635 "using unquote(): %s != %s" % (expect, result))
636 expect = given.replace('+', ' ')
637 result = urllib.unquote_plus(given)
638 self.assertEqual(expect, result,
639 "using unquote_plus(): %s != %s" % (expect, result))
640
Raymond Hettinger4b0f20d2005-10-15 16:41:53 +0000641 def test_unquote_with_unicode(self):
642 r = urllib.unquote(u'br%C3%BCckner_sapporo_20050930.doc')
643 self.assertEqual(r, u'br\xc3\xbcckner_sapporo_20050930.doc')
644
Brett Cannon74bfd702003-04-25 09:39:47 +0000645class urlencode_Tests(unittest.TestCase):
646 """Tests for urlencode()"""
647
648 def help_inputtype(self, given, test_type):
649 """Helper method for testing different input types.
Tim Petersc2659cf2003-05-12 20:19:37 +0000650
Brett Cannon74bfd702003-04-25 09:39:47 +0000651 'given' must lead to only the pairs:
652 * 1st, 1
653 * 2nd, 2
654 * 3rd, 3
Tim Petersc2659cf2003-05-12 20:19:37 +0000655
Brett Cannon74bfd702003-04-25 09:39:47 +0000656 Test cannot assume anything about order. Docs make no guarantee and
657 have possible dictionary input.
Tim Petersc2659cf2003-05-12 20:19:37 +0000658
Brett Cannon74bfd702003-04-25 09:39:47 +0000659 """
660 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
661 result = urllib.urlencode(given)
662 for expected in expect_somewhere:
Ezio Melottiaa980582010-01-23 23:04:36 +0000663 self.assertIn(expected, result,
Brett Cannon74bfd702003-04-25 09:39:47 +0000664 "testing %s: %s not found in %s" %
665 (test_type, expected, result))
666 self.assertEqual(result.count('&'), 2,
667 "testing %s: expected 2 '&'s; got %s" %
668 (test_type, result.count('&')))
669 amp_location = result.index('&')
670 on_amp_left = result[amp_location - 1]
671 on_amp_right = result[amp_location + 1]
Benjamin Peterson5c8da862009-06-30 22:57:08 +0000672 self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
Brett Cannon74bfd702003-04-25 09:39:47 +0000673 "testing %s: '&' not located in proper place in %s" %
674 (test_type, result))
675 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
676 "testing %s: "
677 "unexpected number of characters: %s != %s" %
678 (test_type, len(result), (5 * 3) + 2))
679
680 def test_using_mapping(self):
681 # Test passing in a mapping object as an argument.
682 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
683 "using dict as input type")
684
685 def test_using_sequence(self):
686 # Test passing in a sequence of two-item sequences as an argument.
687 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
688 "using sequence of two-item tuples as input")
689
690 def test_quoting(self):
691 # Make sure keys and values are quoted using quote_plus()
692 given = {"&":"="}
693 expect = "%s=%s" % (hexescape('&'), hexescape('='))
694 result = urllib.urlencode(given)
695 self.assertEqual(expect, result)
696 given = {"key name":"A bunch of pluses"}
697 expect = "key+name=A+bunch+of+pluses"
698 result = urllib.urlencode(given)
699 self.assertEqual(expect, result)
700
701 def test_doseq(self):
702 # Test that passing True for 'doseq' parameter works correctly
703 given = {'sequence':['1', '2', '3']}
704 expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3']))
705 result = urllib.urlencode(given)
706 self.assertEqual(expect, result)
707 result = urllib.urlencode(given, True)
708 for value in given["sequence"]:
709 expect = "sequence=%s" % value
Ezio Melottiaa980582010-01-23 23:04:36 +0000710 self.assertIn(expect, result)
Brett Cannon74bfd702003-04-25 09:39:47 +0000711 self.assertEqual(result.count('&'), 2,
712 "Expected 2 '&'s, got %s" % result.count('&'))
713
714class Pathname_Tests(unittest.TestCase):
715 """Test pathname2url() and url2pathname()"""
716
717 def test_basic(self):
718 # Make sure simple tests pass
719 expected_path = os.path.join("parts", "of", "a", "path")
720 expected_url = "parts/of/a/path"
721 result = urllib.pathname2url(expected_path)
722 self.assertEqual(expected_url, result,
723 "pathname2url() failed; %s != %s" %
724 (result, expected_url))
725 result = urllib.url2pathname(expected_url)
726 self.assertEqual(expected_path, result,
727 "url2pathame() failed; %s != %s" %
728 (result, expected_path))
729
730 def test_quoting(self):
731 # Test automatic quoting and unquoting works for pathnam2url() and
732 # url2pathname() respectively
733 given = os.path.join("needs", "quot=ing", "here")
734 expect = "needs/%s/here" % urllib.quote("quot=ing")
735 result = urllib.pathname2url(given)
736 self.assertEqual(expect, result,
737 "pathname2url() failed; %s != %s" %
738 (expect, result))
739 expect = given
740 result = urllib.url2pathname(result)
741 self.assertEqual(expect, result,
742 "url2pathname() failed; %s != %s" %
743 (expect, result))
744 given = os.path.join("make sure", "using_quote")
745 expect = "%s/using_quote" % urllib.quote("make sure")
746 result = urllib.pathname2url(given)
747 self.assertEqual(expect, result,
748 "pathname2url() failed; %s != %s" %
749 (expect, result))
750 given = "make+sure/using_unquote"
751 expect = os.path.join("make+sure", "using_unquote")
752 result = urllib.url2pathname(given)
753 self.assertEqual(expect, result,
754 "url2pathname() failed; %s != %s" %
755 (expect, result))
Tim Petersc2659cf2003-05-12 20:19:37 +0000756
Senthil Kumarana99b7612011-04-14 12:54:35 +0800757 @unittest.skipUnless(sys.platform == 'win32',
758 'test specific to the nturl2path library')
759 def test_ntpath(self):
760 given = ('/C:/', '///C:/', '/C|//')
761 expect = 'C:\\'
762 for url in given:
763 result = urllib.url2pathname(url)
764 self.assertEqual(expect, result,
765 'nturl2path.url2pathname() failed; %s != %s' %
766 (expect, result))
767 given = '///C|/path'
768 expect = 'C:\\path'
769 result = urllib.url2pathname(given)
770 self.assertEqual(expect, result,
771 'nturl2path.url2pathname() failed; %s != %s' %
772 (expect, result))
773
Senthil Kumaran5e95e762009-03-30 21:51:50 +0000774class Utility_Tests(unittest.TestCase):
775 """Testcase to test the various utility functions in the urllib."""
Serhiy Storchakaf0b630b2015-03-02 16:31:57 +0200776 # In Python 3 this test class is moved to test_urlparse.
777
778 def test_splittype(self):
779 splittype = urllib.splittype
780 self.assertEqual(splittype('type:opaquestring'), ('type', 'opaquestring'))
781 self.assertEqual(splittype('opaquestring'), (None, 'opaquestring'))
782 self.assertEqual(splittype(':opaquestring'), (None, ':opaquestring'))
783 self.assertEqual(splittype('type:'), ('type', ''))
784 self.assertEqual(splittype('type:opaque:string'), ('type', 'opaque:string'))
785
786 def test_splithost(self):
787 splithost = urllib.splithost
788 self.assertEqual(splithost('//www.example.org:80/foo/bar/baz.html'),
789 ('www.example.org:80', '/foo/bar/baz.html'))
790 self.assertEqual(splithost('//www.example.org:80'),
791 ('www.example.org:80', ''))
792 self.assertEqual(splithost('/foo/bar/baz.html'),
793 (None, '/foo/bar/baz.html'))
794
795 def test_splituser(self):
796 splituser = urllib.splituser
797 self.assertEqual(splituser('User:Pass@www.python.org:080'),
798 ('User:Pass', 'www.python.org:080'))
799 self.assertEqual(splituser('@www.python.org:080'),
800 ('', 'www.python.org:080'))
801 self.assertEqual(splituser('www.python.org:080'),
802 (None, 'www.python.org:080'))
803 self.assertEqual(splituser('User:Pass@'),
804 ('User:Pass', ''))
805 self.assertEqual(splituser('User@example.com:Pass@www.python.org:080'),
806 ('User@example.com:Pass', 'www.python.org:080'))
Senthil Kumaran5e95e762009-03-30 21:51:50 +0000807
808 def test_splitpasswd(self):
Serhiy Storchakaf0b630b2015-03-02 16:31:57 +0200809 # Some of the password examples are not sensible, but it is added to
810 # confirming to RFC2617 and addressing issue4675.
811 splitpasswd = urllib.splitpasswd
812 self.assertEqual(splitpasswd('user:ab'), ('user', 'ab'))
813 self.assertEqual(splitpasswd('user:a\nb'), ('user', 'a\nb'))
814 self.assertEqual(splitpasswd('user:a\tb'), ('user', 'a\tb'))
815 self.assertEqual(splitpasswd('user:a\rb'), ('user', 'a\rb'))
816 self.assertEqual(splitpasswd('user:a\fb'), ('user', 'a\fb'))
817 self.assertEqual(splitpasswd('user:a\vb'), ('user', 'a\vb'))
818 self.assertEqual(splitpasswd('user:a:b'), ('user', 'a:b'))
819 self.assertEqual(splitpasswd('user:a b'), ('user', 'a b'))
820 self.assertEqual(splitpasswd('user 2:ab'), ('user 2', 'ab'))
821 self.assertEqual(splitpasswd('user+1:a+b'), ('user+1', 'a+b'))
822 self.assertEqual(splitpasswd('user:'), ('user', ''))
823 self.assertEqual(splitpasswd('user'), ('user', None))
824 self.assertEqual(splitpasswd(':ab'), ('', 'ab'))
Senthil Kumaran5e95e762009-03-30 21:51:50 +0000825
Serhiy Storchaka326b5ab2014-01-18 18:30:09 +0200826 def test_splitport(self):
827 splitport = urllib.splitport
828 self.assertEqual(splitport('parrot:88'), ('parrot', '88'))
829 self.assertEqual(splitport('parrot'), ('parrot', None))
830 self.assertEqual(splitport('parrot:'), ('parrot', None))
831 self.assertEqual(splitport('127.0.0.1'), ('127.0.0.1', None))
832 self.assertEqual(splitport('parrot:cheese'), ('parrot:cheese', None))
Serhiy Storchakaf0b630b2015-03-02 16:31:57 +0200833 self.assertEqual(splitport('[::1]:88'), ('[::1]', '88'))
834 self.assertEqual(splitport('[::1]'), ('[::1]', None))
835 self.assertEqual(splitport(':88'), ('', '88'))
Serhiy Storchaka326b5ab2014-01-18 18:30:09 +0200836
837 def test_splitnport(self):
838 splitnport = urllib.splitnport
839 self.assertEqual(splitnport('parrot:88'), ('parrot', 88))
840 self.assertEqual(splitnport('parrot'), ('parrot', -1))
841 self.assertEqual(splitnport('parrot', 55), ('parrot', 55))
842 self.assertEqual(splitnport('parrot:'), ('parrot', -1))
843 self.assertEqual(splitnport('parrot:', 55), ('parrot', 55))
844 self.assertEqual(splitnport('127.0.0.1'), ('127.0.0.1', -1))
845 self.assertEqual(splitnport('127.0.0.1', 55), ('127.0.0.1', 55))
846 self.assertEqual(splitnport('parrot:cheese'), ('parrot', None))
847 self.assertEqual(splitnport('parrot:cheese', 55), ('parrot', None))
848
Serhiy Storchakaf0b630b2015-03-02 16:31:57 +0200849 def test_splitquery(self):
850 # Normal cases are exercised by other tests; ensure that we also
851 # catch cases with no port specified (testcase ensuring coverage)
852 splitquery = urllib.splitquery
853 self.assertEqual(splitquery('http://python.org/fake?foo=bar'),
854 ('http://python.org/fake', 'foo=bar'))
855 self.assertEqual(splitquery('http://python.org/fake?foo=bar?'),
856 ('http://python.org/fake?foo=bar', ''))
857 self.assertEqual(splitquery('http://python.org/fake'),
858 ('http://python.org/fake', None))
859 self.assertEqual(splitquery('?foo=bar'), ('', 'foo=bar'))
860
861 def test_splittag(self):
862 splittag = urllib.splittag
863 self.assertEqual(splittag('http://example.com?foo=bar#baz'),
864 ('http://example.com?foo=bar', 'baz'))
865 self.assertEqual(splittag('http://example.com?foo=bar#'),
866 ('http://example.com?foo=bar', ''))
867 self.assertEqual(splittag('#baz'), ('', 'baz'))
868 self.assertEqual(splittag('http://example.com?foo=bar'),
869 ('http://example.com?foo=bar', None))
870 self.assertEqual(splittag('http://example.com?foo=bar#baz#boo'),
871 ('http://example.com?foo=bar#baz', 'boo'))
872
873 def test_splitattr(self):
874 splitattr = urllib.splitattr
875 self.assertEqual(splitattr('/path;attr1=value1;attr2=value2'),
876 ('/path', ['attr1=value1', 'attr2=value2']))
877 self.assertEqual(splitattr('/path;'), ('/path', ['']))
878 self.assertEqual(splitattr(';attr1=value1;attr2=value2'),
879 ('', ['attr1=value1', 'attr2=value2']))
880 self.assertEqual(splitattr('/path'), ('/path', []))
881
882 def test_splitvalue(self):
883 # Normal cases are exercised by other tests; test pathological cases
884 # with no key/value pairs. (testcase ensuring coverage)
885 splitvalue = urllib.splitvalue
886 self.assertEqual(splitvalue('foo=bar'), ('foo', 'bar'))
887 self.assertEqual(splitvalue('foo='), ('foo', ''))
888 self.assertEqual(splitvalue('=bar'), ('', 'bar'))
889 self.assertEqual(splitvalue('foobar'), ('foobar', None))
890 self.assertEqual(splitvalue('foo=bar=baz'), ('foo', 'bar=baz'))
891
892 def test_toBytes(self):
893 result = urllib.toBytes(u'http://www.python.org')
894 self.assertEqual(result, 'http://www.python.org')
895 self.assertRaises(UnicodeError, urllib.toBytes,
896 test_support.u(r'http://www.python.org/medi\u00e6val'))
897
898 def test_unwrap(self):
899 url = urllib.unwrap('<URL:type://host/path>')
900 self.assertEqual(url, 'type://host/path')
901
Senthil Kumaran5e95e762009-03-30 21:51:50 +0000902
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000903class URLopener_Tests(unittest.TestCase):
904 """Testcase to test the open method of URLopener class."""
905
906 def test_quoted_open(self):
907 class DummyURLopener(urllib.URLopener):
908 def open_spam(self, url):
909 return url
910
911 self.assertEqual(DummyURLopener().open(
912 'spam://example/ /'),'//example/%20/')
913
Senthil Kumaran18d5a692010-02-20 22:05:34 +0000914 # test the safe characters are not quoted by urlopen
915 self.assertEqual(DummyURLopener().open(
916 "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
917 "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
918
Senthil Kumaran7c2867f2009-04-21 03:24:19 +0000919
Facundo Batistad9880d02007-05-25 04:20:22 +0000920# Just commented them out.
921# Can't really tell why keep failing in windows and sparc.
Ezio Melottic2077b02011-03-16 12:34:31 +0200922# Everywhere else they work ok, but on those machines, sometimes
Facundo Batistad9880d02007-05-25 04:20:22 +0000923# fail in one of the tests, sometimes in other. I have a linux, and
924# the tests go ok.
Ezio Melotti419e23c2013-08-17 16:56:09 +0300925# If anybody has one of the problematic environments, please help!
Facundo Batistad9880d02007-05-25 04:20:22 +0000926# . Facundo
927#
928# def server(evt):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000929# import socket, time
Facundo Batistad9880d02007-05-25 04:20:22 +0000930# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
931# serv.settimeout(3)
932# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
933# serv.bind(("", 9093))
934# serv.listen(5)
935# try:
936# conn, addr = serv.accept()
937# conn.send("1 Hola mundo\n")
938# cantdata = 0
939# while cantdata < 13:
940# data = conn.recv(13-cantdata)
941# cantdata += len(data)
942# time.sleep(.3)
943# conn.send("2 No more lines\n")
944# conn.close()
945# except socket.timeout:
946# pass
947# finally:
948# serv.close()
949# evt.set()
950#
951# class FTPWrapperTests(unittest.TestCase):
952#
953# def setUp(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000954# import ftplib, time, threading
Facundo Batistad9880d02007-05-25 04:20:22 +0000955# ftplib.FTP.port = 9093
956# self.evt = threading.Event()
957# threading.Thread(target=server, args=(self.evt,)).start()
958# time.sleep(.1)
959#
960# def tearDown(self):
961# self.evt.wait()
962#
963# def testBasic(self):
964# # connects
965# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000966# ftp.close()
Facundo Batistad9880d02007-05-25 04:20:22 +0000967#
968# def testTimeoutNone(self):
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000969# # global default timeout is ignored
970# import socket
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200971# self.assertIsNone(socket.getdefaulttimeout())
Facundo Batistad9880d02007-05-25 04:20:22 +0000972# socket.setdefaulttimeout(30)
973# try:
974# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
975# finally:
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000976# socket.setdefaulttimeout(None)
Facundo Batistad9880d02007-05-25 04:20:22 +0000977# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000978# ftp.close()
Facundo Batistad9880d02007-05-25 04:20:22 +0000979#
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000980# def testTimeoutDefault(self):
981# # global default timeout is used
982# import socket
Serhiy Storchaka528bed82014-02-08 14:49:55 +0200983# self.assertIsNone(socket.getdefaulttimeout())
Facundo Batista4f1b1ed2008-05-29 16:39:26 +0000984# socket.setdefaulttimeout(30)
985# try:
986# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
987# finally:
988# socket.setdefaulttimeout(None)
989# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
990# ftp.close()
991#
992# def testTimeoutValue(self):
993# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],
994# timeout=30)
995# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)
996# ftp.close()
Facundo Batista711a54e2007-05-24 17:50:54 +0000997
Skip Montanaro080c9972001-01-28 21:12:22 +0000998
999
Brett Cannon74bfd702003-04-25 09:39:47 +00001000def test_main():
Brett Cannon8bb8fa52008-07-02 01:57:08 +00001001 import warnings
Brett Cannon672237d2008-09-09 00:49:16 +00001002 with warnings.catch_warnings():
Brett Cannon8bb8fa52008-07-02 01:57:08 +00001003 warnings.filterwarnings('ignore', ".*urllib\.urlopen.*Python 3.0",
1004 DeprecationWarning)
1005 test_support.run_unittest(
1006 urlopen_FileTests,
1007 urlopen_HttpTests,
1008 urlretrieve_FileTests,
Senthil Kumaran87e58552011-11-01 02:44:45 +08001009 urlretrieve_HttpTests,
Benjamin Peterson2c7470d2008-09-21 21:27:51 +00001010 ProxyTests,
Brett Cannon8bb8fa52008-07-02 01:57:08 +00001011 QuotingTests,
1012 UnquotingTests,
1013 urlencode_Tests,
1014 Pathname_Tests,
Senthil Kumaran5e95e762009-03-30 21:51:50 +00001015 Utility_Tests,
Senthil Kumaran7c2867f2009-04-21 03:24:19 +00001016 URLopener_Tests,
Brett Cannon8bb8fa52008-07-02 01:57:08 +00001017 #FTPWrapperTests,
1018 )
Brett Cannon74bfd702003-04-25 09:39:47 +00001019
1020
1021
1022if __name__ == '__main__':
1023 test_main()