Debian Codegraph @

Lib/test/test_urllib.py

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