Debian Codegraph @

lib-python/3/test/test_urllib.py

raw symbols SCIP
1 """Regression tests for what was in Python 2's "urllib" module"""
2
3 import urllib.parse
4 import urllib.request
5 import urllib.error
6 import http.client
7 import email.message
8 import io
9 import unittest
10 from unittest.mock import patch
11 from test import support
12 from test.support import os_helper
13 from test.support import socket_helper
14 from test.support import warnings_helper
15 from test.support import control_characters_c0
16 import os
17 try:
18 import ssl
19 except ImportError:
20 ssl = None
21 import sys
22 import tempfile
23 from nturl2path import url2pathname, pathname2url
24
25 from base64 import b64encode
26 import collections
27
28
29 if not socket_helper.has_gethostname:
30 raise unittest.SkipTest("test requires gethostname()")
31
32
33 def hexescape(char):
34 """Escape char as RFC 2396 specifies"""
35 hex_repr = hex(ord(char))[2:].upper()
36 if len(hex_repr) == 1:
37 hex_repr = "0%s" % hex_repr
38 return "%" + hex_repr
39
40 # Shortcut for testing FancyURLopener
41 _urlopener = None
42
43
44 def urlopen(url, data=None, proxies=None):
45 """urlopen(url [, data]) -> open file-like object"""
46 global _urlopener
47 if proxies is not None:
48 opener = urllib.request.FancyURLopener(proxies=proxies)
49 elif not _urlopener:
50 opener = FancyURLopener()
51 _urlopener = opener
52 else:
53 opener = _urlopener
54 if data is None:
55 return opener.open(url)
56 else:
57 return opener.open(url, data)
58
59
60 def FancyURLopener():
61 with warnings_helper.check_warnings(
62 ('FancyURLopener style of invoking requests is deprecated.',
63 DeprecationWarning)):
64 return urllib.request.FancyURLopener()
65
66
67 def fakehttp(fakedata, mock_close=False):
68 class FakeSocket(io.BytesIO):
69 io_refs = 1
70
71 def sendall(self, data):
72 FakeHTTPConnection.buf = data
73
74 def makefile(self, *args, **kwds):
75 self.io_refs += 1
76 return self
77
78 def read(self, amt=None):
79 if self.closed:
80 return b""
81 return io.BytesIO.read(self, amt)
82
83 def readline(self, length=None):
84 if self.closed:
85 return b""
86 return io.BytesIO.readline(self, length)
87
88 def close(self):
89 self.io_refs -= 1
90 if self.io_refs == 0:
91 io.BytesIO.close(self)
92
93 class FakeHTTPConnection(http.client.HTTPConnection):
94
95 # buffer to store data for verification in urlopen tests.
96 buf = None
97
98 def connect(self):
99 self.sock = FakeSocket(self.fakedata)
100 type(self).fakesock = self.sock
101
102 if mock_close:
103 # bpo-36918: HTTPConnection destructor calls close() which calls
104 # flush(). Problem: flush() calls self.fp.flush() which raises
105 # "ValueError: I/O operation on closed file" which is logged as an
106 # "Exception ignored in". Override close() to silence this error.
107 def close(self):
108 pass
109 FakeHTTPConnection.fakedata = fakedata
110
111 return FakeHTTPConnection
112
113
114 class FakeHTTPMixin(object):
115 def fakehttp(self, fakedata, mock_close=False):
116 fake_http_class = fakehttp(fakedata, mock_close=mock_close)
117 self._connection_class = http.client.HTTPConnection
118 http.client.HTTPConnection = fake_http_class
119
120 def unfakehttp(self):
121 http.client.HTTPConnection = self._connection_class
122
123
124 class FakeFTPMixin(object):
125 def fakeftp(self):
126 class FakeFtpWrapper(object):
127 def __init__(self, user, passwd, host, port, dirs, timeout=None,
128 persistent=True):
129 pass
130
131 def retrfile(self, file, type):
132 return io.BytesIO(), 0
133
134 def close(self):
135 pass
136
137 self._ftpwrapper_class = urllib.request.ftpwrapper
138 urllib.request.ftpwrapper = FakeFtpWrapper
139
140 def unfakeftp(self):
141 urllib.request.ftpwrapper = self._ftpwrapper_class
142
143
144 class urlopen_FileTests(unittest.TestCase):
145 """Test urlopen() opening a temporary file.
146
147 Try to test as much functionality as possible so as to cut down on reliance
148 on connecting to the Net for testing.
149
150 """
151
152 def setUp(self):
153 # Create a temp file to use for testing
154 self.text = bytes("test_urllib: %s\n" % self.__class__.__name__,
155 "ascii")
156 f = open(os_helper.TESTFN, 'wb')
157 try:
158 f.write(self.text)
159 finally:
160 f.close()
161 self.pathname = os_helper.TESTFN
162 self.quoted_pathname = urllib.parse.quote(self.pathname)
163 self.returned_obj = urlopen("file:%s" % self.quoted_pathname)
164
165 def tearDown(self):
166 """Shut down the open object"""
167 self.returned_obj.close()
168 os.remove(os_helper.TESTFN)
169
170 def test_interface(self):
171 # Make sure object returned by urlopen() has the specified methods
172 for attr in ("read", "readline", "readlines", "fileno",
173 "close", "info", "geturl", "getcode", "__iter__"):
174 self.assertTrue(hasattr(self.returned_obj, attr),
175 "object returned by urlopen() lacks %s attribute" %
176 attr)
177
178 def test_read(self):
179 self.assertEqual(self.text, self.returned_obj.read())
180
181 def test_readline(self):
182 self.assertEqual(self.text, self.returned_obj.readline())
183 self.assertEqual(b'', self.returned_obj.readline(),
184 "calling readline() after exhausting the file did not"
185 " return an empty string")
186
187 def test_readlines(self):
188 lines_list = self.returned_obj.readlines()
189 self.assertEqual(len(lines_list), 1,
190 "readlines() returned the wrong number of lines")
191 self.assertEqual(lines_list[0], self.text,
192 "readlines() returned improper text")
193
194 def test_fileno(self):
195 file_num = self.returned_obj.fileno()
196 self.assertIsInstance(file_num, int, "fileno() did not return an int")
197 self.assertEqual(os.read(file_num, len(self.text)), self.text,
198 "Reading on the file descriptor returned by fileno() "
199 "did not return the expected text")
200
201 def test_close(self):
202 # Test close() by calling it here and then having it be called again
203 # by the tearDown() method for the test
204 self.returned_obj.close()
205
206 def test_headers(self):
207 self.assertIsInstance(self.returned_obj.headers, email.message.Message)
208
209 def test_url(self):
210 self.assertEqual(self.returned_obj.url, self.quoted_pathname)
211
212 def test_status(self):
213 self.assertIsNone(self.returned_obj.status)
214
215 def test_info(self):
216 self.assertIsInstance(self.returned_obj.info(), email.message.Message)
217
218 def test_geturl(self):
219 self.assertEqual(self.returned_obj.geturl(), self.quoted_pathname)
220
221 def test_getcode(self):
222 self.assertIsNone(self.returned_obj.getcode())
223
224 def test_iter(self):
225 # Test iterator
226 # Don't need to count number of iterations since test would fail the
227 # instant it returned anything beyond the first line from the
228 # comparison.
229 # Use the iterator in the usual implicit way to test for ticket #4608.
230 for line in self.returned_obj:
231 self.assertEqual(line, self.text)
232
233 def test_relativelocalfile(self):
234 self.assertRaises(ValueError,urllib.request.urlopen,'./' + self.pathname)
235
236
237 class ProxyTests(unittest.TestCase):
238
239 def setUp(self):
240 # Records changes to env vars
241 self.env = self.enterContext(os_helper.EnvironmentVarGuard())
242 # Delete all proxy related env vars
243 for k in list(os.environ):
244 if 'proxy' in k.lower():
245 self.env.unset(k)
246
247 def test_getproxies_environment_keep_no_proxies(self):
248 self.env.set('NO_PROXY', 'localhost')
249 proxies = urllib.request.getproxies_environment()
250 # getproxies_environment use lowered case truncated (no '_proxy') keys
251 self.assertEqual('localhost', proxies['no'])
252 # List of no_proxies with space.
253 self.env.set('NO_PROXY', 'localhost, anotherdomain.com, newdomain.com:1234')
254 self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com'))
255 self.assertTrue(urllib.request.proxy_bypass_environment('anotherdomain.com:8888'))
256 self.assertTrue(urllib.request.proxy_bypass_environment('newdomain.com:1234'))
257
258 def test_proxy_cgi_ignore(self):
259 try:
260 self.env.set('HTTP_PROXY', 'http://somewhere:3128')
261 proxies = urllib.request.getproxies_environment()
262 self.assertEqual('http://somewhere:3128', proxies['http'])
263 self.env.set('REQUEST_METHOD', 'GET')
264 proxies = urllib.request.getproxies_environment()
265 self.assertNotIn('http', proxies)
266 finally:
267 self.env.unset('REQUEST_METHOD')
268 self.env.unset('HTTP_PROXY')
269
270 def test_proxy_bypass_environment_host_match(self):
271 bypass = urllib.request.proxy_bypass_environment
272 self.env.set('NO_PROXY',
273 'localhost, anotherdomain.com, newdomain.com:1234, .d.o.t')
274 self.assertTrue(bypass('localhost'))
275 self.assertTrue(bypass('LocalHost')) # MixedCase
276 self.assertTrue(bypass('LOCALHOST')) # UPPERCASE
277 self.assertTrue(bypass('.localhost'))
278 self.assertTrue(bypass('newdomain.com:1234'))
279 self.assertTrue(bypass('.newdomain.com:1234'))
280 self.assertTrue(bypass('foo.d.o.t')) # issue 29142
281 self.assertTrue(bypass('d.o.t'))
282 self.assertTrue(bypass('anotherdomain.com:8888'))
283 self.assertTrue(bypass('.anotherdomain.com:8888'))
284 self.assertTrue(bypass('www.newdomain.com:1234'))
285 self.assertFalse(bypass('prelocalhost'))
286 self.assertFalse(bypass('newdomain.com')) # no port
287 self.assertFalse(bypass('newdomain.com:1235')) # wrong port
288
289 def test_proxy_bypass_environment_always_match(self):
290 bypass = urllib.request.proxy_bypass_environment
291 self.env.set('NO_PROXY', '*')
292 self.assertTrue(bypass('newdomain.com'))
293 self.assertTrue(bypass('newdomain.com:1234'))
294 self.env.set('NO_PROXY', '*, anotherdomain.com')
295 self.assertTrue(bypass('anotherdomain.com'))
296 self.assertFalse(bypass('newdomain.com'))
297 self.assertFalse(bypass('newdomain.com:1234'))
298
299 def test_proxy_bypass_environment_newline(self):
300 bypass = urllib.request.proxy_bypass_environment
301 self.env.set('NO_PROXY',
302 'localhost, anotherdomain.com, newdomain.com:1234')
303 self.assertFalse(bypass('localhost\n'))
304 self.assertFalse(bypass('anotherdomain.com:8888\n'))
305 self.assertFalse(bypass('newdomain.com:1234\n'))
306
307
308 class ProxyTests_withOrderedEnv(unittest.TestCase):
309
310 def setUp(self):
311 # We need to test conditions, where variable order _is_ significant
312 self._saved_env = os.environ
313 # Monkey patch os.environ, start with empty fake environment
314 os.environ = collections.OrderedDict()
315
316 def tearDown(self):
317 os.environ = self._saved_env
318
319 def test_getproxies_environment_prefer_lowercase(self):
320 # Test lowercase preference with removal
321 os.environ['no_proxy'] = ''
322 os.environ['No_Proxy'] = 'localhost'
323 self.assertFalse(urllib.request.proxy_bypass_environment('localhost'))
324 self.assertFalse(urllib.request.proxy_bypass_environment('arbitrary'))
325 os.environ['http_proxy'] = ''
326 os.environ['HTTP_PROXY'] = 'http://somewhere:3128'
327 proxies = urllib.request.getproxies_environment()
328 self.assertEqual({}, proxies)
329 # Test lowercase preference of proxy bypass and correct matching including ports
330 os.environ['no_proxy'] = 'localhost, noproxy.com, my.proxy:1234'
331 os.environ['No_Proxy'] = 'xyz.com'
332 self.assertTrue(urllib.request.proxy_bypass_environment('localhost'))
333 self.assertTrue(urllib.request.proxy_bypass_environment('noproxy.com:5678'))
334 self.assertTrue(urllib.request.proxy_bypass_environment('my.proxy:1234'))
335 self.assertFalse(urllib.request.proxy_bypass_environment('my.proxy'))
336 self.assertFalse(urllib.request.proxy_bypass_environment('arbitrary'))
337 # Test lowercase preference with replacement
338 os.environ['http_proxy'] = 'http://somewhere:3128'
339 os.environ['Http_Proxy'] = 'http://somewhereelse:3128'
340 proxies = urllib.request.getproxies_environment()
341 self.assertEqual('http://somewhere:3128', proxies['http'])
342
343
344 class urlopen_HttpTests(unittest.TestCase, FakeHTTPMixin, FakeFTPMixin):
345 """Test urlopen() opening a fake http connection."""
346
347 def check_read(self, ver):
348 self.fakehttp(b"HTTP/" + ver + b" 200 OK\r\n\r\nHello!")
349 try:
350 fp = urlopen("http://python.org/")
351 self.assertEqual(fp.readline(), b"Hello!")
352 self.assertEqual(fp.readline(), b"")
353 self.assertEqual(fp.geturl(), 'http://python.org/')
354 self.assertEqual(fp.getcode(), 200)
355 finally:
356 self.unfakehttp()
357
358 def test_url_fragment(self):
359 # Issue #11703: geturl() omits fragments in the original URL.
360 url = 'http://docs.python.org/library/urllib.html#OK'
361 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
362 try:
363 fp = urllib.request.urlopen(url)
364 self.assertEqual(fp.geturl(), url)
365 finally:
366 self.unfakehttp()
367
368 def test_willclose(self):
369 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
370 try:
371 resp = urlopen("http://www.python.org")
372 self.assertTrue(resp.fp.will_close)
373 finally:
374 self.unfakehttp()
375
376 @unittest.skipUnless(ssl, "ssl module required")
377 def test_url_path_with_control_char_rejected(self):
378 for char_no in list(range(0, 0x21)) + [0x7f]:
379 char = chr(char_no)
380 schemeless_url = f"//localhost:7777/test{char}/"
381 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
382 try:
383 # We explicitly test urllib.request.urlopen() instead of the top
384 # level 'def urlopen()' function defined in this... (quite ugly)
385 # test suite. They use different url opening codepaths. Plain
386 # urlopen uses FancyURLOpener which goes via a codepath that
387 # calls urllib.parse.quote() on the URL which makes all of the
388 # above attempts at injection within the url _path_ safe.
389 escaped_char_repr = repr(char).replace('\\', r'\\')
390 InvalidURL = http.client.InvalidURL
391 with self.assertRaisesRegex(
392 InvalidURL, f"contain control.*{escaped_char_repr}"):
393 urllib.request.urlopen(f"http:{schemeless_url}")
394 with self.assertRaisesRegex(
395 InvalidURL, f"contain control.*{escaped_char_repr}"):
396 urllib.request.urlopen(f"https:{schemeless_url}")
397 # This code path quotes the URL so there is no injection.
398 resp = urlopen(f"http:{schemeless_url}")
399 self.assertNotIn(char, resp.geturl())
400 finally:
401 self.unfakehttp()
402
403 @unittest.skipUnless(ssl, "ssl module required")
404 def test_url_path_with_newline_header_injection_rejected(self):
405 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
406 host = "localhost:7777?a=1 HTTP/1.1\r\nX-injected: header\r\nTEST: 123"
407 schemeless_url = "//" + host + ":8080/test/?test=a"
408 try:
409 # We explicitly test urllib.request.urlopen() instead of the top
410 # level 'def urlopen()' function defined in this... (quite ugly)
411 # test suite. They use different url opening codepaths. Plain
412 # urlopen uses FancyURLOpener which goes via a codepath that
413 # calls urllib.parse.quote() on the URL which makes all of the
414 # above attempts at injection within the url _path_ safe.
415 InvalidURL = http.client.InvalidURL
416 with self.assertRaisesRegex(
417 InvalidURL, r"contain control.*\\r.*(found at least . .)"):
418 urllib.request.urlopen(f"http:{schemeless_url}")
419 with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"):
420 urllib.request.urlopen(f"https:{schemeless_url}")
421 # This code path quotes the URL so there is no injection.
422 resp = urlopen(f"http:{schemeless_url}")
423 self.assertNotIn(' ', resp.geturl())
424 self.assertNotIn('\r', resp.geturl())
425 self.assertNotIn('\n', resp.geturl())
426 finally:
427 self.unfakehttp()
428
429 @unittest.skipUnless(ssl, "ssl module required")
430 def test_url_host_with_control_char_rejected(self):
431 for char_no in list(range(0, 0x21)) + [0x7f]:
432 char = chr(char_no)
433 schemeless_url = f"//localhost{char}/test/"
434 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
435 try:
436 escaped_char_repr = repr(char).replace('\\', r'\\')
437 InvalidURL = http.client.InvalidURL
438 with self.assertRaisesRegex(
439 InvalidURL, f"contain control.*{escaped_char_repr}"):
440 urlopen(f"http:{schemeless_url}")
441 with self.assertRaisesRegex(InvalidURL, f"contain control.*{escaped_char_repr}"):
442 urlopen(f"https:{schemeless_url}")
443 finally:
444 self.unfakehttp()
445
446 @unittest.skipUnless(ssl, "ssl module required")
447 def test_url_host_with_newline_header_injection_rejected(self):
448 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello.")
449 host = "localhost\r\nX-injected: header\r\n"
450 schemeless_url = "//" + host + ":8080/test/?test=a"
451 try:
452 InvalidURL = http.client.InvalidURL
453 with self.assertRaisesRegex(
454 InvalidURL, r"contain control.*\\r"):
455 urlopen(f"http:{schemeless_url}")
456 with self.assertRaisesRegex(InvalidURL, r"contain control.*\\n"):
457 urlopen(f"https:{schemeless_url}")
458 finally:
459 self.unfakehttp()
460
461 def test_read_0_9(self):
462 # "0.9" response accepted (but not "simple responses" without
463 # a status line)
464 self.check_read(b"0.9")
465
466 def test_read_1_0(self):
467 self.check_read(b"1.0")
468
469 def test_read_1_1(self):
470 self.check_read(b"1.1")
471
472 def test_read_bogus(self):
473 # urlopen() should raise OSError for many error codes.
474 self.fakehttp(b'''HTTP/1.1 401 Authentication Required
475 Date: Wed, 02 Jan 2008 03:03:54 GMT
476 Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
477 Connection: close
478 Content-Type: text/html; charset=iso-8859-1
479 ''', mock_close=True)
480 try:
481 self.assertRaises(OSError, urlopen, "http://python.org/")
482 finally:
483 self.unfakehttp()
484
485 def test_invalid_redirect(self):
486 # urlopen() should raise OSError for many error codes.
487 self.fakehttp(b'''HTTP/1.1 302 Found
488 Date: Wed, 02 Jan 2008 03:03:54 GMT
489 Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
490 Location: file://guidocomputer.athome.com:/python/license
491 Connection: close
492 Content-Type: text/html; charset=iso-8859-1
493 ''', mock_close=True)
494 try:
495 msg = "Redirection to url 'file:"
496 with self.assertRaisesRegex(urllib.error.HTTPError, msg):
497 urlopen("http://python.org/")
498 finally:
499 self.unfakehttp()
500
501 def test_redirect_limit_independent(self):
502 # Ticket #12923: make sure independent requests each use their
503 # own retry limit.
504 for i in range(FancyURLopener().maxtries):
505 self.fakehttp(b'''HTTP/1.1 302 Found
506 Location: file://guidocomputer.athome.com:/python/license
507 Connection: close
508 ''', mock_close=True)
509 try:
510 self.assertRaises(urllib.error.HTTPError, urlopen,
511 "http://something")
512 finally:
513 self.unfakehttp()
514
515 def test_empty_socket(self):
516 # urlopen() raises OSError if the underlying socket does not send any
517 # data. (#1680230)
518 self.fakehttp(b'')
519 try:
520 self.assertRaises(OSError, urlopen, "http://something")
521 finally:
522 self.unfakehttp()
523
524 def test_missing_localfile(self):
525 # Test for #10836
526 with self.assertRaises(urllib.error.URLError) as e:
527 urlopen('file://localhost/a/file/which/doesnot/exists.py')
528 self.assertTrue(e.exception.filename)
529 self.assertTrue(e.exception.reason)
530
531 def test_file_notexists(self):
532 fd, tmp_file = tempfile.mkstemp()
533 tmp_fileurl = 'file://localhost/' + tmp_file.replace(os.path.sep, '/')
534 try:
535 self.assertTrue(os.path.exists(tmp_file))
536 with urlopen(tmp_fileurl) as fobj:
537 self.assertTrue(fobj)
538 finally:
539 os.close(fd)
540 os.unlink(tmp_file)
541 self.assertFalse(os.path.exists(tmp_file))
542 with self.assertRaises(urllib.error.URLError):
543 urlopen(tmp_fileurl)
544
545 def test_ftp_nohost(self):
546 test_ftp_url = 'ftp:///path'
547 with self.assertRaises(urllib.error.URLError) as e:
548 urlopen(test_ftp_url)
549 self.assertFalse(e.exception.filename)
550 self.assertTrue(e.exception.reason)
551
552 def test_ftp_nonexisting(self):
553 with self.assertRaises(urllib.error.URLError) as e:
554 urlopen('ftp://localhost/a/file/which/doesnot/exists.py')
555 self.assertFalse(e.exception.filename)
556 self.assertTrue(e.exception.reason)
557
558 @patch.object(urllib.request, 'MAXFTPCACHE', 0)
559 def test_ftp_cache_pruning(self):
560 self.fakeftp()
561 try:
562 urllib.request.ftpcache['test'] = urllib.request.ftpwrapper('user', 'pass', 'localhost', 21, [])
563 urlopen('ftp://localhost')
564 finally:
565 self.unfakeftp()
566
567 def test_userpass_inurl(self):
568 self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
569 try:
570 fp = urlopen("http://user:[email protected]/")
571 self.assertEqual(fp.readline(), b"Hello!")
572 self.assertEqual(fp.readline(), b"")
573 self.assertEqual(fp.geturl(), 'http://user:[email protected]/')
574 self.assertEqual(fp.getcode(), 200)
575 finally:
576 self.unfakehttp()
577
578 def test_userpass_inurl_w_spaces(self):
579 self.fakehttp(b"HTTP/1.0 200 OK\r\n\r\nHello!")
580 try:
581 userpass = "a b:c d"
582 url = "http://{}@python.org/".format(userpass)
583 fakehttp_wrapper = http.client.HTTPConnection
584 authorization = ("Authorization: Basic %s\r\n" %
585 b64encode(userpass.encode("ASCII")).decode("ASCII"))
586 fp = urlopen(url)
587 # The authorization header must be in place
588 self.assertIn(authorization, fakehttp_wrapper.buf.decode("UTF-8"))
589 self.assertEqual(fp.readline(), b"Hello!")
590 self.assertEqual(fp.readline(), b"")
591 # the spaces are quoted in URL so no match
592 self.assertNotEqual(fp.geturl(), url)
593 self.assertEqual(fp.getcode(), 200)
594 finally:
595 self.unfakehttp()
596
597 def test_URLopener_deprecation(self):
598 with warnings_helper.check_warnings(('',DeprecationWarning)):
599 urllib.request.URLopener()
600
601 @unittest.skipUnless(ssl, "ssl module required")
602 def test_cafile_and_context(self):
603 context = ssl.create_default_context()
604 with warnings_helper.check_warnings(('', DeprecationWarning)):
605 with self.assertRaises(ValueError):
606 urllib.request.urlopen(
607 "https://localhost", cafile="/nonexistent/path", context=context
608 )
609
610
611 class urlopen_DataTests(unittest.TestCase):
612 """Test urlopen() opening a data URL."""
613
614 def setUp(self):
615 # clear _opener global variable
616 self.addCleanup(urllib.request.urlcleanup)
617
618 # text containing URL special- and unicode-characters
619 self.text = "test data URLs :;,%=& \u00f6 \u00c4 "
620 # 2x1 pixel RGB PNG image with one black and one white pixel
621 self.image = (
622 b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x02\x00\x00\x00'
623 b'\x01\x08\x02\x00\x00\x00{@\xe8\xdd\x00\x00\x00\x01sRGB\x00\xae'
624 b'\xce\x1c\xe9\x00\x00\x00\x0fIDAT\x08\xd7c```\xf8\xff\xff?\x00'
625 b'\x06\x01\x02\xfe\no/\x1e\x00\x00\x00\x00IEND\xaeB`\x82')
626
627 self.text_url = (
628 "data:text/plain;charset=UTF-8,test%20data%20URLs%20%3A%3B%2C%25%3"
629 "D%26%20%C3%B6%20%C3%84%20")
630 self.text_url_base64 = (
631 "data:text/plain;charset=ISO-8859-1;base64,dGVzdCBkYXRhIFVSTHMgOjs"
632 "sJT0mIPYgxCA%3D")
633 # base64 encoded data URL that contains ignorable spaces,
634 # such as "\n", " ", "%0A", and "%20".
635 self.image_url = (
636 "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7\n"
637 "QOjdAAAAAXNSR0IArs4c6QAAAA9JREFUCNdj%0AYGBg%2BP//PwAGAQL%2BCm8 "
638 "vHgAAAABJRU5ErkJggg%3D%3D%0A%20")
639
640 self.text_url_resp = urllib.request.urlopen(self.text_url)
641 self.text_url_base64_resp = urllib.request.urlopen(
642 self.text_url_base64)
643 self.image_url_resp = urllib.request.urlopen(self.image_url)
644
645 def test_interface(self):
646 # Make sure object returned by urlopen() has the specified methods
647 for attr in ("read", "readline", "readlines",
648 "close", "info", "geturl", "getcode", "__iter__"):
649 self.assertTrue(hasattr(self.text_url_resp, attr),
650 "object returned by urlopen() lacks %s attribute" %
651 attr)
652
653 def test_info(self):
654 self.assertIsInstance(self.text_url_resp.info(), email.message.Message)
655 self.assertEqual(self.text_url_base64_resp.info().get_params(),
656 [('text/plain', ''), ('charset', 'ISO-8859-1')])
657 self.assertEqual(self.image_url_resp.info()['content-length'],
658 str(len(self.image)))
659 self.assertEqual(urllib.request.urlopen("data:,").info().get_params(),
660 [('text/plain', ''), ('charset', 'US-ASCII')])
661
662 def test_geturl(self):
663 self.assertEqual(self.text_url_resp.geturl(), self.text_url)
664 self.assertEqual(self.text_url_base64_resp.geturl(),
665 self.text_url_base64)
666 self.assertEqual(self.image_url_resp.geturl(), self.image_url)
667
668 def test_read_text(self):
669 self.assertEqual(self.text_url_resp.read().decode(
670 dict(self.text_url_resp.info().get_params())['charset']), self.text)
671
672 def test_read_text_base64(self):
673 self.assertEqual(self.text_url_base64_resp.read().decode(
674 dict(self.text_url_base64_resp.info().get_params())['charset']),
675 self.text)
676
677 def test_read_image(self):
678 self.assertEqual(self.image_url_resp.read(), self.image)
679
680 def test_missing_comma(self):
681 self.assertRaises(ValueError,urllib.request.urlopen,'data:text/plain')
682
683 def test_invalid_base64_data(self):
684 # missing padding character
685 self.assertRaises(ValueError,urllib.request.urlopen,'data:;base64,Cg=')
686
687 def test_invalid_mediatype(self):
688 for c0 in control_characters_c0():
689 self.assertRaises(ValueError,urllib.request.urlopen,
690 f'data:text/html;{c0},data')
691 for c0 in control_characters_c0():
692 self.assertRaises(ValueError,urllib.request.urlopen,
693 f'data:text/html{c0};base64,ZGF0YQ==')
694
695 class urlretrieve_FileTests(unittest.TestCase):
696 """Test urllib.urlretrieve() on local files"""
697
698 def setUp(self):
699 # clear _opener global variable
700 self.addCleanup(urllib.request.urlcleanup)
701
702 # Create a list of temporary files. Each item in the list is a file
703 # name (absolute path or relative to the current working directory).
704 # All files in this list will be deleted in the tearDown method. Note,
705 # this only helps to makes sure temporary files get deleted, but it
706 # does nothing about trying to close files that may still be open. It
707 # is the responsibility of the developer to properly close files even
708 # when exceptional conditions occur.
709 self.tempFiles = []
710
711 # Create a temporary file.
712 self.registerFileForCleanUp(os_helper.TESTFN)
713 self.text = b'testing urllib.urlretrieve'
714 try:
715 FILE = open(os_helper.TESTFN, 'wb')
716 FILE.write(self.text)
717 FILE.close()
718 finally:
719 try: FILE.close()
720 except: pass
721
722 def tearDown(self):
723 # Delete the temporary files.
724 for each in self.tempFiles:
725 try: os.remove(each)
726 except: pass
727
728 def constructLocalFileUrl(self, filePath):
729 filePath = os.path.abspath(filePath)
730 try:
731 filePath.encode("utf-8")
732 except UnicodeEncodeError:
733 raise unittest.SkipTest("filePath is not encodable to utf8")
734 return "file://%s" % urllib.request.pathname2url(filePath)
735
736 def createNewTempFile(self, data=b""):
737 """Creates a new temporary file containing the specified data,
738 registers the file for deletion during the test fixture tear down, and
739 returns the absolute path of the file."""
740
741 newFd, newFilePath = tempfile.mkstemp()
742 try:
743 self.registerFileForCleanUp(newFilePath)
744 newFile = os.fdopen(newFd, "wb")
745 newFile.write(data)
746 newFile.close()
747 finally:
748 try: newFile.close()
749 except: pass
750 return newFilePath
751
752 def registerFileForCleanUp(self, fileName):
753 self.tempFiles.append(fileName)
754
755 def test_basic(self):
756 # Make sure that a local file just gets its own location returned and
757 # a headers value is returned.
758 result = urllib.request.urlretrieve("file:%s" % os_helper.TESTFN)
759 self.assertEqual(result[0], os_helper.TESTFN)
760 self.assertIsInstance(result[1], email.message.Message,
761 "did not get an email.message.Message instance "
762 "as second returned value")
763
764 def test_copy(self):
765 # Test that setting the filename argument works.
766 second_temp = "%s.2" % os_helper.TESTFN
767 self.registerFileForCleanUp(second_temp)
768 result = urllib.request.urlretrieve(self.constructLocalFileUrl(
769 os_helper.TESTFN), second_temp)
770 self.assertEqual(second_temp, result[0])
771 self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
772 "made")
773 FILE = open(second_temp, 'rb')
774 try:
775 text = FILE.read()
776 FILE.close()
777 finally:
778 try: FILE.close()
779 except: pass
780 self.assertEqual(self.text, text)
781
782 def test_reporthook(self):
783 # Make sure that the reporthook works.
784 def hooktester(block_count, block_read_size, file_size, count_holder=[0]):
785 self.assertIsInstance(block_count, int)
786 self.assertIsInstance(block_read_size, int)
787 self.assertIsInstance(file_size, int)
788 self.assertEqual(block_count, count_holder[0])
789 count_holder[0] = count_holder[0] + 1
790 second_temp = "%s.2" % os_helper.TESTFN
791 self.registerFileForCleanUp(second_temp)
792 urllib.request.urlretrieve(
793 self.constructLocalFileUrl(os_helper.TESTFN),
794 second_temp, hooktester)
795
796 def test_reporthook_0_bytes(self):
797 # Test on zero length file. Should call reporthook only 1 time.
798 report = []
799 def hooktester(block_count, block_read_size, file_size, _report=report):
800 _report.append((block_count, block_read_size, file_size))
801 srcFileName = self.createNewTempFile()
802 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
803 os_helper.TESTFN, hooktester)
804 self.assertEqual(len(report), 1)
805 self.assertEqual(report[0][2], 0)
806
807 def test_reporthook_5_bytes(self):
808 # Test on 5 byte file. Should call reporthook only 2 times (once when
809 # the "network connection" is established and once when the block is
810 # read).
811 report = []
812 def hooktester(block_count, block_read_size, file_size, _report=report):
813 _report.append((block_count, block_read_size, file_size))
814 srcFileName = self.createNewTempFile(b"x" * 5)
815 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
816 os_helper.TESTFN, hooktester)
817 self.assertEqual(len(report), 2)
818 self.assertEqual(report[0][2], 5)
819 self.assertEqual(report[1][2], 5)
820
821 def test_reporthook_8193_bytes(self):
822 # Test on 8193 byte file. Should call reporthook only 3 times (once
823 # when the "network connection" is established, once for the next 8192
824 # bytes, and once for the last byte).
825 report = []
826 def hooktester(block_count, block_read_size, file_size, _report=report):
827 _report.append((block_count, block_read_size, file_size))
828 srcFileName = self.createNewTempFile(b"x" * 8193)
829 urllib.request.urlretrieve(self.constructLocalFileUrl(srcFileName),
830 os_helper.TESTFN, hooktester)
831 self.assertEqual(len(report), 3)
832 self.assertEqual(report[0][2], 8193)
833 self.assertEqual(report[0][1], 8192)
834 self.assertEqual(report[1][1], 8192)
835 self.assertEqual(report[2][1], 8192)
836
837
838 class urlretrieve_HttpTests(unittest.TestCase, FakeHTTPMixin):
839 """Test urllib.urlretrieve() using fake http connections"""
840
841 def test_short_content_raises_ContentTooShortError(self):
842 self.addCleanup(urllib.request.urlcleanup)
843
844 self.fakehttp(b'''HTTP/1.1 200 OK
845 Date: Wed, 02 Jan 2008 03:03:54 GMT
846 Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
847 Connection: close
848 Content-Length: 100
849 Content-Type: text/html; charset=iso-8859-1
850
851 FF
852 ''')
853
854 def _reporthook(par1, par2, par3):
855 pass
856
857 with self.assertRaises(urllib.error.ContentTooShortError):
858 try:
859 urllib.request.urlretrieve(support.TEST_HTTP_URL,
860 reporthook=_reporthook)
861 finally:
862 self.unfakehttp()
863
864 def test_short_content_raises_ContentTooShortError_without_reporthook(self):
865 self.addCleanup(urllib.request.urlcleanup)
866
867 self.fakehttp(b'''HTTP/1.1 200 OK
868 Date: Wed, 02 Jan 2008 03:03:54 GMT
869 Server: Apache/1.3.33 (Debian GNU/Linux) mod_ssl/2.8.22 OpenSSL/0.9.7e
870 Connection: close
871 Content-Length: 100
872 Content-Type: text/html; charset=iso-8859-1
873
874 FF
875 ''')
876 with self.assertRaises(urllib.error.ContentTooShortError):
877 try:
878 urllib.request.urlretrieve(support.TEST_HTTP_URL)
879 finally:
880 self.unfakehttp()
881
882
883 class QuotingTests(unittest.TestCase):
884 r"""Tests for urllib.quote() and urllib.quote_plus()
885
886 According to RFC 3986 (Uniform Resource Identifiers), to escape a
887 character you write it as '%' + <2 character US-ASCII hex value>.
888 The Python code of ``'%' + hex(ord(<character>))[2:]`` escapes a
889 character properly. Case does not matter on the hex letters.
890
891 The various character sets specified are:
892
893 Reserved characters : ";/?:@&=+$,"
894 Have special meaning in URIs and must be escaped if not being used for
895 their special meaning
896 Data characters : letters, digits, and "-_.!~*'()"
897 Unreserved and do not need to be escaped; can be, though, if desired
898 Control characters : 0x00 - 0x1F, 0x7F
899 Have no use in URIs so must be escaped
900 space : 0x20
901 Must be escaped
902 Delimiters : '<>#%"'
903 Must be escaped
904 Unwise : "{}|\^[]`"
905 Must be escaped
906
907 """
908
909 def test_never_quote(self):
910 # Make sure quote() does not quote letters, digits, and "_,.-"
911 do_not_quote = '' .join(["ABCDEFGHIJKLMNOPQRSTUVWXYZ",
912 "abcdefghijklmnopqrstuvwxyz",
913 "0123456789",
914 "_.-~"])
915 result = urllib.parse.quote(do_not_quote)
916 self.assertEqual(do_not_quote, result,
917 "using quote(): %r != %r" % (do_not_quote, result))
918 result = urllib.parse.quote_plus(do_not_quote)
919 self.assertEqual(do_not_quote, result,
920 "using quote_plus(): %r != %r" % (do_not_quote, result))
921
922 def test_default_safe(self):
923 # Test '/' is default value for 'safe' parameter
924 self.assertEqual(urllib.parse.quote.__defaults__[0], '/')
925
926 def test_safe(self):
927 # Test setting 'safe' parameter does what it should do
928 quote_by_default = "<>"
929 result = urllib.parse.quote(quote_by_default, safe=quote_by_default)
930 self.assertEqual(quote_by_default, result,
931 "using quote(): %r != %r" % (quote_by_default, result))
932 result = urllib.parse.quote_plus(quote_by_default,
933 safe=quote_by_default)
934 self.assertEqual(quote_by_default, result,
935 "using quote_plus(): %r != %r" %
936 (quote_by_default, result))
937 # Safe expressed as bytes rather than str
938 result = urllib.parse.quote(quote_by_default, safe=b"<>")
939 self.assertEqual(quote_by_default, result,
940 "using quote(): %r != %r" % (quote_by_default, result))
941 # "Safe" non-ASCII characters should have no effect
942 # (Since URIs are not allowed to have non-ASCII characters)
943 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="\xfc")
944 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
945 self.assertEqual(expect, result,
946 "using quote(): %r != %r" %
947 (expect, result))
948 # Same as above, but using a bytes rather than str
949 result = urllib.parse.quote("a\xfcb", encoding="latin-1", safe=b"\xfc")
950 expect = urllib.parse.quote("a\xfcb", encoding="latin-1", safe="")
951 self.assertEqual(expect, result,
952 "using quote(): %r != %r" %
953 (expect, result))
954
955 def test_default_quoting(self):
956 # Make sure all characters that should be quoted are by default sans
957 # space (separate test for that).
958 should_quote = [chr(num) for num in range(32)] # For 0x00 - 0x1F
959 should_quote.append(r'<>#%"{}|\^[]`')
960 should_quote.append(chr(127)) # For 0x7F
961 should_quote = ''.join(should_quote)
962 for char in should_quote:
963 result = urllib.parse.quote(char)
964 self.assertEqual(hexescape(char), result,
965 "using quote(): "
966 "%s should be escaped to %s, not %s" %
967 (char, hexescape(char), result))
968 result = urllib.parse.quote_plus(char)
969 self.assertEqual(hexescape(char), result,
970 "using quote_plus(): "
971 "%s should be escapes to %s, not %s" %
972 (char, hexescape(char), result))
973 del should_quote
974 partial_quote = "ab[]cd"
975 expected = "ab%5B%5Dcd"
976 result = urllib.parse.quote(partial_quote)
977 self.assertEqual(expected, result,
978 "using quote(): %r != %r" % (expected, result))
979 result = urllib.parse.quote_plus(partial_quote)
980 self.assertEqual(expected, result,
981 "using quote_plus(): %r != %r" % (expected, result))
982
983 def test_quoting_space(self):
984 # Make sure quote() and quote_plus() handle spaces as specified in
985 # their unique way
986 result = urllib.parse.quote(' ')
987 self.assertEqual(result, hexescape(' '),
988 "using quote(): %r != %r" % (result, hexescape(' ')))
989 result = urllib.parse.quote_plus(' ')
990 self.assertEqual(result, '+',
991 "using quote_plus(): %r != +" % result)
992 given = "a b cd e f"
993 expect = given.replace(' ', hexescape(' '))
994 result = urllib.parse.quote(given)
995 self.assertEqual(expect, result,
996 "using quote(): %r != %r" % (expect, result))
997 expect = given.replace(' ', '+')
998 result = urllib.parse.quote_plus(given)
999 self.assertEqual(expect, result,
1000 "using quote_plus(): %r != %r" % (expect, result))
1001
1002 def test_quoting_plus(self):
1003 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma'),
1004 'alpha%2Bbeta+gamma')
1005 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', '+'),
1006 'alpha+beta+gamma')
1007 # Test with bytes
1008 self.assertEqual(urllib.parse.quote_plus(b'alpha+beta gamma'),
1009 'alpha%2Bbeta+gamma')
1010 # Test with safe bytes
1011 self.assertEqual(urllib.parse.quote_plus('alpha+beta gamma', b'+'),
1012 'alpha+beta+gamma')
1013
1014 def test_quote_bytes(self):
1015 # Bytes should quote directly to percent-encoded values
1016 given = b"\xa2\xd8ab\xff"
1017 expect = "%A2%D8ab%FF"
1018 result = urllib.parse.quote(given)
1019 self.assertEqual(expect, result,
1020 "using quote(): %r != %r" % (expect, result))
1021 # Encoding argument should raise type error on bytes input
1022 self.assertRaises(TypeError, urllib.parse.quote, given,
1023 encoding="latin-1")
1024 # quote_from_bytes should work the same
1025 result = urllib.parse.quote_from_bytes(given)
1026 self.assertEqual(expect, result,
1027 "using quote_from_bytes(): %r != %r"
1028 % (expect, result))
1029
1030 def test_quote_with_unicode(self):
1031 # Characters in Latin-1 range, encoded by default in UTF-8
1032 given = "\xa2\xd8ab\xff"
1033 expect = "%C2%A2%C3%98ab%C3%BF"
1034 result = urllib.parse.quote(given)
1035 self.assertEqual(expect, result,
1036 "using quote(): %r != %r" % (expect, result))
1037 # Characters in Latin-1 range, encoded by with None (default)
1038 result = urllib.parse.quote(given, encoding=None, errors=None)
1039 self.assertEqual(expect, result,
1040 "using quote(): %r != %r" % (expect, result))
1041 # Characters in Latin-1 range, encoded with Latin-1
1042 given = "\xa2\xd8ab\xff"
1043 expect = "%A2%D8ab%FF"
1044 result = urllib.parse.quote(given, encoding="latin-1")
1045 self.assertEqual(expect, result,
1046 "using quote(): %r != %r" % (expect, result))
1047 # Characters in BMP, encoded by default in UTF-8
1048 given = "\u6f22\u5b57" # "Kanji"
1049 expect = "%E6%BC%A2%E5%AD%97"
1050 result = urllib.parse.quote(given)
1051 self.assertEqual(expect, result,
1052 "using quote(): %r != %r" % (expect, result))
1053 # Characters in BMP, encoded with Latin-1
1054 given = "\u6f22\u5b57"
1055 self.assertRaises(UnicodeEncodeError, urllib.parse.quote, given,
1056 encoding="latin-1")
1057 # Characters in BMP, encoded with Latin-1, with replace error handling
1058 given = "\u6f22\u5b57"
1059 expect = "%3F%3F" # "??"
1060 result = urllib.parse.quote(given, encoding="latin-1",
1061 errors="replace")
1062 self.assertEqual(expect, result,
1063 "using quote(): %r != %r" % (expect, result))
1064 # Characters in BMP, Latin-1, with xmlcharref error handling
1065 given = "\u6f22\u5b57"
1066 expect = "%26%2328450%3B%26%2323383%3B" # "&#28450;&#23383;"
1067 result = urllib.parse.quote(given, encoding="latin-1",
1068 errors="xmlcharrefreplace")
1069 self.assertEqual(expect, result,
1070 "using quote(): %r != %r" % (expect, result))
1071
1072 def test_quote_plus_with_unicode(self):
1073 # Encoding (latin-1) test for quote_plus
1074 given = "\xa2\xd8 \xff"
1075 expect = "%A2%D8+%FF"
1076 result = urllib.parse.quote_plus(given, encoding="latin-1")
1077 self.assertEqual(expect, result,
1078 "using quote_plus(): %r != %r" % (expect, result))
1079 # Errors test for quote_plus
1080 given = "ab\u6f22\u5b57 cd"
1081 expect = "ab%3F%3F+cd"
1082 result = urllib.parse.quote_plus(given, encoding="latin-1",
1083 errors="replace")
1084 self.assertEqual(expect, result,
1085 "using quote_plus(): %r != %r" % (expect, result))
1086
1087
1088 class UnquotingTests(unittest.TestCase):
1089 """Tests for unquote() and unquote_plus()
1090
1091 See the doc string for quoting_Tests for details on quoting and such.
1092
1093 """
1094
1095 def test_unquoting(self):
1096 # Make sure unquoting of all ASCII values works
1097 escape_list = []
1098 for num in range(128):
1099 given = hexescape(chr(num))
1100 expect = chr(num)
1101 result = urllib.parse.unquote(given)
1102 self.assertEqual(expect, result,
1103 "using unquote(): %r != %r" % (expect, result))
1104 result = urllib.parse.unquote_plus(given)
1105 self.assertEqual(expect, result,
1106 "using unquote_plus(): %r != %r" %
1107 (expect, result))
1108 escape_list.append(given)
1109 escape_string = ''.join(escape_list)
1110 del escape_list
1111 result = urllib.parse.unquote(escape_string)
1112 self.assertEqual(result.count('%'), 1,
1113 "using unquote(): not all characters escaped: "
1114 "%s" % result)
1115 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, None)
1116 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote, ())
1117
1118 def test_unquoting_badpercent(self):
1119 # Test unquoting on bad percent-escapes
1120 given = '%xab'
1121 expect = given
1122 result = urllib.parse.unquote(given)
1123 self.assertEqual(expect, result, "using unquote(): %r != %r"
1124 % (expect, result))
1125 given = '%x'
1126 expect = given
1127 result = urllib.parse.unquote(given)
1128 self.assertEqual(expect, result, "using unquote(): %r != %r"
1129 % (expect, result))
1130 given = '%'
1131 expect = given
1132 result = urllib.parse.unquote(given)
1133 self.assertEqual(expect, result, "using unquote(): %r != %r"
1134 % (expect, result))
1135 # unquote_to_bytes
1136 given = '%xab'
1137 expect = bytes(given, 'ascii')
1138 result = urllib.parse.unquote_to_bytes(given)
1139 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
1140 % (expect, result))
1141 given = '%x'
1142 expect = bytes(given, 'ascii')
1143 result = urllib.parse.unquote_to_bytes(given)
1144 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
1145 % (expect, result))
1146 given = '%'
1147 expect = bytes(given, 'ascii')
1148 result = urllib.parse.unquote_to_bytes(given)
1149 self.assertEqual(expect, result, "using unquote_to_bytes(): %r != %r"
1150 % (expect, result))
1151 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, None)
1152 self.assertRaises((TypeError, AttributeError), urllib.parse.unquote_to_bytes, ())
1153
1154 def test_unquoting_mixed_case(self):
1155 # Test unquoting on mixed-case hex digits in the percent-escapes
1156 given = '%Ab%eA'
1157 expect = b'\xab\xea'
1158 result = urllib.parse.unquote_to_bytes(given)
1159 self.assertEqual(expect, result,
1160 "using unquote_to_bytes(): %r != %r"
1161 % (expect, result))
1162
1163 def test_unquoting_parts(self):
1164 # Make sure unquoting works when have non-quoted characters
1165 # interspersed
1166 given = 'ab%sd' % hexescape('c')
1167 expect = "abcd"
1168 result = urllib.parse.unquote(given)
1169 self.assertEqual(expect, result,
1170 "using quote(): %r != %r" % (expect, result))
1171 result = urllib.parse.unquote_plus(given)
1172 self.assertEqual(expect, result,
1173 "using unquote_plus(): %r != %r" % (expect, result))
1174
1175 def test_unquoting_plus(self):
1176 # Test difference between unquote() and unquote_plus()
1177 given = "are+there+spaces..."
1178 expect = given
1179 result = urllib.parse.unquote(given)
1180 self.assertEqual(expect, result,
1181 "using unquote(): %r != %r" % (expect, result))
1182 expect = given.replace('+', ' ')
1183 result = urllib.parse.unquote_plus(given)
1184 self.assertEqual(expect, result,
1185 "using unquote_plus(): %r != %r" % (expect, result))
1186
1187 def test_unquote_to_bytes(self):
1188 given = 'br%C3%BCckner_sapporo_20050930.doc'
1189 expect = b'br\xc3\xbcckner_sapporo_20050930.doc'
1190 result = urllib.parse.unquote_to_bytes(given)
1191 self.assertEqual(expect, result,
1192 "using unquote_to_bytes(): %r != %r"
1193 % (expect, result))
1194 # Test on a string with unescaped non-ASCII characters
1195 # (Technically an invalid URI; expect those characters to be UTF-8
1196 # encoded).
1197 result = urllib.parse.unquote_to_bytes("\u6f22%C3%BC")
1198 expect = b'\xe6\xbc\xa2\xc3\xbc' # UTF-8 for "\u6f22\u00fc"
1199 self.assertEqual(expect, result,
1200 "using unquote_to_bytes(): %r != %r"
1201 % (expect, result))
1202 # Test with a bytes as input
1203 given = b'%A2%D8ab%FF'
1204 expect = b'\xa2\xd8ab\xff'
1205 result = urllib.parse.unquote_to_bytes(given)
1206 self.assertEqual(expect, result,
1207 "using unquote_to_bytes(): %r != %r"
1208 % (expect, result))
1209 # Test with a bytes as input, with unescaped non-ASCII bytes
1210 # (Technically an invalid URI; expect those bytes to be preserved)
1211 given = b'%A2\xd8ab%FF'
1212 expect = b'\xa2\xd8ab\xff'
1213 result = urllib.parse.unquote_to_bytes(given)
1214 self.assertEqual(expect, result,
1215 "using unquote_to_bytes(): %r != %r"
1216 % (expect, result))
1217
1218 def test_unquote_with_unicode(self):
1219 # Characters in the Latin-1 range, encoded with UTF-8
1220 given = 'br%C3%BCckner_sapporo_20050930.doc'
1221 expect = 'br\u00fcckner_sapporo_20050930.doc'
1222 result = urllib.parse.unquote(given)
1223 self.assertEqual(expect, result,
1224 "using unquote(): %r != %r" % (expect, result))
1225 # Characters in the Latin-1 range, encoded with None (default)
1226 result = urllib.parse.unquote(given, encoding=None, errors=None)
1227 self.assertEqual(expect, result,
1228 "using unquote(): %r != %r" % (expect, result))
1229
1230 # Characters in the Latin-1 range, encoded with Latin-1
1231 result = urllib.parse.unquote('br%FCckner_sapporo_20050930.doc',
1232 encoding="latin-1")
1233 expect = 'br\u00fcckner_sapporo_20050930.doc'
1234 self.assertEqual(expect, result,
1235 "using unquote(): %r != %r" % (expect, result))
1236
1237 # Characters in BMP, encoded with UTF-8
1238 given = "%E6%BC%A2%E5%AD%97"
1239 expect = "\u6f22\u5b57" # "Kanji"
1240 result = urllib.parse.unquote(given)
1241 self.assertEqual(expect, result,
1242 "using unquote(): %r != %r" % (expect, result))
1243
1244 # Decode with UTF-8, invalid sequence
1245 given = "%F3%B1"
1246 expect = "\ufffd" # Replacement character
1247 result = urllib.parse.unquote(given)
1248 self.assertEqual(expect, result,
1249 "using unquote(): %r != %r" % (expect, result))
1250
1251 # Decode with UTF-8, invalid sequence, replace errors
1252 result = urllib.parse.unquote(given, errors="replace")
1253 self.assertEqual(expect, result,
1254 "using unquote(): %r != %r" % (expect, result))
1255
1256 # Decode with UTF-8, invalid sequence, ignoring errors
1257 given = "%F3%B1"
1258 expect = ""
1259 result = urllib.parse.unquote(given, errors="ignore")
1260 self.assertEqual(expect, result,
1261 "using unquote(): %r != %r" % (expect, result))
1262
1263 # A mix of non-ASCII and percent-encoded characters, UTF-8
1264 result = urllib.parse.unquote("\u6f22%C3%BC")
1265 expect = '\u6f22\u00fc'
1266 self.assertEqual(expect, result,
1267 "using unquote(): %r != %r" % (expect, result))
1268
1269 # A mix of non-ASCII and percent-encoded characters, Latin-1
1270 # (Note, the string contains non-Latin-1-representable characters)
1271 result = urllib.parse.unquote("\u6f22%FC", encoding="latin-1")
1272 expect = '\u6f22\u00fc'
1273 self.assertEqual(expect, result,
1274 "using unquote(): %r != %r" % (expect, result))
1275
1276 def test_unquoting_with_bytes_input(self):
1277 # ASCII characters decoded to a string
1278 given = b'blueberryjam'
1279 expect = 'blueberryjam'
1280 result = urllib.parse.unquote(given)
1281 self.assertEqual(expect, result,
1282 "using unquote(): %r != %r" % (expect, result))
1283
1284 # A mix of non-ASCII hex-encoded characters and ASCII characters
1285 given = b'bl\xc3\xa5b\xc3\xa6rsyltet\xc3\xb8y'
1286 expect = 'bl\u00e5b\u00e6rsyltet\u00f8y'
1287 result = urllib.parse.unquote(given)
1288 self.assertEqual(expect, result,
1289 "using unquote(): %r != %r" % (expect, result))
1290
1291 # A mix of non-ASCII percent-encoded characters and ASCII characters
1292 given = b'bl%c3%a5b%c3%a6rsyltet%c3%b8j'
1293 expect = 'bl\u00e5b\u00e6rsyltet\u00f8j'
1294 result = urllib.parse.unquote(given)
1295 self.assertEqual(expect, result,
1296 "using unquote(): %r != %r" % (expect, result))
1297
1298
1299 class urlencode_Tests(unittest.TestCase):
1300 """Tests for urlencode()"""
1301
1302 def help_inputtype(self, given, test_type):
1303 """Helper method for testing different input types.
1304
1305 'given' must lead to only the pairs:
1306 * 1st, 1
1307 * 2nd, 2
1308 * 3rd, 3
1309
1310 Test cannot assume anything about order. Docs make no guarantee and
1311 have possible dictionary input.
1312
1313 """
1314 expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
1315 result = urllib.parse.urlencode(given)
1316 for expected in expect_somewhere:
1317 self.assertIn(expected, result,
1318 "testing %s: %s not found in %s" %
1319 (test_type, expected, result))
1320 self.assertEqual(result.count('&'), 2,
1321 "testing %s: expected 2 '&'s; got %s" %
1322 (test_type, result.count('&')))
1323 amp_location = result.index('&')
1324 on_amp_left = result[amp_location - 1]
1325 on_amp_right = result[amp_location + 1]
1326 self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
1327 "testing %s: '&' not located in proper place in %s" %
1328 (test_type, result))
1329 self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
1330 "testing %s: "
1331 "unexpected number of characters: %s != %s" %
1332 (test_type, len(result), (5 * 3) + 2))
1333
1334 def test_using_mapping(self):
1335 # Test passing in a mapping object as an argument.
1336 self.help_inputtype({"1st":'1', "2nd":'2', "3rd":'3'},
1337 "using dict as input type")
1338
1339 def test_using_sequence(self):
1340 # Test passing in a sequence of two-item sequences as an argument.
1341 self.help_inputtype([('1st', '1'), ('2nd', '2'), ('3rd', '3')],
1342 "using sequence of two-item tuples as input")
1343
1344 def test_quoting(self):
1345 # Make sure keys and values are quoted using quote_plus()
1346 given = {"&":"="}
1347 expect = "%s=%s" % (hexescape('&'), hexescape('='))
1348 result = urllib.parse.urlencode(given)
1349 self.assertEqual(expect, result)
1350 given = {"key name":"A bunch of pluses"}
1351 expect = "key+name=A+bunch+of+pluses"
1352 result = urllib.parse.urlencode(given)
1353 self.assertEqual(expect, result)
1354
1355 def test_doseq(self):
1356 # Test that passing True for 'doseq' parameter works correctly
1357 given = {'sequence':['1', '2', '3']}
1358 expect = "sequence=%s" % urllib.parse.quote_plus(str(['1', '2', '3']))
1359 result = urllib.parse.urlencode(given)
1360 self.assertEqual(expect, result)
1361 result = urllib.parse.urlencode(given, True)
1362 for value in given["sequence"]:
1363 expect = "sequence=%s" % value
1364 self.assertIn(expect, result)
1365 self.assertEqual(result.count('&'), 2,
1366 "Expected 2 '&'s, got %s" % result.count('&'))
1367
1368 def test_empty_sequence(self):
1369 self.assertEqual("", urllib.parse.urlencode({}))
1370 self.assertEqual("", urllib.parse.urlencode([]))
1371
1372 def test_nonstring_values(self):
1373 self.assertEqual("a=1", urllib.parse.urlencode({"a": 1}))
1374 self.assertEqual("a=None", urllib.parse.urlencode({"a": None}))
1375
1376 def test_nonstring_seq_values(self):
1377 self.assertEqual("a=1&a=2", urllib.parse.urlencode({"a": [1, 2]}, True))
1378 self.assertEqual("a=None&a=a",
1379 urllib.parse.urlencode({"a": [None, "a"]}, True))
1380 data = collections.OrderedDict([("a", 1), ("b", 1)])
1381 self.assertEqual("a=a&a=b",
1382 urllib.parse.urlencode({"a": data}, True))
1383
1384 def test_urlencode_encoding(self):
1385 # ASCII encoding. Expect %3F with errors="replace'
1386 given = (('\u00a0', '\u00c1'),)
1387 expect = '%3F=%3F'
1388 result = urllib.parse.urlencode(given, encoding="ASCII", errors="replace")
1389 self.assertEqual(expect, result)
1390
1391 # Default is UTF-8 encoding.
1392 given = (('\u00a0', '\u00c1'),)
1393 expect = '%C2%A0=%C3%81'
1394 result = urllib.parse.urlencode(given)
1395 self.assertEqual(expect, result)
1396
1397 # Latin-1 encoding.
1398 given = (('\u00a0', '\u00c1'),)
1399 expect = '%A0=%C1'
1400 result = urllib.parse.urlencode(given, encoding="latin-1")
1401 self.assertEqual(expect, result)
1402
1403 def test_urlencode_encoding_doseq(self):
1404 # ASCII Encoding. Expect %3F with errors="replace'
1405 given = (('\u00a0', '\u00c1'),)
1406 expect = '%3F=%3F'
1407 result = urllib.parse.urlencode(given, doseq=True,
1408 encoding="ASCII", errors="replace")
1409 self.assertEqual(expect, result)
1410
1411 # ASCII Encoding. On a sequence of values.
1412 given = (("\u00a0", (1, "\u00c1")),)
1413 expect = '%3F=1&%3F=%3F'
1414 result = urllib.parse.urlencode(given, True,
1415 encoding="ASCII", errors="replace")
1416 self.assertEqual(expect, result)
1417
1418 # Utf-8
1419 given = (("\u00a0", "\u00c1"),)
1420 expect = '%C2%A0=%C3%81'
1421 result = urllib.parse.urlencode(given, True)
1422 self.assertEqual(expect, result)
1423
1424 given = (("\u00a0", (42, "\u00c1")),)
1425 expect = '%C2%A0=42&%C2%A0=%C3%81'
1426 result = urllib.parse.urlencode(given, True)
1427 self.assertEqual(expect, result)
1428
1429 # latin-1
1430 given = (("\u00a0", "\u00c1"),)
1431 expect = '%A0=%C1'
1432 result = urllib.parse.urlencode(given, True, encoding="latin-1")
1433 self.assertEqual(expect, result)
1434
1435 given = (("\u00a0", (42, "\u00c1")),)
1436 expect = '%A0=42&%A0=%C1'
1437 result = urllib.parse.urlencode(given, True, encoding="latin-1")
1438 self.assertEqual(expect, result)
1439
1440 def test_urlencode_bytes(self):
1441 given = ((b'\xa0\x24', b'\xc1\x24'),)
1442 expect = '%A0%24=%C1%24'
1443 result = urllib.parse.urlencode(given)
1444 self.assertEqual(expect, result)
1445 result = urllib.parse.urlencode(given, True)
1446 self.assertEqual(expect, result)
1447
1448 # Sequence of values
1449 given = ((b'\xa0\x24', (42, b'\xc1\x24')),)
1450 expect = '%A0%24=42&%A0%24=%C1%24'
1451 result = urllib.parse.urlencode(given, True)
1452 self.assertEqual(expect, result)
1453
1454 def test_urlencode_encoding_safe_parameter(self):
1455
1456 # Send '$' (\x24) as safe character
1457 # Default utf-8 encoding
1458
1459 given = ((b'\xa0\x24', b'\xc1\x24'),)
1460 result = urllib.parse.urlencode(given, safe=":$")
1461 expect = '%A0$=%C1$'
1462 self.assertEqual(expect, result)
1463
1464 given = ((b'\xa0\x24', b'\xc1\x24'),)
1465 result = urllib.parse.urlencode(given, doseq=True, safe=":$")
1466 expect = '%A0$=%C1$'
1467 self.assertEqual(expect, result)
1468
1469 # Safe parameter in sequence
1470 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
1471 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
1472 result = urllib.parse.urlencode(given, True, safe=":$")
1473 self.assertEqual(expect, result)
1474
1475 # Test all above in latin-1 encoding
1476
1477 given = ((b'\xa0\x24', b'\xc1\x24'),)
1478 result = urllib.parse.urlencode(given, safe=":$",
1479 encoding="latin-1")
1480 expect = '%A0$=%C1$'
1481 self.assertEqual(expect, result)
1482
1483 given = ((b'\xa0\x24', b'\xc1\x24'),)
1484 expect = '%A0$=%C1$'
1485 result = urllib.parse.urlencode(given, doseq=True, safe=":$",
1486 encoding="latin-1")
1487
1488 given = ((b'\xa0\x24', (b'\xc1\x24', 0xd, 42)),)
1489 expect = '%A0$=%C1$&%A0$=13&%A0$=42'
1490 result = urllib.parse.urlencode(given, True, safe=":$",
1491 encoding="latin-1")
1492 self.assertEqual(expect, result)
1493
1494 class Pathname_Tests(unittest.TestCase):
1495 """Test pathname2url() and url2pathname()"""
1496
1497 def test_basic(self):
1498 # Make sure simple tests pass
1499 expected_path = os.path.join("parts", "of", "a", "path")
1500 expected_url = "parts/of/a/path"
1501 result = urllib.request.pathname2url(expected_path)
1502 self.assertEqual(expected_url, result,
1503 "pathname2url() failed; %s != %s" %
1504 (result, expected_url))
1505 result = urllib.request.url2pathname(expected_url)
1506 self.assertEqual(expected_path, result,
1507 "url2pathame() failed; %s != %s" %
1508 (result, expected_path))
1509
1510 def test_quoting(self):
1511 # Test automatic quoting and unquoting works for pathnam2url() and
1512 # url2pathname() respectively
1513 given = os.path.join("needs", "quot=ing", "here")
1514 expect = "needs/%s/here" % urllib.parse.quote("quot=ing")
1515 result = urllib.request.pathname2url(given)
1516 self.assertEqual(expect, result,
1517 "pathname2url() failed; %s != %s" %
1518 (expect, result))
1519 expect = given
1520 result = urllib.request.url2pathname(result)
1521 self.assertEqual(expect, result,
1522 "url2pathname() failed; %s != %s" %
1523 (expect, result))
1524 given = os.path.join("make sure", "using_quote")
1525 expect = "%s/using_quote" % urllib.parse.quote("make sure")
1526 result = urllib.request.pathname2url(given)
1527 self.assertEqual(expect, result,
1528 "pathname2url() failed; %s != %s" %
1529 (expect, result))
1530 given = "make+sure/using_unquote"
1531 expect = os.path.join("make+sure", "using_unquote")
1532 result = urllib.request.url2pathname(given)
1533 self.assertEqual(expect, result,
1534 "url2pathname() failed; %s != %s" %
1535 (expect, result))
1536
1537 @unittest.skipUnless(sys.platform == 'win32',
1538 'test specific to the nturl2path functions.')
1539 def test_prefixes(self):
1540 # Test special prefixes are correctly handled in pathname2url()
1541 given = '\\\\?\\C:\\dir'
1542 expect = '///C:/dir'
1543 result = urllib.request.pathname2url(given)
1544 self.assertEqual(expect, result,
1545 "pathname2url() failed; %s != %s" %
1546 (expect, result))
1547 given = '\\\\?\\unc\\server\\share\\dir'
1548 expect = '/server/share/dir'
1549 result = urllib.request.pathname2url(given)
1550 self.assertEqual(expect, result,
1551 "pathname2url() failed; %s != %s" %
1552 (expect, result))
1553
1554
1555 @unittest.skipUnless(sys.platform == 'win32',
1556 'test specific to the urllib.url2path function.')
1557 def test_ntpath(self):
1558 given = ('/C:/', '///C:/', '/C|//')
1559 expect = 'C:\\'
1560 for url in given:
1561 result = urllib.request.url2pathname(url)
1562 self.assertEqual(expect, result,
1563 'urllib.request..url2pathname() failed; %s != %s' %
1564 (expect, result))
1565 given = '///C|/path'
1566 expect = 'C:\\path'
1567 result = urllib.request.url2pathname(given)
1568 self.assertEqual(expect, result,
1569 'urllib.request.url2pathname() failed; %s != %s' %
1570 (expect, result))
1571
1572 class Utility_Tests(unittest.TestCase):
1573 """Testcase to test the various utility functions in the urllib."""
1574
1575 def test_thishost(self):
1576 """Test the urllib.request.thishost utility function returns a tuple"""
1577 self.assertIsInstance(urllib.request.thishost(), tuple)
1578
1579
1580 class URLopener_Tests(FakeHTTPMixin, unittest.TestCase):
1581 """Testcase to test the open method of URLopener class."""
1582
1583 def test_quoted_open(self):
1584 class DummyURLopener(urllib.request.URLopener):
1585 def open_spam(self, url):
1586 return url
1587 with warnings_helper.check_warnings(
1588 ('DummyURLopener style of invoking requests is deprecated.',
1589 DeprecationWarning)):
1590 self.assertEqual(DummyURLopener().open(
1591 'spam://example/ /'),'//example/%20/')
1592
1593 # test the safe characters are not quoted by urlopen
1594 self.assertEqual(DummyURLopener().open(
1595 "spam://c:|windows%/:=&?~#+!$,;'@()*[]|/path/"),
1596 "//c:|windows%/:=&?~#+!$,;'@()*[]|/path/")
1597
1598 @warnings_helper.ignore_warnings(category=DeprecationWarning)
1599 def test_urlopener_retrieve_file(self):
1600 with os_helper.temp_dir() as tmpdir:
1601 fd, tmpfile = tempfile.mkstemp(dir=tmpdir)
1602 os.close(fd)
1603 fileurl = "file:" + urllib.request.pathname2url(tmpfile)
1604 filename, _ = urllib.request.URLopener().retrieve(fileurl)
1605 # Some buildbots have TEMP folder that uses a lowercase drive letter.
1606 self.assertEqual(os.path.normcase(filename), os.path.normcase(tmpfile))
1607
1608 @warnings_helper.ignore_warnings(category=DeprecationWarning)
1609 def test_urlopener_retrieve_remote(self):
1610 url = "http://www.python.org/file.txt"
1611 self.fakehttp(b"HTTP/1.1 200 OK\r\n\r\nHello!")
1612 self.addCleanup(self.unfakehttp)
1613 filename, _ = urllib.request.URLopener().retrieve(url)
1614 self.assertEqual(os.path.splitext(filename)[1], ".txt")
1615
1616 @warnings_helper.ignore_warnings(category=DeprecationWarning)
1617 def test_local_file_open(self):
1618 # bpo-35907, CVE-2019-9948: urllib must reject local_file:// scheme
1619 class DummyURLopener(urllib.request.URLopener):
1620 def open_local_file(self, url):
1621 return url
1622 for url in ('local_file://example', 'local-file://example'):
1623 self.assertRaises(OSError, urllib.request.urlopen, url)
1624 self.assertRaises(OSError, urllib.request.URLopener().open, url)
1625 self.assertRaises(OSError, urllib.request.URLopener().retrieve, url)
1626 self.assertRaises(OSError, DummyURLopener().open, url)
1627 self.assertRaises(OSError, DummyURLopener().retrieve, url)
1628
1629
1630 class RequestTests(unittest.TestCase):
1631 """Unit tests for urllib.request.Request."""
1632
1633 def test_default_values(self):
1634 Request = urllib.request.Request
1635 request = Request("http://www.python.org")
1636 self.assertEqual(request.get_method(), 'GET')
1637 request = Request("http://www.python.org", {})
1638 self.assertEqual(request.get_method(), 'POST')
1639
1640 def test_with_method_arg(self):
1641 Request = urllib.request.Request
1642 request = Request("http://www.python.org", method='HEAD')
1643 self.assertEqual(request.method, 'HEAD')
1644 self.assertEqual(request.get_method(), 'HEAD')
1645 request = Request("http://www.python.org", {}, method='HEAD')
1646 self.assertEqual(request.method, 'HEAD')
1647 self.assertEqual(request.get_method(), 'HEAD')
1648 request = Request("http://www.python.org", method='GET')
1649 self.assertEqual(request.get_method(), 'GET')
1650 request.method = 'HEAD'
1651 self.assertEqual(request.get_method(), 'HEAD')
1652
1653
1654 class URL2PathNameTests(unittest.TestCase):
1655
1656 def test_converting_drive_letter(self):
1657 self.assertEqual(url2pathname("///C|"), 'C:')
1658 self.assertEqual(url2pathname("///C:"), 'C:')
1659 self.assertEqual(url2pathname("///C|/"), 'C:\\')
1660
1661 def test_converting_when_no_drive_letter(self):
1662 # cannot end a raw string in \
1663 self.assertEqual(url2pathname("///C/test/"), r'\\\C\test' '\\')
1664 self.assertEqual(url2pathname("////C/test/"), r'\\C\test' '\\')
1665
1666 def test_simple_compare(self):
1667 self.assertEqual(url2pathname("///C|/foo/bar/spam.foo"),
1668 r'C:\foo\bar\spam.foo')
1669
1670 def test_non_ascii_drive_letter(self):
1671 self.assertRaises(IOError, url2pathname, "///\u00e8|/")
1672
1673 def test_roundtrip_url2pathname(self):
1674 list_of_paths = ['C:',
1675 r'\\\C\test\\',
1676 r'C:\foo\bar\spam.foo'
1677 ]
1678 for path in list_of_paths:
1679 self.assertEqual(url2pathname(pathname2url(path)), path)
1680
1681 class PathName2URLTests(unittest.TestCase):
1682
1683 def test_converting_drive_letter(self):
1684 self.assertEqual(pathname2url("C:"), '///C:')
1685 self.assertEqual(pathname2url("C:\\"), '///C:')
1686
1687 def test_converting_when_no_drive_letter(self):
1688 self.assertEqual(pathname2url(r"\\\folder\test" "\\"),
1689 '/////folder/test/')
1690 self.assertEqual(pathname2url(r"\\folder\test" "\\"),
1691 '////folder/test/')
1692 self.assertEqual(pathname2url(r"\folder\test" "\\"),
1693 '/folder/test/')
1694
1695 def test_simple_compare(self):
1696 self.assertEqual(pathname2url(r'C:\foo\bar\spam.foo'),
1697 "///C:/foo/bar/spam.foo" )
1698
1699 def test_long_drive_letter(self):
1700 self.assertRaises(IOError, pathname2url, "XX:\\")
1701
1702 def test_roundtrip_pathname2url(self):
1703 list_of_paths = ['///C:',
1704 '/////folder/test/',
1705 '///C:/foo/bar/spam.foo']
1706 for path in list_of_paths:
1707 self.assertEqual(pathname2url(url2pathname(path)), path)
1708
1709 if __name__ == '__main__':
1710 unittest.main()