+++ /dev/null
-"""Regresssion tests for urllib"""\r
-\r
-import urllib\r
-import httplib\r
-import unittest\r
-from test import test_support\r
-import os\r
-import sys\r
-import mimetools\r
-import tempfile\r
-import StringIO\r
-\r
-def hexescape(char):\r
- """Escape char as RFC 2396 specifies"""\r
- hex_repr = hex(ord(char))[2:].upper()\r
- if len(hex_repr) == 1:\r
- hex_repr = "0%s" % hex_repr\r
- return "%" + hex_repr\r
-\r
-class urlopen_FileTests(unittest.TestCase):\r
- """Test urlopen() opening a temporary file.\r
-\r
- Try to test as much functionality as possible so as to cut down on reliance\r
- on connecting to the Net for testing.\r
-\r
- """\r
-\r
- def setUp(self):\r
- """Setup of a temp file to use for testing"""\r
- self.text = "test_urllib: %s\n" % self.__class__.__name__\r
- FILE = file(test_support.TESTFN, 'wb')\r
- try:\r
- FILE.write(self.text)\r
- finally:\r
- FILE.close()\r
- self.pathname = test_support.TESTFN\r
- self.returned_obj = urllib.urlopen("file:%s" % self.pathname)\r
-\r
- def tearDown(self):\r
- """Shut down the open object"""\r
- self.returned_obj.close()\r
- os.remove(test_support.TESTFN)\r
-\r
- def test_interface(self):\r
- # Make sure object returned by urlopen() has the specified methods\r
- for attr in ("read", "readline", "readlines", "fileno",\r
- "close", "info", "geturl", "getcode", "__iter__"):\r
- self.assertTrue(hasattr(self.returned_obj, attr),\r
- "object returned by urlopen() lacks %s attribute" %\r
- attr)\r
-\r
- def test_read(self):\r
- self.assertEqual(self.text, self.returned_obj.read())\r
-\r
- def test_readline(self):\r
- self.assertEqual(self.text, self.returned_obj.readline())\r
- self.assertEqual('', self.returned_obj.readline(),\r
- "calling readline() after exhausting the file did not"\r
- " return an empty string")\r
-\r
- def test_readlines(self):\r
- lines_list = self.returned_obj.readlines()\r
- self.assertEqual(len(lines_list), 1,\r
- "readlines() returned the wrong number of lines")\r
- self.assertEqual(lines_list[0], self.text,\r
- "readlines() returned improper text")\r
-\r
- def test_fileno(self):\r
- file_num = self.returned_obj.fileno()\r
- self.assertIsInstance(file_num, int, "fileno() did not return an int")\r
- self.assertEqual(os.read(file_num, len(self.text)), self.text,\r
- "Reading on the file descriptor returned by fileno() "\r
- "did not return the expected text")\r
-\r
- def test_close(self):\r
- # Test close() by calling it hear and then having it be called again\r
- # by the tearDown() method for the test\r
- self.returned_obj.close()\r
-\r
- def test_info(self):\r
- self.assertIsInstance(self.returned_obj.info(), mimetools.Message)\r
-\r
- def test_geturl(self):\r
- self.assertEqual(self.returned_obj.geturl(), self.pathname)\r
-\r
- def test_getcode(self):\r
- self.assertEqual(self.returned_obj.getcode(), None)\r
-\r
- def test_iter(self):\r
- # Test iterator\r
- # Don't need to count number of iterations since test would fail the\r
- # instant it returned anything beyond the first line from the\r
- # comparison\r
- for line in self.returned_obj.__iter__():\r
- self.assertEqual(line, self.text)\r
-\r
-class ProxyTests(unittest.TestCase):\r
-\r
- def setUp(self):\r
- # Records changes to env vars\r
- self.env = test_support.EnvironmentVarGuard()\r
- # Delete all proxy related env vars\r
- for k in os.environ.keys():\r
- if 'proxy' in k.lower():\r
- self.env.unset(k)\r
-\r
- def tearDown(self):\r
- # Restore all proxy related env vars\r
- self.env.__exit__()\r
- del self.env\r
-\r
- def test_getproxies_environment_keep_no_proxies(self):\r
- self.env.set('NO_PROXY', 'localhost')\r
- proxies = urllib.getproxies_environment()\r
- # getproxies_environment use lowered case truncated (no '_proxy') keys\r
- self.assertEqual('localhost', proxies['no'])\r
-\r
-\r
-class urlopen_HttpTests(unittest.TestCase):\r
- """Test urlopen() opening a fake http connection."""\r
-\r
- def fakehttp(self, fakedata):\r
- class FakeSocket(StringIO.StringIO):\r
- def sendall(self, str): pass\r
- def makefile(self, mode, name): return self\r
- def read(self, amt=None):\r
- if self.closed: return ''\r
- return StringIO.StringIO.read(self, amt)\r
- def readline(self, length=None):\r
- if self.closed: return ''\r
- return StringIO.StringIO.readline(self, length)\r
- class FakeHTTPConnection(httplib.HTTPConnection):\r
- def connect(self):\r
- self.sock = FakeSocket(fakedata)\r
- assert httplib.HTTP._connection_class == httplib.HTTPConnection\r
- httplib.HTTP._connection_class = FakeHTTPConnection\r
-\r
- def unfakehttp(self):\r
- httplib.HTTP._connection_class = httplib.HTTPConnection\r
-\r
- def test_read(self):\r
- self.fakehttp('Hello!')\r
- try:\r
- fp = urllib.urlopen("http://python.org/")\r
- self.assertEqual(fp.readline(), 'Hello!')\r
- self.assertEqual(fp.readline(), '')\r
- self.assertEqual(fp.geturl(), 'http://python.org/')\r
- self.assertEqual(fp.getcode(), 200)\r
- finally:\r
- self.unfakehttp()\r
-\r
- def test_url_fragment(self):\r
- # Issue #11703: geturl() omits fragments in the original URL.\r
- url = 'http://docs.python.org/library/urllib.html#OK'\r
- self.fakehttp('Hello!')\r
- try:\r
- fp = urllib.urlopen(url)\r
- self.assertEqual(fp.geturl(), url)\r
- finally:\r
- self.unfakehttp()\r
-\r
- def test_read_bogus(self):\r
- # urlopen() should raise IOError for many error codes.\r
- self.fakehttp('''HTTP/1.1 401 Authentication Required\r
-Date: Wed, 02 Jan 2008 03:03:54 GMT\r
-Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e\r
-Connection: close\r
-Content-Type: text/html; charset=iso-8859-1\r
-''')\r
- try:\r
- self.assertRaises(IOError, urllib.urlopen, "http://python.org/")\r
- finally:\r
- self.unfakehttp()\r
-\r
- def test_invalid_redirect(self):\r
- # urlopen() should raise IOError for many error codes.\r
- self.fakehttp("""HTTP/1.1 302 Found\r
-Date: Wed, 02 Jan 2008 03:03:54 GMT\r
-Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e\r
-Location: file:README\r
-Connection: close\r
-Content-Type: text/html; charset=iso-8859-1\r
-""")\r
- try:\r
- self.assertRaises(IOError, urllib.urlopen, "http://python.org/")\r
- finally:\r
- self.unfakehttp()\r
-\r
- def test_empty_socket(self):\r
- # urlopen() raises IOError if the underlying socket does not send any\r
- # data. (#1680230)\r
- self.fakehttp('')\r
- try:\r
- self.assertRaises(IOError, urllib.urlopen, 'http://something')\r
- finally:\r
- self.unfakehttp()\r
-\r
-class urlretrieve_FileTests(unittest.TestCase):\r
- """Test urllib.urlretrieve() on local files"""\r
-\r
- def setUp(self):\r
- # Create a list of temporary files. Each item in the list is a file\r
- # name (absolute path or relative to the current working directory).\r
- # All files in this list will be deleted in the tearDown method. Note,\r
- # this only helps to makes sure temporary files get deleted, but it\r
- # does nothing about trying to close files that may still be open. It\r
- # is the responsibility of the developer to properly close files even\r
- # when exceptional conditions occur.\r
- self.tempFiles = []\r
-\r
- # Create a temporary file.\r
- self.registerFileForCleanUp(test_support.TESTFN)\r
- self.text = 'testing urllib.urlretrieve'\r
- try:\r
- FILE = file(test_support.TESTFN, 'wb')\r
- FILE.write(self.text)\r
- FILE.close()\r
- finally:\r
- try: FILE.close()\r
- except: pass\r
-\r
- def tearDown(self):\r
- # Delete the temporary files.\r
- for each in self.tempFiles:\r
- try: os.remove(each)\r
- except: pass\r
-\r
- def constructLocalFileUrl(self, filePath):\r
- return "file://%s" % urllib.pathname2url(os.path.abspath(filePath))\r
-\r
- def createNewTempFile(self, data=""):\r
- """Creates a new temporary file containing the specified data,\r
- registers the file for deletion during the test fixture tear down, and\r
- returns the absolute path of the file."""\r
-\r
- newFd, newFilePath = tempfile.mkstemp()\r
- try:\r
- self.registerFileForCleanUp(newFilePath)\r
- newFile = os.fdopen(newFd, "wb")\r
- newFile.write(data)\r
- newFile.close()\r
- finally:\r
- try: newFile.close()\r
- except: pass\r
- return newFilePath\r
-\r
- def registerFileForCleanUp(self, fileName):\r
- self.tempFiles.append(fileName)\r
-\r
- def test_basic(self):\r
- # Make sure that a local file just gets its own location returned and\r
- # a headers value is returned.\r
- result = urllib.urlretrieve("file:%s" % test_support.TESTFN)\r
- self.assertEqual(result[0], test_support.TESTFN)\r
- self.assertIsInstance(result[1], mimetools.Message,\r
- "did not get a mimetools.Message instance as "\r
- "second returned value")\r
-\r
- def test_copy(self):\r
- # Test that setting the filename argument works.\r
- second_temp = "%s.2" % test_support.TESTFN\r
- self.registerFileForCleanUp(second_temp)\r
- result = urllib.urlretrieve(self.constructLocalFileUrl(\r
- test_support.TESTFN), second_temp)\r
- self.assertEqual(second_temp, result[0])\r
- self.assertTrue(os.path.exists(second_temp), "copy of the file was not "\r
- "made")\r
- FILE = file(second_temp, 'rb')\r
- try:\r
- text = FILE.read()\r
- FILE.close()\r
- finally:\r
- try: FILE.close()\r
- except: pass\r
- self.assertEqual(self.text, text)\r
-\r
- def test_reporthook(self):\r
- # Make sure that the reporthook works.\r
- def hooktester(count, block_size, total_size, count_holder=[0]):\r
- self.assertIsInstance(count, int)\r
- self.assertIsInstance(block_size, int)\r
- self.assertIsInstance(total_size, int)\r
- self.assertEqual(count, count_holder[0])\r
- count_holder[0] = count_holder[0] + 1\r
- second_temp = "%s.2" % test_support.TESTFN\r
- self.registerFileForCleanUp(second_temp)\r
- urllib.urlretrieve(self.constructLocalFileUrl(test_support.TESTFN),\r
- second_temp, hooktester)\r
-\r
- def test_reporthook_0_bytes(self):\r
- # Test on zero length file. Should call reporthook only 1 time.\r
- report = []\r
- def hooktester(count, block_size, total_size, _report=report):\r
- _report.append((count, block_size, total_size))\r
- srcFileName = self.createNewTempFile()\r
- urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),\r
- test_support.TESTFN, hooktester)\r
- self.assertEqual(len(report), 1)\r
- self.assertEqual(report[0][2], 0)\r
-\r
- def test_reporthook_5_bytes(self):\r
- # Test on 5 byte file. Should call reporthook only 2 times (once when\r
- # the "network connection" is established and once when the block is\r
- # read). Since the block size is 8192 bytes, only one block read is\r
- # required to read the entire file.\r
- report = []\r
- def hooktester(count, block_size, total_size, _report=report):\r
- _report.append((count, block_size, total_size))\r
- srcFileName = self.createNewTempFile("x" * 5)\r
- urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),\r
- test_support.TESTFN, hooktester)\r
- self.assertEqual(len(report), 2)\r
- self.assertEqual(report[0][1], 8192)\r
- self.assertEqual(report[0][2], 5)\r
-\r
- def test_reporthook_8193_bytes(self):\r
- # Test on 8193 byte file. Should call reporthook only 3 times (once\r
- # when the "network connection" is established, once for the next 8192\r
- # bytes, and once for the last byte).\r
- report = []\r
- def hooktester(count, block_size, total_size, _report=report):\r
- _report.append((count, block_size, total_size))\r
- srcFileName = self.createNewTempFile("x" * 8193)\r
- urllib.urlretrieve(self.constructLocalFileUrl(srcFileName),\r
- test_support.TESTFN, hooktester)\r
- self.assertEqual(len(report), 3)\r
- self.assertEqual(report[0][1], 8192)\r
- self.assertEqual(report[0][2], 8193)\r
-\r
-class QuotingTests(unittest.TestCase):\r
- """Tests for urllib.quote() and urllib.quote_plus()\r
-\r
- According to RFC 2396 ("Uniform Resource Identifiers), to escape a\r
- character you write it as '%' + <2 character US-ASCII hex value>. The Python\r
- code of ``'%' + hex(ord(<character>))[2:]`` escapes a character properly.\r
- Case does not matter on the hex letters.\r
-\r
- The various character sets specified are:\r
-\r
- Reserved characters : ";/?:@&=+$,"\r
- Have special meaning in URIs and must be escaped if not being used for\r
- their special meaning\r
- Data characters : letters, digits, and "-_.!~*'()"\r
- Unreserved and do not need to be escaped; can be, though, if desired\r
- Control characters : 0x00 - 0x1F, 0x7F\r
- Have no use in URIs so must be escaped\r
- space : 0x20\r
- Must be escaped\r
- Delimiters : '<>#%"'\r
- Must be escaped\r
- Unwise : "{}|\^[]`"\r
- Must be escaped\r
-\r
- """\r
-\r
- def test_never_quote(self):\r
- # Make sure quote() does not quote letters, digits, and "_,.-"\r
- do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",\r
- "abcdefghijklmnopqrstuvwxyz",\r
- "0123456789",\r
- "_.-"])\r
- result = urllib.quote(do_not_quote)\r
- self.assertEqual(do_not_quote, result,\r
- "using quote(): %s != %s" % (do_not_quote, result))\r
- result = urllib.quote_plus(do_not_quote)\r
- self.assertEqual(do_not_quote, result,\r
- "using quote_plus(): %s != %s" % (do_not_quote, result))\r
-\r
- def test_default_safe(self):\r
- # Test '/' is default value for 'safe' parameter\r
- self.assertEqual(urllib.quote.func_defaults[0], '/')\r
-\r
- def test_safe(self):\r
- # Test setting 'safe' parameter does what it should do\r
- quote_by_default = "<>"\r
- result = urllib.quote(quote_by_default, safe=quote_by_default)\r
- self.assertEqual(quote_by_default, result,\r
- "using quote(): %s != %s" % (quote_by_default, result))\r
- result = urllib.quote_plus(quote_by_default, safe=quote_by_default)\r
- self.assertEqual(quote_by_default, result,\r
- "using quote_plus(): %s != %s" %\r
- (quote_by_default, result))\r
-\r
- def test_default_quoting(self):\r
- # Make sure all characters that should be quoted are by default sans\r
- # space (separate test for that).\r
- should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F\r
- should_quote.append('<>#%"{}|\^[]`')\r
- should_quote.append(chr(127)) # For 0x7F\r
- should_quote = ''.join(should_quote)\r
- for char in should_quote:\r
- result = urllib.quote(char)\r
- self.assertEqual(hexescape(char), result,\r
- "using quote(): %s should be escaped to %s, not %s" %\r
- (char, hexescape(char), result))\r
- result = urllib.quote_plus(char)\r
- self.assertEqual(hexescape(char), result,\r
- "using quote_plus(): "\r
- "%s should be escapes to %s, not %s" %\r
- (char, hexescape(char), result))\r
- del should_quote\r
- partial_quote = "ab[]cd"\r
- expected = "ab%5B%5Dcd"\r
- result = urllib.quote(partial_quote)\r
- self.assertEqual(expected, result,\r
- "using quote(): %s != %s" % (expected, result))\r
- self.assertEqual(expected, result,\r
- "using quote_plus(): %s != %s" % (expected, result))\r
- self.assertRaises(TypeError, urllib.quote, None)\r
-\r
- def test_quoting_space(self):\r
- # Make sure quote() and quote_plus() handle spaces as specified in\r
- # their unique way\r
- result = urllib.quote(' ')\r
- self.assertEqual(result, hexescape(' '),\r
- "using quote(): %s != %s" % (result, hexescape(' ')))\r
- result = urllib.quote_plus(' ')\r
- self.assertEqual(result, '+',\r
- "using quote_plus(): %s != +" % result)\r
- given = "a b cd e f"\r
- expect = given.replace(' ', hexescape(' '))\r
- result = urllib.quote(given)\r
- self.assertEqual(expect, result,\r
- "using quote(): %s != %s" % (expect, result))\r
- expect = given.replace(' ', '+')\r
- result = urllib.quote_plus(given)\r
- self.assertEqual(expect, result,\r
- "using quote_plus(): %s != %s" % (expect, result))\r
-\r
- def test_quoting_plus(self):\r
- self.assertEqual(urllib.quote_plus('alpha+beta gamma'),\r
- 'alpha%2Bbeta+gamma')\r
- self.assertEqual(urllib.quote_plus('alpha+beta gamma', '+'),\r
- 'alpha+beta+gamma')\r
-\r
-class UnquotingTests(unittest.TestCase):\r
- """Tests for unquote() and unquote_plus()\r
-\r
- See the doc string for quoting_Tests for details on quoting and such.\r
-\r
- """\r
-\r
- def test_unquoting(self):\r
- # Make sure unquoting of all ASCII values works\r
- escape_list = []\r
- for num in range(128):\r
- given = hexescape(chr(num))\r
- expect = chr(num)\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result,\r
- "using unquote(): %s != %s" % (expect, result))\r
- result = urllib.unquote_plus(given)\r
- self.assertEqual(expect, result,\r
- "using unquote_plus(): %s != %s" %\r
- (expect, result))\r
- escape_list.append(given)\r
- escape_string = ''.join(escape_list)\r
- del escape_list\r
- result = urllib.unquote(escape_string)\r
- self.assertEqual(result.count('%'), 1,\r
- "using quote(): not all characters escaped; %s" %\r
- result)\r
- result = urllib.unquote(escape_string)\r
- self.assertEqual(result.count('%'), 1,\r
- "using unquote(): not all characters escaped: "\r
- "%s" % result)\r
-\r
- def test_unquoting_badpercent(self):\r
- # Test unquoting on bad percent-escapes\r
- given = '%xab'\r
- expect = given\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result, "using unquote(): %r != %r"\r
- % (expect, result))\r
- given = '%x'\r
- expect = given\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result, "using unquote(): %r != %r"\r
- % (expect, result))\r
- given = '%'\r
- expect = given\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result, "using unquote(): %r != %r"\r
- % (expect, result))\r
-\r
- def test_unquoting_mixed_case(self):\r
- # Test unquoting on mixed-case hex digits in the percent-escapes\r
- given = '%Ab%eA'\r
- expect = '\xab\xea'\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result, "using unquote(): %r != %r"\r
- % (expect, result))\r
-\r
- def test_unquoting_parts(self):\r
- # Make sure unquoting works when have non-quoted characters\r
- # interspersed\r
- given = 'ab%sd' % hexescape('c')\r
- expect = "abcd"\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result,\r
- "using quote(): %s != %s" % (expect, result))\r
- result = urllib.unquote_plus(given)\r
- self.assertEqual(expect, result,\r
- "using unquote_plus(): %s != %s" % (expect, result))\r
-\r
- def test_unquoting_plus(self):\r
- # Test difference between unquote() and unquote_plus()\r
- given = "are+there+spaces..."\r
- expect = given\r
- result = urllib.unquote(given)\r
- self.assertEqual(expect, result,\r
- "using unquote(): %s != %s" % (expect, result))\r
- expect = given.replace('+', ' ')\r
- result = urllib.unquote_plus(given)\r
- self.assertEqual(expect, result,\r
- "using unquote_plus(): %s != %s" % (expect, result))\r
-\r
- def test_unquote_with_unicode(self):\r
- r = urllib.unquote(u'br%C3%BCckner_sapporo_20050930.doc')\r
- self.assertEqual(r, u'br\xc3\xbcckner_sapporo_20050930.doc')\r
-\r
-class urlencode_Tests(unittest.TestCase):\r
- """Tests for urlencode()"""\r
-\r
- def help_inputtype(self, given, test_type):\r
- """Helper method for testing different input types.\r
-\r
- 'given' must lead to only the pairs:\r
- * 1st, 1\r
- * 2nd, 2\r
- * 3rd, 3\r
-\r
- Test cannot assume anything about order. Docs make no guarantee and\r
- have possible dictionary input.\r
-\r
- """\r
- expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]\r
- result = urllib.urlencode(given)\r
- for expected in expect_somewhere:\r
- self.assertIn(expected, result,\r
- "testing %s: %s not found in %s" %\r
- (test_type, expected, result))\r
- self.assertEqual(result.count('&'), 2,\r
- "testing %s: expected 2 '&'s; got %s" %\r
- (test_type, result.count('&')))\r
- amp_location = result.index('&')\r
- on_amp_left = result[amp_location - 1]\r
- on_amp_right = result[amp_location + 1]\r
- self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),\r
- "testing %s: '&' not located in proper place in %s" %\r
- (test_type, result))\r
- self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps\r
- "testing %s: "\r
- "unexpected number of characters: %s != %s" %\r
- (test_type, len(result), (5 * 3) + 2))\r
-\r
- def test_using_mapping(self):\r
- # Test passing in a mapping object as an argument.\r
- self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},\r
- "using dict as input type")\r
-\r
- def test_using_sequence(self):\r
- # Test passing in a sequence of two-item sequences as an argument.\r
- self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],\r
- "using sequence of two-item tuples as input")\r
-\r
- def test_quoting(self):\r
- # Make sure keys and values are quoted using quote_plus()\r
- given = {"&":"="}\r
- expect = "%s=%s" % (hexescape('&'), hexescape('='))\r
- result = urllib.urlencode(given)\r
- self.assertEqual(expect, result)\r
- given = {"key name":"A bunch of pluses"}\r
- expect = "key+name=A+bunch+of+pluses"\r
- result = urllib.urlencode(given)\r
- self.assertEqual(expect, result)\r
-\r
- def test_doseq(self):\r
- # Test that passing True for 'doseq' parameter works correctly\r
- given = {'sequence':['1', '2', '3']}\r
- expect = "sequence=%s" % urllib.quote_plus(str(['1', '2', '3']))\r
- result = urllib.urlencode(given)\r
- self.assertEqual(expect, result)\r
- result = urllib.urlencode(given, True)\r
- for value in given["sequence"]:\r
- expect = "sequence=%s" % value\r
- self.assertIn(expect, result)\r
- self.assertEqual(result.count('&'), 2,\r
- "Expected 2 '&'s, got %s" % result.count('&'))\r
-\r
-class Pathname_Tests(unittest.TestCase):\r
- """Test pathname2url() and url2pathname()"""\r
-\r
- def test_basic(self):\r
- # Make sure simple tests pass\r
- expected_path = os.path.join("parts", "of", "a", "path")\r
- expected_url = "parts/of/a/path"\r
- result = urllib.pathname2url(expected_path)\r
- self.assertEqual(expected_url, result,\r
- "pathname2url() failed; %s != %s" %\r
- (result, expected_url))\r
- result = urllib.url2pathname(expected_url)\r
- self.assertEqual(expected_path, result,\r
- "url2pathame() failed; %s != %s" %\r
- (result, expected_path))\r
-\r
- def test_quoting(self):\r
- # Test automatic quoting and unquoting works for pathnam2url() and\r
- # url2pathname() respectively\r
- given = os.path.join("needs", "quot=ing", "here")\r
- expect = "needs/%s/here" % urllib.quote("quot=ing")\r
- result = urllib.pathname2url(given)\r
- self.assertEqual(expect, result,\r
- "pathname2url() failed; %s != %s" %\r
- (expect, result))\r
- expect = given\r
- result = urllib.url2pathname(result)\r
- self.assertEqual(expect, result,\r
- "url2pathname() failed; %s != %s" %\r
- (expect, result))\r
- given = os.path.join("make sure", "using_quote")\r
- expect = "%s/using_quote" % urllib.quote("make sure")\r
- result = urllib.pathname2url(given)\r
- self.assertEqual(expect, result,\r
- "pathname2url() failed; %s != %s" %\r
- (expect, result))\r
- given = "make+sure/using_unquote"\r
- expect = os.path.join("make+sure", "using_unquote")\r
- result = urllib.url2pathname(given)\r
- self.assertEqual(expect, result,\r
- "url2pathname() failed; %s != %s" %\r
- (expect, result))\r
-\r
- @unittest.skipUnless(sys.platform == 'win32',\r
- 'test specific to the nturl2path library')\r
- def test_ntpath(self):\r
- given = ('/C:/', '///C:/', '/C|//')\r
- expect = 'C:\\'\r
- for url in given:\r
- result = urllib.url2pathname(url)\r
- self.assertEqual(expect, result,\r
- 'nturl2path.url2pathname() failed; %s != %s' %\r
- (expect, result))\r
- given = '///C|/path'\r
- expect = 'C:\\path'\r
- result = urllib.url2pathname(given)\r
- self.assertEqual(expect, result,\r
- 'nturl2path.url2pathname() failed; %s != %s' %\r
- (expect, result))\r
-\r
-class Utility_Tests(unittest.TestCase):\r
- """Testcase to test the various utility functions in the urllib."""\r
-\r
- def test_splitpasswd(self):\r
- """Some of the password examples are not sensible, but it is added to\r
- confirming to RFC2617 and addressing issue4675.\r
- """\r
- self.assertEqual(('user', 'ab'),urllib.splitpasswd('user:ab'))\r
- self.assertEqual(('user', 'a\nb'),urllib.splitpasswd('user:a\nb'))\r
- self.assertEqual(('user', 'a\tb'),urllib.splitpasswd('user:a\tb'))\r
- self.assertEqual(('user', 'a\rb'),urllib.splitpasswd('user:a\rb'))\r
- self.assertEqual(('user', 'a\fb'),urllib.splitpasswd('user:a\fb'))\r
- self.assertEqual(('user', 'a\vb'),urllib.splitpasswd('user:a\vb'))\r
- self.assertEqual(('user', 'a:b'),urllib.splitpasswd('user:a:b'))\r
-\r
-\r
-class URLopener_Tests(unittest.TestCase):\r
- """Testcase to test the open method of URLopener class."""\r
-\r
- def test_quoted_open(self):\r
- class DummyURLopener(urllib.URLopener):\r
- def open_spam(self, url):\r
- return url\r
-\r
- self.assertEqual(DummyURLopener().open(\r
- 'spam://example/ /'),'//example/%20/')\r
-\r
- # test the safe characters are not quoted by urlopen\r
- self.assertEqual(DummyURLopener().open(\r
- "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),\r
- "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")\r
-\r
-\r
-# Just commented them out.\r
-# Can't really tell why keep failing in windows and sparc.\r
-# Everywhere else they work ok, but on those machines, sometimes\r
-# fail in one of the tests, sometimes in other. I have a linux, and\r
-# the tests go ok.\r
-# If anybody has one of the problematic enviroments, please help!\r
-# . Facundo\r
-#\r
-# def server(evt):\r
-# import socket, time\r
-# serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r
-# serv.settimeout(3)\r
-# serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\r
-# serv.bind(("", 9093))\r
-# serv.listen(5)\r
-# try:\r
-# conn, addr = serv.accept()\r
-# conn.send("1 Hola mundo\n")\r
-# cantdata = 0\r
-# while cantdata < 13:\r
-# data = conn.recv(13-cantdata)\r
-# cantdata += len(data)\r
-# time.sleep(.3)\r
-# conn.send("2 No more lines\n")\r
-# conn.close()\r
-# except socket.timeout:\r
-# pass\r
-# finally:\r
-# serv.close()\r
-# evt.set()\r
-#\r
-# class FTPWrapperTests(unittest.TestCase):\r
-#\r
-# def setUp(self):\r
-# import ftplib, time, threading\r
-# ftplib.FTP.port = 9093\r
-# self.evt = threading.Event()\r
-# threading.Thread(target=server, args=(self.evt,)).start()\r
-# time.sleep(.1)\r
-#\r
-# def tearDown(self):\r
-# self.evt.wait()\r
-#\r
-# def testBasic(self):\r
-# # connects\r
-# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])\r
-# ftp.close()\r
-#\r
-# def testTimeoutNone(self):\r
-# # global default timeout is ignored\r
-# import socket\r
-# self.assertTrue(socket.getdefaulttimeout() is None)\r
-# socket.setdefaulttimeout(30)\r
-# try:\r
-# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])\r
-# finally:\r
-# socket.setdefaulttimeout(None)\r
-# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)\r
-# ftp.close()\r
-#\r
-# def testTimeoutDefault(self):\r
-# # global default timeout is used\r
-# import socket\r
-# self.assertTrue(socket.getdefaulttimeout() is None)\r
-# socket.setdefaulttimeout(30)\r
-# try:\r
-# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])\r
-# finally:\r
-# socket.setdefaulttimeout(None)\r
-# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)\r
-# ftp.close()\r
-#\r
-# def testTimeoutValue(self):\r
-# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [],\r
-# timeout=30)\r
-# self.assertEqual(ftp.ftp.sock.gettimeout(), 30)\r
-# ftp.close()\r
-\r
-\r
-\r
-def test_main():\r
- import warnings\r
- with warnings.catch_warnings():\r
- warnings.filterwarnings('ignore', ".*urllib\.urlopen.*Python 3.0",\r
- DeprecationWarning)\r
- test_support.run_unittest(\r
- urlopen_FileTests,\r
- urlopen_HttpTests,\r
- urlretrieve_FileTests,\r
- ProxyTests,\r
- QuotingTests,\r
- UnquotingTests,\r
- urlencode_Tests,\r
- Pathname_Tests,\r
- Utility_Tests,\r
- URLopener_Tests,\r
- #FTPWrapperTests,\r
- )\r
-\r
-\r
-\r
-if __name__ == '__main__':\r
- test_main()\r