Debian Codegraph @

Lib/test/test_urlparse.py

raw
1 import sys
2 import unicodedata
3 import unittest
4 import urllib.parse
5 from test import support
6 from test.support.testcase import ExtraAssertions
7
8 RFC1808_BASE = "http://a/b/c/d;p?q#f"
9 RFC2396_BASE = "http://a/b/c/d;p?q"
10 RFC3986_BASE = 'http://a/b/c/d;p?q'
11 SIMPLE_BASE = 'http://a/b/c/d'
12
13 # Each parse_qsl testcase is a two-tuple that contains
14 # a string with the query and a list with the expected result.
15
16 parse_qsl_test_cases = [
17 ("", []),
18 ("&", []),
19 ("&&", []),
20 ("=", [('', '')]),
21 ("=a", [('', 'a')]),
22 ("a", [('a', '')]),
23 ("a=", [('a', '')]),
24 ("a=b=c", [('a', 'b=c')]),
25 ("a%3Db=c", [('a=b', 'c')]),
26 ("a=b&c=d", [('a', 'b'), ('c', 'd')]),
27 ("a=b%26c=d", [('a', 'b&c=d')]),
28 ("&a=b", [('a', 'b')]),
29 ("a=a+b&b=b+c", [('a', 'a b'), ('b', 'b c')]),
30 ("a=1&a=2", [('a', '1'), ('a', '2')]),
31 (b"", []),
32 (b"&", []),
33 (b"&&", []),
34 (b"=", [(b'', b'')]),
35 (b"=a", [(b'', b'a')]),
36 (b"a", [(b'a', b'')]),
37 (b"a=", [(b'a', b'')]),
38 (b"a=b=c", [(b'a', b'b=c')]),
39 (b"a%3Db=c", [(b'a=b', b'c')]),
40 (b"a=b&c=d", [(b'a', b'b'), (b'c', b'd')]),
41 (b"a=b%26c=d", [(b'a', b'b&c=d')]),
42 (b"&a=b", [(b'a', b'b')]),
43 (b"a=a+b&b=b+c", [(b'a', b'a b'), (b'b', b'b c')]),
44 (b"a=1&a=2", [(b'a', b'1'), (b'a', b'2')]),
45 (";a=b", [(';a', 'b')]),
46 ("a=a+b;b=b+c", [('a', 'a b;b=b c')]),
47 (b";a=b", [(b';a', b'b')]),
48 (b"a=a+b;b=b+c", [(b'a', b'a b;b=b c')]),
49
50 ("\u0141=\xE9", [('\u0141', '\xE9')]),
51 ("%C5%81=%C3%A9", [('\u0141', '\xE9')]),
52 ("%81=%A9", [('\ufffd', '\ufffd')]),
53 (b"\xc5\x81=\xc3\xa9", [(b'\xc5\x81', b'\xc3\xa9')]),
54 (b"%C5%81=%C3%A9", [(b'\xc5\x81', b'\xc3\xa9')]),
55 (b"\x81=\xA9", [(b'\x81', b'\xa9')]),
56 (b"%81=%A9", [(b'\x81', b'\xa9')]),
57 ]
58
59 # Each parse_qs testcase is a two-tuple that contains
60 # a string with the query and a dictionary with the expected result.
61
62 parse_qs_test_cases = [
63 ("", {}),
64 ("&", {}),
65 ("&&", {}),
66 ("=", {'': ['']}),
67 ("=a", {'': ['a']}),
68 ("a", {'a': ['']}),
69 ("a=", {'a': ['']}),
70 ("a=b=c", {'a': ['b=c']}),
71 ("a%3Db=c", {'a=b': ['c']}),
72 ("a=b&c=d", {'a': ['b'], 'c': ['d']}),
73 ("a=b%26c=d", {'a': ['b&c=d']}),
74 ("&a=b", {'a': ['b']}),
75 ("a=a+b&b=b+c", {'a': ['a b'], 'b': ['b c']}),
76 ("a=1&a=2", {'a': ['1', '2']}),
77 (b"", {}),
78 (b"&", {}),
79 (b"&&", {}),
80 (b"=", {b'': [b'']}),
81 (b"=a", {b'': [b'a']}),
82 (b"a", {b'a': [b'']}),
83 (b"a=", {b'a': [b'']}),
84 (b"a=b=c", {b'a': [b'b=c']}),
85 (b"a%3Db=c", {b'a=b': [b'c']}),
86 (b"a=b&c=d", {b'a': [b'b'], b'c': [b'd']}),
87 (b"a=b%26c=d", {b'a': [b'b&c=d']}),
88 (b"&a=b", {b'a': [b'b']}),
89 (b"a=a+b&b=b+c", {b'a': [b'a b'], b'b': [b'b c']}),
90 (b"a=1&a=2", {b'a': [b'1', b'2']}),
91 (";a=b", {';a': ['b']}),
92 ("a=a+b;b=b+c", {'a': ['a b;b=b c']}),
93 (b";a=b", {b';a': [b'b']}),
94 (b"a=a+b;b=b+c", {b'a':[ b'a b;b=b c']}),
95 (b"a=a%E2%80%99b", {b'a': [b'a\xe2\x80\x99b']}),
96
97 ("\u0141=\xE9", {'\u0141': ['\xE9']}),
98 ("%C5%81=%C3%A9", {'\u0141': ['\xE9']}),
99 ("%81=%A9", {'\ufffd': ['\ufffd']}),
100 (b"\xc5\x81=\xc3\xa9", {b'\xc5\x81': [b'\xc3\xa9']}),
101 (b"%C5%81=%C3%A9", {b'\xc5\x81': [b'\xc3\xa9']}),
102 (b"\x81=\xA9", {b'\x81': [b'\xa9']}),
103 (b"%81=%A9", {b'\x81': [b'\xa9']}),
104 ]
105
106 class UrlParseTestCase(unittest.TestCase, ExtraAssertions):
107
108 def checkRoundtrips(self, url, parsed, split, url2=None):
109 if url2 is None:
110 url2 = url
111 result = urllib.parse.urlparse(url)
112 self.assertSequenceEqual(result, parsed)
113 t = (result.scheme, result.netloc, result.path,
114 result.params, result.query, result.fragment)
115 self.assertSequenceEqual(t, parsed)
116 # put it back together and it should be the same
117 result2 = urllib.parse.urlunparse(result)
118 self.assertSequenceEqual(result2, url2)
119 self.assertSequenceEqual(result2, result.geturl())
120
121 # the result of geturl() is a fixpoint; we can always parse it
122 # again to get the same result:
123 result3 = urllib.parse.urlparse(result.geturl())
124 self.assertEqual(result3.geturl(), result.geturl())
125 self.assertSequenceEqual(result3, result)
126 self.assertEqual(result3.scheme, result.scheme)
127 self.assertEqual(result3.netloc, result.netloc)
128 self.assertEqual(result3.path, result.path)
129 self.assertEqual(result3.params, result.params)
130 self.assertEqual(result3.query, result.query)
131 self.assertEqual(result3.fragment, result.fragment)
132 self.assertEqual(result3.username, result.username)
133 self.assertEqual(result3.password, result.password)
134 self.assertEqual(result3.hostname, result.hostname)
135 self.assertEqual(result3.port, result.port)
136
137 # check the roundtrip using urlsplit() as well
138 result = urllib.parse.urlsplit(url)
139 self.assertSequenceEqual(result, split)
140 t = (result.scheme, result.netloc, result.path,
141 result.query, result.fragment)
142 self.assertSequenceEqual(t, split)
143 result2 = urllib.parse.urlunsplit(result)
144 self.assertSequenceEqual(result2, url2)
145 self.assertSequenceEqual(result2, result.geturl())
146
147 # check the fixpoint property of re-parsing the result of geturl()
148 result3 = urllib.parse.urlsplit(result.geturl())
149 self.assertEqual(result3.geturl(), result.geturl())
150 self.assertSequenceEqual(result3, result)
151 self.assertEqual(result3.scheme, result.scheme)
152 self.assertEqual(result3.netloc, result.netloc)
153 self.assertEqual(result3.path, result.path)
154 self.assertEqual(result3.query, result.query)
155 self.assertEqual(result3.fragment, result.fragment)
156 self.assertEqual(result3.username, result.username)
157 self.assertEqual(result3.password, result.password)
158 self.assertEqual(result3.hostname, result.hostname)
159 self.assertEqual(result3.port, result.port)
160
161 @support.subTests('orig,expect', parse_qsl_test_cases)
162 def test_qsl(self, orig, expect):
163 result = urllib.parse.parse_qsl(orig, keep_blank_values=True)
164 self.assertEqual(result, expect)
165 expect_without_blanks = [v for v in expect if len(v[1])]
166 result = urllib.parse.parse_qsl(orig, keep_blank_values=False)
167 self.assertEqual(result, expect_without_blanks)
168
169 @support.subTests('orig,expect', parse_qs_test_cases)
170 def test_qs(self, orig, expect):
171 result = urllib.parse.parse_qs(orig, keep_blank_values=True)
172 self.assertEqual(result, expect)
173 expect_without_blanks = {v: expect[v]
174 for v in expect if len(expect[v][0])}
175 result = urllib.parse.parse_qs(orig, keep_blank_values=False)
176 self.assertEqual(result, expect_without_blanks)
177
178 @support.subTests('bytes', (False, True))
179 @support.subTests('url,parsed,split', [
180 ('path/to/file',
181 ('', '', 'path/to/file', '', '', ''),
182 ('', '', 'path/to/file', '', '')),
183 ('/path/to/file',
184 ('', '', '/path/to/file', '', '', ''),
185 ('', '', '/path/to/file', '', '')),
186 ('//path/to/file',
187 ('', 'path', '/to/file', '', '', ''),
188 ('', 'path', '/to/file', '', '')),
189 ('////path/to/file',
190 ('', '', '//path/to/file', '', '', ''),
191 ('', '', '//path/to/file', '', '')),
192 ('/////path/to/file',
193 ('', '', '///path/to/file', '', '', ''),
194 ('', '', '///path/to/file', '', '')),
195 ('scheme:path/to/file',
196 ('scheme', '', 'path/to/file', '', '', ''),
197 ('scheme', '', 'path/to/file', '', '')),
198 ('scheme:/path/to/file',
199 ('scheme', '', '/path/to/file', '', '', ''),
200 ('scheme', '', '/path/to/file', '', '')),
201 ('scheme://path/to/file',
202 ('scheme', 'path', '/to/file', '', '', ''),
203 ('scheme', 'path', '/to/file', '', '')),
204 ('scheme:////path/to/file',
205 ('scheme', '', '//path/to/file', '', '', ''),
206 ('scheme', '', '//path/to/file', '', '')),
207 ('scheme://///path/to/file',
208 ('scheme', '', '///path/to/file', '', '', ''),
209 ('scheme', '', '///path/to/file', '', '')),
210 ('file:tmp/junk.txt',
211 ('file', '', 'tmp/junk.txt', '', '', ''),
212 ('file', '', 'tmp/junk.txt', '', '')),
213 ('file:///tmp/junk.txt',
214 ('file', '', '/tmp/junk.txt', '', '', ''),
215 ('file', '', '/tmp/junk.txt', '', '')),
216 ('file:////tmp/junk.txt',
217 ('file', '', '//tmp/junk.txt', '', '', ''),
218 ('file', '', '//tmp/junk.txt', '', '')),
219 ('file://///tmp/junk.txt',
220 ('file', '', '///tmp/junk.txt', '', '', ''),
221 ('file', '', '///tmp/junk.txt', '', '')),
222 ('http:tmp/junk.txt',
223 ('http', '', 'tmp/junk.txt', '', '', ''),
224 ('http', '', 'tmp/junk.txt', '', '')),
225 ('http://example.com/tmp/junk.txt',
226 ('http', 'example.com', '/tmp/junk.txt', '', '', ''),
227 ('http', 'example.com', '/tmp/junk.txt', '', '')),
228 ('http:///example.com/tmp/junk.txt',
229 ('http', '', '/example.com/tmp/junk.txt', '', '', ''),
230 ('http', '', '/example.com/tmp/junk.txt', '', '')),
231 ('http:////example.com/tmp/junk.txt',
232 ('http', '', '//example.com/tmp/junk.txt', '', '', ''),
233 ('http', '', '//example.com/tmp/junk.txt', '', '')),
234 ('imap://mail.python.org/mbox1',
235 ('imap', 'mail.python.org', '/mbox1', '', '', ''),
236 ('imap', 'mail.python.org', '/mbox1', '', '')),
237 ('mms://wms.sys.hinet.net/cts/Drama/09006251100.asf',
238 ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf',
239 '', '', ''),
240 ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf',
241 '', '')),
242 ('nfs://server/path/to/file.txt',
243 ('nfs', 'server', '/path/to/file.txt', '', '', ''),
244 ('nfs', 'server', '/path/to/file.txt', '', '')),
245 ('svn+ssh://svn.zope.org/repos/main/ZConfig/trunk/',
246 ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/',
247 '', '', ''),
248 ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/',
249 '', '')),
250 ('git+ssh://[email protected]/user/project.git',
251 ('git+ssh', '[email protected]','/user/project.git',
252 '','',''),
253 ('git+ssh', '[email protected]','/user/project.git',
254 '', '')),
255 ('itms-services://?action=download-manifest&url=https://example.com/app',
256 ('itms-services', '', '', '',
257 'action=download-manifest&url=https://example.com/app', ''),
258 ('itms-services', '', '',
259 'action=download-manifest&url=https://example.com/app', '')),
260 ('+scheme:path/to/file',
261 ('', '', '+scheme:path/to/file', '', '', ''),
262 ('', '', '+scheme:path/to/file', '', '')),
263 ('sch_me:path/to/file',
264 ('', '', 'sch_me:path/to/file', '', '', ''),
265 ('', '', 'sch_me:path/to/file', '', '')),
266 ('schème:path/to/file',
267 ('', '', 'schème:path/to/file', '', '', ''),
268 ('', '', 'schème:path/to/file', '', '')),
269 ])
270 def test_roundtrips(self, bytes, url, parsed, split):
271 if bytes:
272 if not url.isascii():
273 self.skipTest('non-ASCII bytes')
274 url = str_encode(url)
275 parsed = tuple_encode(parsed)
276 split = tuple_encode(split)
277 self.checkRoundtrips(url, parsed, split)
278
279 @support.subTests('bytes', (False, True))
280 @support.subTests('url,url2,parsed,split', [
281 ('///path/to/file',
282 '/path/to/file',
283 ('', '', '/path/to/file', '', '', ''),
284 ('', '', '/path/to/file', '', '')),
285 ('scheme:///path/to/file',
286 'scheme:/path/to/file',
287 ('scheme', '', '/path/to/file', '', '', ''),
288 ('scheme', '', '/path/to/file', '', '')),
289 ('file:/tmp/junk.txt',
290 'file:///tmp/junk.txt',
291 ('file', '', '/tmp/junk.txt', '', '', ''),
292 ('file', '', '/tmp/junk.txt', '', '')),
293 ('http:/tmp/junk.txt',
294 'http:///tmp/junk.txt',
295 ('http', '', '/tmp/junk.txt', '', '', ''),
296 ('http', '', '/tmp/junk.txt', '', '')),
297 ('https:/tmp/junk.txt',
298 'https:///tmp/junk.txt',
299 ('https', '', '/tmp/junk.txt', '', '', ''),
300 ('https', '', '/tmp/junk.txt', '', '')),
301 ])
302 def test_roundtrips_normalization(self, bytes, url, url2, parsed, split):
303 if bytes:
304 url = str_encode(url)
305 url2 = str_encode(url2)
306 parsed = tuple_encode(parsed)
307 split = tuple_encode(split)
308 self.checkRoundtrips(url, parsed, split, url2)
309
310 @support.subTests('bytes', (False, True))
311 @support.subTests('scheme', ('http', 'https'))
312 @support.subTests('url,parsed,split', [
313 ('://www.python.org',
314 ('www.python.org', '', '', '', ''),
315 ('www.python.org', '', '', '')),
316 ('://www.python.org#abc',
317 ('www.python.org', '', '', '', 'abc'),
318 ('www.python.org', '', '', 'abc')),
319 ('://www.python.org?q=abc',
320 ('www.python.org', '', '', 'q=abc', ''),
321 ('www.python.org', '', 'q=abc', '')),
322 ('://www.python.org/#abc',
323 ('www.python.org', '/', '', '', 'abc'),
324 ('www.python.org', '/', '', 'abc')),
325 ('://a/b/c/d;p?q#f',
326 ('a', '/b/c/d', 'p', 'q', 'f'),
327 ('a', '/b/c/d;p', 'q', 'f')),
328 ])
329 def test_http_roundtrips(self, bytes, scheme, url, parsed, split):
330 # urllib.parse.urlsplit treats 'http:' as an optimized special case,
331 # so we test both 'http:' and 'https:' in all the following.
332 # Three cheers for white box knowledge!
333 if bytes:
334 scheme = str_encode(scheme)
335 url = str_encode(url)
336 parsed = tuple_encode(parsed)
337 split = tuple_encode(split)
338 url = scheme + url
339 parsed = (scheme,) + parsed
340 split = (scheme,) + split
341 self.checkRoundtrips(url, parsed, split)
342
343 def checkJoin(self, base, relurl, expected):
344 with self.subTest(base=base, relurl=relurl):
345 self.assertEqual(urllib.parse.urljoin(base, relurl), expected)
346 baseb = base.encode('ascii')
347 relurlb = relurl.encode('ascii')
348 expectedb = expected.encode('ascii')
349 self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb)
350
351 relurl = urllib.parse.urlunsplit(urllib.parse.urlsplit(relurl))
352 self.assertEqual(urllib.parse.urljoin(base, relurl), expected)
353 relurlb = urllib.parse.urlunsplit(urllib.parse.urlsplit(relurlb))
354 self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb)
355
356 @support.subTests('bytes', (False, True))
357 @support.subTests('u', ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',])
358 def test_unparse_parse(self, bytes, u):
359 if bytes:
360 u = str_encode(u)
361 self.assertEqual(urllib.parse.urlunsplit(urllib.parse.urlsplit(u)), u)
362 self.assertEqual(urllib.parse.urlunparse(urllib.parse.urlparse(u)), u)
363
364 def test_RFC1808(self):
365 # "normal" cases from RFC 1808:
366 self.checkJoin(RFC1808_BASE, 'g:h', 'g:h')
367 self.checkJoin(RFC1808_BASE, 'g', 'http://a/b/c/g')
368 self.checkJoin(RFC1808_BASE, './g', 'http://a/b/c/g')
369 self.checkJoin(RFC1808_BASE, 'g/', 'http://a/b/c/g/')
370 self.checkJoin(RFC1808_BASE, '/g', 'http://a/g')
371 self.checkJoin(RFC1808_BASE, '//g', 'http://g')
372 self.checkJoin(RFC1808_BASE, 'g?y', 'http://a/b/c/g?y')
373 self.checkJoin(RFC1808_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x')
374 self.checkJoin(RFC1808_BASE, '#s', 'http://a/b/c/d;p?q#s')
375 self.checkJoin(RFC1808_BASE, 'g#s', 'http://a/b/c/g#s')
376 self.checkJoin(RFC1808_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x')
377 self.checkJoin(RFC1808_BASE, 'g?y#s', 'http://a/b/c/g?y#s')
378 self.checkJoin(RFC1808_BASE, 'g;x', 'http://a/b/c/g;x')
379 self.checkJoin(RFC1808_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s')
380 self.checkJoin(RFC1808_BASE, '.', 'http://a/b/c/')
381 self.checkJoin(RFC1808_BASE, './', 'http://a/b/c/')
382 self.checkJoin(RFC1808_BASE, '..', 'http://a/b/')
383 self.checkJoin(RFC1808_BASE, '../', 'http://a/b/')
384 self.checkJoin(RFC1808_BASE, '../g', 'http://a/b/g')
385 self.checkJoin(RFC1808_BASE, '../..', 'http://a/')
386 self.checkJoin(RFC1808_BASE, '../../', 'http://a/')
387 self.checkJoin(RFC1808_BASE, '../../g', 'http://a/g')
388
389 # "abnormal" cases from RFC 1808:
390 self.checkJoin(RFC1808_BASE, '', 'http://a/b/c/d;p?q#f')
391 self.checkJoin(RFC1808_BASE, 'g.', 'http://a/b/c/g.')
392 self.checkJoin(RFC1808_BASE, '.g', 'http://a/b/c/.g')
393 self.checkJoin(RFC1808_BASE, 'g..', 'http://a/b/c/g..')
394 self.checkJoin(RFC1808_BASE, '..g', 'http://a/b/c/..g')
395 self.checkJoin(RFC1808_BASE, './../g', 'http://a/b/g')
396 self.checkJoin(RFC1808_BASE, './g/.', 'http://a/b/c/g/')
397 self.checkJoin(RFC1808_BASE, 'g/./h', 'http://a/b/c/g/h')
398 self.checkJoin(RFC1808_BASE, 'g/../h', 'http://a/b/c/h')
399
400 # RFC 1808 and RFC 1630 disagree on these (according to RFC 1808),
401 # so we'll not actually run these tests (which expect 1808 behavior).
402 #self.checkJoin(RFC1808_BASE, 'http:g', 'http:g')
403 #self.checkJoin(RFC1808_BASE, 'http:', 'http:')
404
405 # XXX: The following tests are no longer compatible with RFC3986
406 # self.checkJoin(RFC1808_BASE, '../../../g', 'http://a/../g')
407 # self.checkJoin(RFC1808_BASE, '../../../../g', 'http://a/../../g')
408 # self.checkJoin(RFC1808_BASE, '/./g', 'http://a/./g')
409 # self.checkJoin(RFC1808_BASE, '/../g', 'http://a/../g')
410
411
412 def test_RFC2368(self):
413 # Issue 11467: path that starts with a number is not parsed correctly
414 self.assertEqual(urllib.parse.urlparse('mailto:[email protected]'),
415 ('mailto', '', '[email protected]', '', '', ''))
416
417 def test_RFC2396(self):
418 # cases from RFC 2396
419
420 self.checkJoin(RFC2396_BASE, 'g:h', 'g:h')
421 self.checkJoin(RFC2396_BASE, 'g', 'http://a/b/c/g')
422 self.checkJoin(RFC2396_BASE, './g', 'http://a/b/c/g')
423 self.checkJoin(RFC2396_BASE, 'g/', 'http://a/b/c/g/')
424 self.checkJoin(RFC2396_BASE, '/g', 'http://a/g')
425 self.checkJoin(RFC2396_BASE, '//g', 'http://g')
426 self.checkJoin(RFC2396_BASE, 'g?y', 'http://a/b/c/g?y')
427 self.checkJoin(RFC2396_BASE, '#s', 'http://a/b/c/d;p?q#s')
428 self.checkJoin(RFC2396_BASE, 'g#s', 'http://a/b/c/g#s')
429 self.checkJoin(RFC2396_BASE, 'g?y#s', 'http://a/b/c/g?y#s')
430 self.checkJoin(RFC2396_BASE, 'g;x', 'http://a/b/c/g;x')
431 self.checkJoin(RFC2396_BASE, 'g;x?y#s', 'http://a/b/c/g;x?y#s')
432 self.checkJoin(RFC2396_BASE, '.', 'http://a/b/c/')
433 self.checkJoin(RFC2396_BASE, './', 'http://a/b/c/')
434 self.checkJoin(RFC2396_BASE, '..', 'http://a/b/')
435 self.checkJoin(RFC2396_BASE, '../', 'http://a/b/')
436 self.checkJoin(RFC2396_BASE, '../g', 'http://a/b/g')
437 self.checkJoin(RFC2396_BASE, '../..', 'http://a/')
438 self.checkJoin(RFC2396_BASE, '../../', 'http://a/')
439 self.checkJoin(RFC2396_BASE, '../../g', 'http://a/g')
440 self.checkJoin(RFC2396_BASE, '', RFC2396_BASE)
441 self.checkJoin(RFC2396_BASE, 'g.', 'http://a/b/c/g.')
442 self.checkJoin(RFC2396_BASE, '.g', 'http://a/b/c/.g')
443 self.checkJoin(RFC2396_BASE, 'g..', 'http://a/b/c/g..')
444 self.checkJoin(RFC2396_BASE, '..g', 'http://a/b/c/..g')
445 self.checkJoin(RFC2396_BASE, './../g', 'http://a/b/g')
446 self.checkJoin(RFC2396_BASE, './g/.', 'http://a/b/c/g/')
447 self.checkJoin(RFC2396_BASE, 'g/./h', 'http://a/b/c/g/h')
448 self.checkJoin(RFC2396_BASE, 'g/../h', 'http://a/b/c/h')
449 self.checkJoin(RFC2396_BASE, 'g;x=1/./y', 'http://a/b/c/g;x=1/y')
450 self.checkJoin(RFC2396_BASE, 'g;x=1/../y', 'http://a/b/c/y')
451 self.checkJoin(RFC2396_BASE, 'g?y/./x', 'http://a/b/c/g?y/./x')
452 self.checkJoin(RFC2396_BASE, 'g?y/../x', 'http://a/b/c/g?y/../x')
453 self.checkJoin(RFC2396_BASE, 'g#s/./x', 'http://a/b/c/g#s/./x')
454 self.checkJoin(RFC2396_BASE, 'g#s/../x', 'http://a/b/c/g#s/../x')
455
456 # XXX: The following tests are no longer compatible with RFC3986
457 # self.checkJoin(RFC2396_BASE, '../../../g', 'http://a/../g')
458 # self.checkJoin(RFC2396_BASE, '../../../../g', 'http://a/../../g')
459 # self.checkJoin(RFC2396_BASE, '/./g', 'http://a/./g')
460 # self.checkJoin(RFC2396_BASE, '/../g', 'http://a/../g')
461
462 def test_RFC3986(self):
463 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y')
464 self.checkJoin(RFC3986_BASE, ';x', 'http://a/b/c/;x')
465 self.checkJoin(RFC3986_BASE, 'g:h','g:h')
466 self.checkJoin(RFC3986_BASE, 'g','http://a/b/c/g')
467 self.checkJoin(RFC3986_BASE, './g','http://a/b/c/g')
468 self.checkJoin(RFC3986_BASE, 'g/','http://a/b/c/g/')
469 self.checkJoin(RFC3986_BASE, '/g','http://a/g')
470 self.checkJoin(RFC3986_BASE, '//g','http://g')
471 self.checkJoin(RFC3986_BASE, '?y','http://a/b/c/d;p?y')
472 self.checkJoin(RFC3986_BASE, 'g?y','http://a/b/c/g?y')
473 self.checkJoin(RFC3986_BASE, '#s','http://a/b/c/d;p?q#s')
474 self.checkJoin(RFC3986_BASE, 'g#s','http://a/b/c/g#s')
475 self.checkJoin(RFC3986_BASE, 'g?y#s','http://a/b/c/g?y#s')
476 self.checkJoin(RFC3986_BASE, ';x','http://a/b/c/;x')
477 self.checkJoin(RFC3986_BASE, 'g;x','http://a/b/c/g;x')
478 self.checkJoin(RFC3986_BASE, 'g;x?y#s','http://a/b/c/g;x?y#s')
479 self.checkJoin(RFC3986_BASE, '','http://a/b/c/d;p?q')
480 self.checkJoin(RFC3986_BASE, '.','http://a/b/c/')
481 self.checkJoin(RFC3986_BASE, './','http://a/b/c/')
482 self.checkJoin(RFC3986_BASE, '..','http://a/b/')
483 self.checkJoin(RFC3986_BASE, '../','http://a/b/')
484 self.checkJoin(RFC3986_BASE, '../g','http://a/b/g')
485 self.checkJoin(RFC3986_BASE, '../..','http://a/')
486 self.checkJoin(RFC3986_BASE, '../../','http://a/')
487 self.checkJoin(RFC3986_BASE, '../../g','http://a/g')
488 self.checkJoin(RFC3986_BASE, '../../../g', 'http://a/g')
489
490 # Abnormal Examples
491
492 # The 'abnormal scenarios' are incompatible with RFC2986 parsing
493 # Tests are here for reference.
494
495 self.checkJoin(RFC3986_BASE, '../../../g','http://a/g')
496 self.checkJoin(RFC3986_BASE, '../../../../g','http://a/g')
497 self.checkJoin(RFC3986_BASE, '/./g','http://a/g')
498 self.checkJoin(RFC3986_BASE, '/../g','http://a/g')
499 self.checkJoin(RFC3986_BASE, 'g.','http://a/b/c/g.')
500 self.checkJoin(RFC3986_BASE, '.g','http://a/b/c/.g')
501 self.checkJoin(RFC3986_BASE, 'g..','http://a/b/c/g..')
502 self.checkJoin(RFC3986_BASE, '..g','http://a/b/c/..g')
503 self.checkJoin(RFC3986_BASE, './../g','http://a/b/g')
504 self.checkJoin(RFC3986_BASE, './g/.','http://a/b/c/g/')
505 self.checkJoin(RFC3986_BASE, 'g/./h','http://a/b/c/g/h')
506 self.checkJoin(RFC3986_BASE, 'g/../h','http://a/b/c/h')
507 self.checkJoin(RFC3986_BASE, 'g;x=1/./y','http://a/b/c/g;x=1/y')
508 self.checkJoin(RFC3986_BASE, 'g;x=1/../y','http://a/b/c/y')
509 self.checkJoin(RFC3986_BASE, 'g?y/./x','http://a/b/c/g?y/./x')
510 self.checkJoin(RFC3986_BASE, 'g?y/../x','http://a/b/c/g?y/../x')
511 self.checkJoin(RFC3986_BASE, 'g#s/./x','http://a/b/c/g#s/./x')
512 self.checkJoin(RFC3986_BASE, 'g#s/../x','http://a/b/c/g#s/../x')
513 #self.checkJoin(RFC3986_BASE, 'http:g','http:g') # strict parser
514 self.checkJoin(RFC3986_BASE, 'http:g','http://a/b/c/g') #relaxed parser
515
516 # Test for issue9721
517 self.checkJoin('http://a/b/c/de', ';x','http://a/b/c/;x')
518
519 def test_urljoins(self):
520 self.checkJoin(SIMPLE_BASE, 'g:h','g:h')
521 self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
522 self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
523 self.checkJoin(SIMPLE_BASE, 'g','http://a/b/c/g')
524 self.checkJoin(SIMPLE_BASE, './g','http://a/b/c/g')
525 self.checkJoin(SIMPLE_BASE, 'g/','http://a/b/c/g/')
526 self.checkJoin(SIMPLE_BASE, '/g','http://a/g')
527 self.checkJoin(SIMPLE_BASE, '//g','http://g')
528 self.checkJoin(SIMPLE_BASE, '?y','http://a/b/c/d?y')
529 self.checkJoin(SIMPLE_BASE, 'g?y','http://a/b/c/g?y')
530 self.checkJoin(SIMPLE_BASE, 'g?y/./x','http://a/b/c/g?y/./x')
531 self.checkJoin(SIMPLE_BASE, '.','http://a/b/c/')
532 self.checkJoin(SIMPLE_BASE, './','http://a/b/c/')
533 self.checkJoin(SIMPLE_BASE, '..','http://a/b/')
534 self.checkJoin(SIMPLE_BASE, '../','http://a/b/')
535 self.checkJoin(SIMPLE_BASE, '../g','http://a/b/g')
536 self.checkJoin(SIMPLE_BASE, '../..','http://a/')
537 self.checkJoin(SIMPLE_BASE, '../../g','http://a/g')
538 self.checkJoin(SIMPLE_BASE, './../g','http://a/b/g')
539 self.checkJoin(SIMPLE_BASE, './g/.','http://a/b/c/g/')
540 self.checkJoin(SIMPLE_BASE, 'g/./h','http://a/b/c/g/h')
541 self.checkJoin(SIMPLE_BASE, 'g/../h','http://a/b/c/h')
542 self.checkJoin(SIMPLE_BASE, 'http:g','http://a/b/c/g')
543 self.checkJoin(SIMPLE_BASE, 'http:','http://a/b/c/d')
544 self.checkJoin(SIMPLE_BASE, 'http:?y','http://a/b/c/d?y')
545 self.checkJoin(SIMPLE_BASE, 'http:g?y','http://a/b/c/g?y')
546 self.checkJoin(SIMPLE_BASE, 'http:g?y/./x','http://a/b/c/g?y/./x')
547 self.checkJoin('http:///', '..','http:///')
548 self.checkJoin('', 'http://a/b/c/g?y/./x','http://a/b/c/g?y/./x')
549 self.checkJoin('', 'http://a/./g', 'http://a/./g')
550 self.checkJoin('svn://pathtorepo/dir1', 'dir2', 'svn://pathtorepo/dir2')
551 self.checkJoin('svn+ssh://pathtorepo/dir1', 'dir2', 'svn+ssh://pathtorepo/dir2')
552 self.checkJoin('ws://a/b','g','ws://a/g')
553 self.checkJoin('wss://a/b','g','wss://a/g')
554
555 # XXX: The following tests are no longer compatible with RFC3986
556 # self.checkJoin(SIMPLE_BASE, '../../../g','http://a/../g')
557 # self.checkJoin(SIMPLE_BASE, '/./g','http://a/./g')
558
559 # test for issue22118 duplicate slashes
560 self.checkJoin(SIMPLE_BASE + '/', 'foo', SIMPLE_BASE + '/foo')
561
562 # Non-RFC-defined tests, covering variations of base and trailing
563 # slashes
564 self.checkJoin('http://a/b/c/d/e/', '../../f/g/', 'http://a/b/c/f/g/')
565 self.checkJoin('http://a/b/c/d/e', '../../f/g/', 'http://a/b/f/g/')
566 self.checkJoin('http://a/b/c/d/e/', '/../../f/g/', 'http://a/f/g/')
567 self.checkJoin('http://a/b/c/d/e', '/../../f/g/', 'http://a/f/g/')
568 self.checkJoin('http://a/b/c/d/e/', '../../f/g', 'http://a/b/c/f/g')
569 self.checkJoin('http://a/b/', '../../f/g/', 'http://a/f/g/')
570
571 # issue 23703: don't duplicate filename
572 self.checkJoin('a', 'b', 'b')
573
574 @support.subTests('bytes', (False, True))
575 @support.subTests('url,hostname,port', [
576 ('http://Test.python.org:5432/foo/', 'test.python.org', 5432),
577 ('http://12.34.56.78:5432/foo/', '12.34.56.78', 5432),
578 ('http://[::1]:5432/foo/', '::1', 5432),
579 ('http://[dead:beef::1]:5432/foo/', 'dead:beef::1', 5432),
580 ('http://[dead:beef::]:5432/foo/', 'dead:beef::', 5432),
581 ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:5432/foo/',
582 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', 5432),
583 ('http://[::12.34.56.78]:5432/foo/', '::12.34.56.78', 5432),
584 ('http://[::ffff:12.34.56.78]:5432/foo/',
585 '::ffff:12.34.56.78', 5432),
586 ('http://Test.python.org/foo/', 'test.python.org', None),
587 ('http://12.34.56.78/foo/', '12.34.56.78', None),
588 ('http://[::1]/foo/', '::1', None),
589 ('http://[dead:beef::1]/foo/', 'dead:beef::1', None),
590 ('http://[dead:beef::]/foo/', 'dead:beef::', None),
591 ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]/foo/',
592 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None),
593 ('http://[::12.34.56.78]/foo/', '::12.34.56.78', None),
594 ('http://[::ffff:12.34.56.78]/foo/',
595 '::ffff:12.34.56.78', None),
596 ('http://Test.python.org:/foo/', 'test.python.org', None),
597 ('http://12.34.56.78:/foo/', '12.34.56.78', None),
598 ('http://[::1]:/foo/', '::1', None),
599 ('http://[dead:beef::1]:/foo/', 'dead:beef::1', None),
600 ('http://[dead:beef::]:/foo/', 'dead:beef::', None),
601 ('http://[dead:beef:cafe:5417:affe:8FA3:deaf:feed]:/foo/',
602 'dead:beef:cafe:5417:affe:8fa3:deaf:feed', None),
603 ('http://[::12.34.56.78]:/foo/', '::12.34.56.78', None),
604 ('http://[::ffff:12.34.56.78]:/foo/',
605 '::ffff:12.34.56.78', None),
606 ])
607 def test_RFC2732(self, bytes, url, hostname, port):
608 if bytes:
609 url = str_encode(url)
610 hostname = str_encode(hostname)
611 urlparsed = urllib.parse.urlparse(url)
612 self.assertEqual((urlparsed.hostname, urlparsed.port), (hostname, port))
613
614 @support.subTests('bytes', (False, True))
615 @support.subTests('invalid_url', [
616 'http://::12.34.56.78]/',
617 'http://[::1/foo/',
618 'ftp://[::1/foo/bad]/bad',
619 'http://[::1/foo/bad]/bad',
620 'http://[::ffff:12.34.56.78'])
621 def test_RFC2732_invalid(self, bytes, invalid_url):
622 if bytes:
623 invalid_url = str_encode(invalid_url)
624 self.assertRaises(ValueError, urllib.parse.urlparse, invalid_url)
625
626 @support.subTests('bytes', (False, True))
627 @support.subTests('url,defrag,frag', [
628 ('http://python.org#frag', 'http://python.org', 'frag'),
629 ('http://python.org', 'http://python.org', ''),
630 ('http://python.org/#frag', 'http://python.org/', 'frag'),
631 ('http://python.org/', 'http://python.org/', ''),
632 ('http://python.org/?q#frag', 'http://python.org/?q', 'frag'),
633 ('http://python.org/?q', 'http://python.org/?q', ''),
634 ('http://python.org/p#frag', 'http://python.org/p', 'frag'),
635 ('http://python.org/p?q', 'http://python.org/p?q', ''),
636 (RFC1808_BASE, 'http://a/b/c/d;p?q', 'f'),
637 (RFC2396_BASE, 'http://a/b/c/d;p?q', ''),
638 ])
639 def test_urldefrag(self, bytes, url, defrag, frag):
640 if bytes:
641 url = str_encode(url)
642 defrag = str_encode(defrag)
643 frag = str_encode(frag)
644 result = urllib.parse.urldefrag(url)
645 hash = '#' if isinstance(url, str) else b'#'
646 self.assertEqual(result.geturl(), url.rstrip(hash))
647 self.assertEqual(result, (defrag, frag))
648 self.assertEqual(result.url, defrag)
649 self.assertEqual(result.fragment, frag)
650
651 def test_urlsplit_scoped_IPv6(self):
652 p = urllib.parse.urlsplit('http://[FE80::822a:a8ff:fe49:470c%tESt]:1234')
653 self.assertEqual(p.hostname, "fe80::822a:a8ff:fe49:470c%tESt")
654 self.assertEqual(p.netloc, '[FE80::822a:a8ff:fe49:470c%tESt]:1234')
655
656 p = urllib.parse.urlsplit(b'http://[FE80::822a:a8ff:fe49:470c%tESt]:1234')
657 self.assertEqual(p.hostname, b"fe80::822a:a8ff:fe49:470c%tESt")
658 self.assertEqual(p.netloc, b'[FE80::822a:a8ff:fe49:470c%tESt]:1234')
659
660 def test_urlsplit_attributes(self):
661 url = "HTTP://WWW.PYTHON.ORG/doc/#frag"
662 p = urllib.parse.urlsplit(url)
663 self.assertEqual(p.scheme, "http")
664 self.assertEqual(p.netloc, "WWW.PYTHON.ORG")
665 self.assertEqual(p.path, "/doc/")
666 self.assertEqual(p.query, "")
667 self.assertEqual(p.fragment, "frag")
668 self.assertEqual(p.username, None)
669 self.assertEqual(p.password, None)
670 self.assertEqual(p.hostname, "www.python.org")
671 self.assertEqual(p.port, None)
672 # geturl() won't return exactly the original URL in this case
673 # since the scheme is always case-normalized
674 # We handle this by ignoring the first 4 characters of the URL
675 self.assertEqual(p.geturl()[4:], url[4:])
676
677 url = "http://User:[email protected]:080/doc/?query=yes#frag"
678 p = urllib.parse.urlsplit(url)
679 self.assertEqual(p.scheme, "http")
680 self.assertEqual(p.netloc, "User:[email protected]:080")
681 self.assertEqual(p.path, "/doc/")
682 self.assertEqual(p.query, "query=yes")
683 self.assertEqual(p.fragment, "frag")
684 self.assertEqual(p.username, "User")
685 self.assertEqual(p.password, "Pass")
686 self.assertEqual(p.hostname, "www.python.org")
687 self.assertEqual(p.port, 80)
688 self.assertEqual(p.geturl(), url)
689
690 # Addressing issue1698, which suggests Username can contain
691 # "@" characters. Though not RFC compliant, many ftp sites allow
692 # and request email addresses as usernames.
693
694 url = "http://[email protected]:[email protected]:080/doc/?query=yes#frag"
695 p = urllib.parse.urlsplit(url)
696 self.assertEqual(p.scheme, "http")
697 self.assertEqual(p.netloc, "[email protected]:[email protected]:080")
698 self.assertEqual(p.path, "/doc/")
699 self.assertEqual(p.query, "query=yes")
700 self.assertEqual(p.fragment, "frag")
701 self.assertEqual(p.username, "[email protected]")
702 self.assertEqual(p.password, "Pass")
703 self.assertEqual(p.hostname, "www.python.org")
704 self.assertEqual(p.port, 80)
705 self.assertEqual(p.geturl(), url)
706
707 # And check them all again, only with bytes this time
708 url = b"HTTP://WWW.PYTHON.ORG/doc/#frag"
709 p = urllib.parse.urlsplit(url)
710 self.assertEqual(p.scheme, b"http")
711 self.assertEqual(p.netloc, b"WWW.PYTHON.ORG")
712 self.assertEqual(p.path, b"/doc/")
713 self.assertEqual(p.query, b"")
714 self.assertEqual(p.fragment, b"frag")
715 self.assertEqual(p.username, None)
716 self.assertEqual(p.password, None)
717 self.assertEqual(p.hostname, b"www.python.org")
718 self.assertEqual(p.port, None)
719 self.assertEqual(p.geturl()[4:], url[4:])
720
721 url = b"http://User:[email protected]:080/doc/?query=yes#frag"
722 p = urllib.parse.urlsplit(url)
723 self.assertEqual(p.scheme, b"http")
724 self.assertEqual(p.netloc, b"User:[email protected]:080")
725 self.assertEqual(p.path, b"/doc/")
726 self.assertEqual(p.query, b"query=yes")
727 self.assertEqual(p.fragment, b"frag")
728 self.assertEqual(p.username, b"User")
729 self.assertEqual(p.password, b"Pass")
730 self.assertEqual(p.hostname, b"www.python.org")
731 self.assertEqual(p.port, 80)
732 self.assertEqual(p.geturl(), url)
733
734 url = b"http://[email protected]:[email protected]:080/doc/?query=yes#frag"
735 p = urllib.parse.urlsplit(url)
736 self.assertEqual(p.scheme, b"http")
737 self.assertEqual(p.netloc, b"[email protected]:[email protected]:080")
738 self.assertEqual(p.path, b"/doc/")
739 self.assertEqual(p.query, b"query=yes")
740 self.assertEqual(p.fragment, b"frag")
741 self.assertEqual(p.username, b"[email protected]")
742 self.assertEqual(p.password, b"Pass")
743 self.assertEqual(p.hostname, b"www.python.org")
744 self.assertEqual(p.port, 80)
745 self.assertEqual(p.geturl(), url)
746
747 # Verify an illegal port raises ValueError
748 url = b"HTTP://WWW.PYTHON.ORG:65536/doc/#frag"
749 p = urllib.parse.urlsplit(url)
750 with self.assertRaisesRegex(ValueError, "out of range"):
751 p.port
752
753 def test_urlsplit_remove_unsafe_bytes(self):
754 # Remove ASCII tabs and newlines from input
755 url = "http\t://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
756 p = urllib.parse.urlsplit(url)
757 self.assertEqual(p.scheme, "http")
758 self.assertEqual(p.netloc, "www.python.org")
759 self.assertEqual(p.path, "/javascript:alert('msg')/")
760 self.assertEqual(p.query, "query=something")
761 self.assertEqual(p.fragment, "fragment")
762 self.assertEqual(p.username, None)
763 self.assertEqual(p.password, None)
764 self.assertEqual(p.hostname, "www.python.org")
765 self.assertEqual(p.port, None)
766 self.assertEqual(p.geturl(), "http://www.python.org/javascript:alert('msg')/?query=something#fragment")
767
768 # Remove ASCII tabs and newlines from input as bytes.
769 url = b"http\t://www.python\n.org\t/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
770 p = urllib.parse.urlsplit(url)
771 self.assertEqual(p.scheme, b"http")
772 self.assertEqual(p.netloc, b"www.python.org")
773 self.assertEqual(p.path, b"/javascript:alert('msg')/")
774 self.assertEqual(p.query, b"query=something")
775 self.assertEqual(p.fragment, b"fragment")
776 self.assertEqual(p.username, None)
777 self.assertEqual(p.password, None)
778 self.assertEqual(p.hostname, b"www.python.org")
779 self.assertEqual(p.port, None)
780 self.assertEqual(p.geturl(), b"http://www.python.org/javascript:alert('msg')/?query=something#fragment")
781
782 # with scheme as cache-key
783 url = "http://www.python.org/java\nscript:\talert('msg\r\n')/?query\n=\tsomething#frag\nment"
784 scheme = "ht\ntp"
785 for _ in range(2):
786 p = urllib.parse.urlsplit(url, scheme=scheme)
787 self.assertEqual(p.scheme, "http")
788 self.assertEqual(p.geturl(), "http://www.python.org/javascript:alert('msg')/?query=something#fragment")
789
790 def test_urlsplit_strip_url(self):
791 noise = bytes(range(0, 0x20 + 1))
792 base_url = "http://User:[email protected]:080/doc/?query=yes#frag"
793
794 url = noise.decode("utf-8") + base_url
795 p = urllib.parse.urlsplit(url)
796 self.assertEqual(p.scheme, "http")
797 self.assertEqual(p.netloc, "User:[email protected]:080")
798 self.assertEqual(p.path, "/doc/")
799 self.assertEqual(p.query, "query=yes")
800 self.assertEqual(p.fragment, "frag")
801 self.assertEqual(p.username, "User")
802 self.assertEqual(p.password, "Pass")
803 self.assertEqual(p.hostname, "www.python.org")
804 self.assertEqual(p.port, 80)
805 self.assertEqual(p.geturl(), base_url)
806
807 url = noise + base_url.encode("utf-8")
808 p = urllib.parse.urlsplit(url)
809 self.assertEqual(p.scheme, b"http")
810 self.assertEqual(p.netloc, b"User:[email protected]:080")
811 self.assertEqual(p.path, b"/doc/")
812 self.assertEqual(p.query, b"query=yes")
813 self.assertEqual(p.fragment, b"frag")
814 self.assertEqual(p.username, b"User")
815 self.assertEqual(p.password, b"Pass")
816 self.assertEqual(p.hostname, b"www.python.org")
817 self.assertEqual(p.port, 80)
818 self.assertEqual(p.geturl(), base_url.encode("utf-8"))
819
820 # Test that trailing space is preserved as some applications rely on
821 # this within query strings.
822 query_spaces_url = "https://www.python.org:88/doc/?query= "
823 p = urllib.parse.urlsplit(noise.decode("utf-8") + query_spaces_url)
824 self.assertEqual(p.scheme, "https")
825 self.assertEqual(p.netloc, "www.python.org:88")
826 self.assertEqual(p.path, "/doc/")
827 self.assertEqual(p.query, "query= ")
828 self.assertEqual(p.port, 88)
829 self.assertEqual(p.geturl(), query_spaces_url)
830
831 p = urllib.parse.urlsplit("www.pypi.org ")
832 # That "hostname" gets considered a "path" due to the
833 # trailing space and our existing logic... YUCK...
834 # and re-assembles via geturl aka unurlsplit into the original.
835 # django.core.validators.URLValidator (at least through v3.2) relies on
836 # this, for better or worse, to catch it in a ValidationError via its
837 # regular expressions.
838 # Here we test the basic round trip concept of such a trailing space.
839 self.assertEqual(urllib.parse.urlunsplit(p), "www.pypi.org ")
840
841 # with scheme as cache-key
842 url = "//www.python.org/"
843 scheme = noise.decode("utf-8") + "https" + noise.decode("utf-8")
844 for _ in range(2):
845 p = urllib.parse.urlsplit(url, scheme=scheme)
846 self.assertEqual(p.scheme, "https")
847 self.assertEqual(p.geturl(), "https://www.python.org/")
848
849 @support.subTests('bytes', (False, True))
850 @support.subTests('parse', (urllib.parse.urlsplit, urllib.parse.urlparse))
851 @support.subTests('port', ("foo", "1.5", "-1", "0x10", "-0", "1_1", " 1", "1 ", "६"))
852 def test_attributes_bad_port(self, bytes, parse, port):
853 """Check handling of invalid ports."""
854 netloc = "www.example.net:" + port
855 url = "http://" + netloc + "/"
856 if bytes:
857 if not (netloc.isascii() and port.isascii()):
858 self.skipTest('non-ASCII bytes')
859 netloc = str_encode(netloc)
860 url = str_encode(url)
861 p = parse(url)
862 self.assertEqual(p.netloc, netloc)
863 with self.assertRaises(ValueError):
864 p.port
865
866 @support.subTests('bytes', (False, True))
867 @support.subTests('parse', (urllib.parse.urlsplit, urllib.parse.urlparse))
868 @support.subTests('scheme', (".", "+", "-", "0", "http&", "६http"))
869 def test_attributes_bad_scheme(self, bytes, parse, scheme):
870 """Check handling of invalid schemes."""
871 url = scheme + "://www.example.net"
872 if bytes:
873 if not url.isascii():
874 self.skipTest('non-ASCII bytes')
875 url = url.encode("ascii")
876 p = parse(url)
877 self.assertEqual(p.scheme, b"" if bytes else "")
878
879 def test_attributes_without_netloc(self):
880 # This example is straight from RFC 3261. It looks like it
881 # should allow the username, hostname, and port to be filled
882 # in, but doesn't. Since it's a URI and doesn't use the
883 # scheme://netloc syntax, the netloc and related attributes
884 # should be left empty.
885 uri = "sip:[email protected];maddr=239.255.255.1;ttl=15"
886 p = urllib.parse.urlsplit(uri)
887 self.assertEqual(p.netloc, "")
888 self.assertEqual(p.username, None)
889 self.assertEqual(p.password, None)
890 self.assertEqual(p.hostname, None)
891 self.assertEqual(p.port, None)
892 self.assertEqual(p.geturl(), uri)
893
894 p = urllib.parse.urlparse(uri)
895 self.assertEqual(p.netloc, "")
896 self.assertEqual(p.username, None)
897 self.assertEqual(p.password, None)
898 self.assertEqual(p.hostname, None)
899 self.assertEqual(p.port, None)
900 self.assertEqual(p.geturl(), uri)
901
902 # You guessed it, repeating the test with bytes input
903 uri = b"sip:[email protected];maddr=239.255.255.1;ttl=15"
904 p = urllib.parse.urlsplit(uri)
905 self.assertEqual(p.netloc, b"")
906 self.assertEqual(p.username, None)
907 self.assertEqual(p.password, None)
908 self.assertEqual(p.hostname, None)
909 self.assertEqual(p.port, None)
910 self.assertEqual(p.geturl(), uri)
911
912 p = urllib.parse.urlparse(uri)
913 self.assertEqual(p.netloc, b"")
914 self.assertEqual(p.username, None)
915 self.assertEqual(p.password, None)
916 self.assertEqual(p.hostname, None)
917 self.assertEqual(p.port, None)
918 self.assertEqual(p.geturl(), uri)
919
920 def test_noslash(self):
921 # Issue 1637: http://foo.com?query is legal
922 self.assertEqual(urllib.parse.urlparse("http://example.com?blahblah=/foo"),
923 ('http', 'example.com', '', '', 'blahblah=/foo', ''))
924 self.assertEqual(urllib.parse.urlparse(b"http://example.com?blahblah=/foo"),
925 (b'http', b'example.com', b'', b'', b'blahblah=/foo', b''))
926
927 def test_withoutscheme(self):
928 # Test urlparse without scheme
929 # Issue 754016: urlparse goes wrong with IP:port without scheme
930 # RFC 1808 specifies that netloc should start with //, urlparse expects
931 # the same, otherwise it classifies the portion of url as path.
932 self.assertEqual(urllib.parse.urlparse("path"),
933 ('','','path','','',''))
934 self.assertEqual(urllib.parse.urlparse("//www.python.org:80"),
935 ('','www.python.org:80','','','',''))
936 self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
937 ('http','www.python.org:80','','','',''))
938 # Repeat for bytes input
939 self.assertEqual(urllib.parse.urlparse(b"path"),
940 (b'',b'',b'path',b'',b'',b''))
941 self.assertEqual(urllib.parse.urlparse(b"//www.python.org:80"),
942 (b'',b'www.python.org:80',b'',b'',b'',b''))
943 self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"),
944 (b'http',b'www.python.org:80',b'',b'',b'',b''))
945
946 def test_portseparator(self):
947 # Issue 754016 makes changes for port separator ':' from scheme separator
948 self.assertEqual(urllib.parse.urlparse("http:80"), ('http','','80','','',''))
949 self.assertEqual(urllib.parse.urlparse("https:80"), ('https','','80','','',''))
950 self.assertEqual(urllib.parse.urlparse("path:80"), ('path','','80','','',''))
951 self.assertEqual(urllib.parse.urlparse("http:"),('http','','','','',''))
952 self.assertEqual(urllib.parse.urlparse("https:"),('https','','','','',''))
953 self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"),
954 ('http','www.python.org:80','','','',''))
955 # As usual, need to check bytes input as well
956 self.assertEqual(urllib.parse.urlparse(b"http:80"), (b'http',b'',b'80',b'',b'',b''))
957 self.assertEqual(urllib.parse.urlparse(b"https:80"), (b'https',b'',b'80',b'',b'',b''))
958 self.assertEqual(urllib.parse.urlparse(b"path:80"), (b'path',b'',b'80',b'',b'',b''))
959 self.assertEqual(urllib.parse.urlparse(b"http:"),(b'http',b'',b'',b'',b'',b''))
960 self.assertEqual(urllib.parse.urlparse(b"https:"),(b'https',b'',b'',b'',b'',b''))
961 self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"),
962 (b'http',b'www.python.org:80',b'',b'',b'',b''))
963
964 def test_usingsys(self):
965 # Issue 3314: sys module is used in the error
966 self.assertRaises(TypeError, urllib.parse.urlencode, "foo")
967
968 def test_anyscheme(self):
969 # Issue 7904: s3://foo.com/stuff has netloc "foo.com".
970 self.assertEqual(urllib.parse.urlparse("s3://foo.com/stuff"),
971 ('s3', 'foo.com', '/stuff', '', '', ''))
972 self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff"),
973 ('x-newscheme', 'foo.com', '/stuff', '', '', ''))
974 self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query#fragment"),
975 ('x-newscheme', 'foo.com', '/stuff', '', 'query', 'fragment'))
976 self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query"),
977 ('x-newscheme', 'foo.com', '/stuff', '', 'query', ''))
978
979 # And for bytes...
980 self.assertEqual(urllib.parse.urlparse(b"s3://foo.com/stuff"),
981 (b's3', b'foo.com', b'/stuff', b'', b'', b''))
982 self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff"),
983 (b'x-newscheme', b'foo.com', b'/stuff', b'', b'', b''))
984 self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query#fragment"),
985 (b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b'fragment'))
986 self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query"),
987 (b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b''))
988
989 @support.subTests('func', (urllib.parse.urlparse, urllib.parse.urlsplit))
990 def test_default_scheme(self, func):
991 # Exercise the scheme parameter of urlparse() and urlsplit()
992 result = func("http://example.net/", "ftp")
993 self.assertEqual(result.scheme, "http")
994 result = func(b"http://example.net/", b"ftp")
995 self.assertEqual(result.scheme, b"http")
996 self.assertEqual(func("path", "ftp").scheme, "ftp")
997 self.assertEqual(func("path", scheme="ftp").scheme, "ftp")
998 self.assertEqual(func(b"path", scheme=b"ftp").scheme, b"ftp")
999 self.assertEqual(func("path").scheme, "")
1000 self.assertEqual(func(b"path").scheme, b"")
1001 self.assertEqual(func(b"path", "").scheme, b"")
1002
1003 @support.subTests('url,attr,expected_frag', (
1004 ("http:#frag", "path", "frag"),
1005 ("//example.net#frag", "path", "frag"),
1006 ("index.html#frag", "path", "frag"),
1007 (";a=b#frag", "params", "frag"),
1008 ("?a=b#frag", "query", "frag"),
1009 ("#frag", "path", "frag"),
1010 ("abc#@frag", "path", "@frag"),
1011 ("//abc#@frag", "path", "@frag"),
1012 ("//abc:80#@frag", "path", "@frag"),
1013 ("//abc#@frag:80", "path", "@frag:80"),
1014 ))
1015 @support.subTests('func', (urllib.parse.urlparse, urllib.parse.urlsplit))
1016 def test_parse_fragments(self, url, attr, expected_frag, func):
1017 # Exercise the allow_fragments parameter of urlparse() and urlsplit()
1018 if attr == "params" and func is urllib.parse.urlsplit:
1019 attr = "path"
1020 result = func(url, allow_fragments=False)
1021 self.assertEqual(result.fragment, "")
1022 self.assertEndsWith(getattr(result, attr),
1023 "#" + expected_frag)
1024 self.assertEqual(func(url, "", False).fragment, "")
1025
1026 result = func(url, allow_fragments=True)
1027 self.assertEqual(result.fragment, expected_frag)
1028 self.assertNotEndsWith(getattr(result, attr), expected_frag)
1029 self.assertEqual(func(url, "", True).fragment,
1030 expected_frag)
1031 self.assertEqual(func(url).fragment, expected_frag)
1032
1033 def test_mixed_types_rejected(self):
1034 # Several functions that process either strings or ASCII encoded bytes
1035 # accept multiple arguments. Check they reject mixed type input
1036 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1037 urllib.parse.urlparse("www.python.org", b"http")
1038 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1039 urllib.parse.urlparse(b"www.python.org", "http")
1040 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1041 urllib.parse.urlsplit("www.python.org", b"http")
1042 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1043 urllib.parse.urlsplit(b"www.python.org", "http")
1044 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1045 urllib.parse.urlunparse(( b"http", "www.python.org","","","",""))
1046 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1047 urllib.parse.urlunparse(("http", b"www.python.org","","","",""))
1048 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1049 urllib.parse.urlunsplit((b"http", "www.python.org","","",""))
1050 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1051 urllib.parse.urlunsplit(("http", b"www.python.org","","",""))
1052 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1053 urllib.parse.urljoin("http://python.org", b"http://python.org")
1054 with self.assertRaisesRegex(TypeError, "Cannot mix str"):
1055 urllib.parse.urljoin(b"http://python.org", "http://python.org")
1056
1057 @support.subTests('result_type', [
1058 urllib.parse.DefragResult,
1059 urllib.parse.SplitResult,
1060 urllib.parse.ParseResult,
1061 ])
1062 def test_result_pairs(self, result_type):
1063 # Check encoding and decoding between result pairs
1064 str_type = result_type
1065 num_args = len(str_type._fields)
1066 bytes_type = str_type._encoded_counterpart
1067 self.assertIs(bytes_type._decoded_counterpart, str_type)
1068 str_args = ('',) * num_args
1069 bytes_args = (b'',) * num_args
1070 str_result = str_type(*str_args)
1071 bytes_result = bytes_type(*bytes_args)
1072 encoding = 'ascii'
1073 errors = 'strict'
1074 self.assertEqual(str_result, str_args)
1075 self.assertEqual(bytes_result.decode(), str_args)
1076 self.assertEqual(bytes_result.decode(), str_result)
1077 self.assertEqual(bytes_result.decode(encoding), str_args)
1078 self.assertEqual(bytes_result.decode(encoding), str_result)
1079 self.assertEqual(bytes_result.decode(encoding, errors), str_args)
1080 self.assertEqual(bytes_result.decode(encoding, errors), str_result)
1081 self.assertEqual(bytes_result, bytes_args)
1082 self.assertEqual(str_result.encode(), bytes_args)
1083 self.assertEqual(str_result.encode(), bytes_result)
1084 self.assertEqual(str_result.encode(encoding), bytes_args)
1085 self.assertEqual(str_result.encode(encoding), bytes_result)
1086 self.assertEqual(str_result.encode(encoding, errors), bytes_args)
1087 self.assertEqual(str_result.encode(encoding, errors), bytes_result)
1088
1089 def test_parse_qs_encoding(self):
1090 result = urllib.parse.parse_qs("key=\u0141%E9", encoding="latin-1")
1091 self.assertEqual(result, {'key': ['\u0141\xE9']})
1092 result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="utf-8")
1093 self.assertEqual(result, {'key': ['\u0141\xE9']})
1094 result = urllib.parse.parse_qs("key=\u0141%C3%A9", encoding="ascii")
1095 self.assertEqual(result, {'key': ['\u0141\ufffd\ufffd']})
1096 result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii")
1097 self.assertEqual(result, {'key': ['\u0141\ufffd-']})
1098 result = urllib.parse.parse_qs("key=\u0141%E9-", encoding="ascii",
1099 errors="ignore")
1100 self.assertEqual(result, {'key': ['\u0141-']})
1101
1102 def test_parse_qsl_encoding(self):
1103 result = urllib.parse.parse_qsl("key=\u0141%E9", encoding="latin-1")
1104 self.assertEqual(result, [('key', '\u0141\xE9')])
1105 result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="utf-8")
1106 self.assertEqual(result, [('key', '\u0141\xE9')])
1107 result = urllib.parse.parse_qsl("key=\u0141%C3%A9", encoding="ascii")
1108 self.assertEqual(result, [('key', '\u0141\ufffd\ufffd')])
1109 result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii")
1110 self.assertEqual(result, [('key', '\u0141\ufffd-')])
1111 result = urllib.parse.parse_qsl("key=\u0141%E9-", encoding="ascii",
1112 errors="ignore")
1113 self.assertEqual(result, [('key', '\u0141-')])
1114
1115 def test_parse_qsl_max_num_fields(self):
1116 with self.assertRaises(ValueError):
1117 urllib.parse.parse_qsl('&'.join(['a=a']*11), max_num_fields=10)
1118 urllib.parse.parse_qsl('&'.join(['a=a']*10), max_num_fields=10)
1119
1120 @support.subTests('orig,expect', [
1121 (";", {}),
1122 (";;", {}),
1123 (";a=b", {'a': ['b']}),
1124 ("a=a+b;b=b+c", {'a': ['a b'], 'b': ['b c']}),
1125 ("a=1;a=2", {'a': ['1', '2']}),
1126 (b";", {}),
1127 (b";;", {}),
1128 (b";a=b", {b'a': [b'b']}),
1129 (b"a=a+b;b=b+c", {b'a': [b'a b'], b'b': [b'b c']}),
1130 (b"a=1;a=2", {b'a': [b'1', b'2']}),
1131 ])
1132 def test_parse_qs_separator(self, orig, expect):
1133 result = urllib.parse.parse_qs(orig, separator=';')
1134 self.assertEqual(result, expect)
1135 result_bytes = urllib.parse.parse_qs(orig, separator=b';')
1136 self.assertEqual(result_bytes, expect)
1137
1138 @support.subTests('orig,expect', [
1139 (";", []),
1140 (";;", []),
1141 (";a=b", [('a', 'b')]),
1142 ("a=a+b;b=b+c", [('a', 'a b'), ('b', 'b c')]),
1143 ("a=1;a=2", [('a', '1'), ('a', '2')]),
1144 (b";", []),
1145 (b";;", []),
1146 (b";a=b", [(b'a', b'b')]),
1147 (b"a=a+b;b=b+c", [(b'a', b'a b'), (b'b', b'b c')]),
1148 (b"a=1;a=2", [(b'a', b'1'), (b'a', b'2')]),
1149 ])
1150 def test_parse_qsl_separator(self, orig, expect):
1151 result = urllib.parse.parse_qsl(orig, separator=';')
1152 self.assertEqual(result, expect)
1153 result_bytes = urllib.parse.parse_qsl(orig, separator=b';')
1154 self.assertEqual(result_bytes, expect)
1155
1156 def test_parse_qsl_bytes(self):
1157 self.assertEqual(urllib.parse.parse_qsl(b'a=b'), [(b'a', b'b')])
1158 self.assertEqual(urllib.parse.parse_qsl(bytearray(b'a=b')), [(b'a', b'b')])
1159 self.assertEqual(urllib.parse.parse_qsl(memoryview(b'a=b')), [(b'a', b'b')])
1160
1161 def test_parse_qsl_false_value(self):
1162 kwargs = dict(keep_blank_values=True, strict_parsing=True)
1163 for x in '', b'', None, 0, 0.0, [], {}, memoryview(b''):
1164 self.assertEqual(urllib.parse.parse_qsl(x, **kwargs), [])
1165 self.assertRaises(ValueError, urllib.parse.parse_qsl, x, separator=1)
1166
1167 def test_parse_qsl_errors(self):
1168 self.assertRaises(TypeError, urllib.parse.parse_qsl, list(b'a=b'))
1169 self.assertRaises(TypeError, urllib.parse.parse_qsl, iter(b'a=b'))
1170 self.assertRaises(TypeError, urllib.parse.parse_qsl, 1)
1171 self.assertRaises(TypeError, urllib.parse.parse_qsl, object())
1172
1173 for separator in '', b'', None, 0, 1, 0.0, 1.5:
1174 with self.assertRaises(ValueError):
1175 urllib.parse.parse_qsl('a=b', separator=separator)
1176 with self.assertRaises(UnicodeEncodeError):
1177 urllib.parse.parse_qsl(b'a=b', separator='\xa6')
1178 with self.assertRaises(UnicodeDecodeError):
1179 urllib.parse.parse_qsl('a=b', separator=b'\xa6')
1180
1181 def test_urlencode_sequences(self):
1182 # Other tests incidentally urlencode things; test non-covered cases:
1183 # Sequence and object values.
1184 result = urllib.parse.urlencode({'a': [1, 2], 'b': (3, 4, 5)}, True)
1185 # we cannot rely on ordering here
1186 assert set(result.split('&')) == {'a=1', 'a=2', 'b=3', 'b=4', 'b=5'}
1187
1188 class Trivial:
1189 def __str__(self):
1190 return 'trivial'
1191
1192 result = urllib.parse.urlencode({'a': Trivial()}, True)
1193 self.assertEqual(result, 'a=trivial')
1194
1195 def test_urlencode_quote_via(self):
1196 result = urllib.parse.urlencode({'a': 'some value'})
1197 self.assertEqual(result, "a=some+value")
1198 result = urllib.parse.urlencode({'a': 'some value/another'},
1199 quote_via=urllib.parse.quote)
1200 self.assertEqual(result, "a=some%20value%2Fanother")
1201 result = urllib.parse.urlencode({'a': 'some value/another'},
1202 safe='/', quote_via=urllib.parse.quote)
1203 self.assertEqual(result, "a=some%20value/another")
1204
1205 def test_quote_from_bytes(self):
1206 self.assertRaises(TypeError, urllib.parse.quote_from_bytes, 'foo')
1207 result = urllib.parse.quote_from_bytes(b'archaeological arcana')
1208 self.assertEqual(result, 'archaeological%20arcana')
1209 result = urllib.parse.quote_from_bytes(b'')
1210 self.assertEqual(result, '')
1211 result = urllib.parse.quote_from_bytes(b'A'*10_000)
1212 self.assertEqual(result, 'A'*10_000)
1213 result = urllib.parse.quote_from_bytes(b'z\x01/ '*253_183)
1214 self.assertEqual(result, 'z%01/%20'*253_183)
1215
1216 def test_unquote_to_bytes(self):
1217 result = urllib.parse.unquote_to_bytes('abc%20def')
1218 self.assertEqual(result, b'abc def')
1219 result = urllib.parse.unquote_to_bytes('')
1220 self.assertEqual(result, b'')
1221
1222 def test_quote_errors(self):
1223 self.assertRaises(TypeError, urllib.parse.quote, b'foo',
1224 encoding='utf-8')
1225 self.assertRaises(TypeError, urllib.parse.quote, b'foo', errors='strict')
1226
1227 def test_issue14072(self):
1228 p1 = urllib.parse.urlsplit('tel:+31-641044153')
1229 self.assertEqual(p1.scheme, 'tel')
1230 self.assertEqual(p1.path, '+31-641044153')
1231 p2 = urllib.parse.urlsplit('tel:+31641044153')
1232 self.assertEqual(p2.scheme, 'tel')
1233 self.assertEqual(p2.path, '+31641044153')
1234 # assert the behavior for urlparse
1235 p1 = urllib.parse.urlparse('tel:+31-641044153')
1236 self.assertEqual(p1.scheme, 'tel')
1237 self.assertEqual(p1.path, '+31-641044153')
1238 p2 = urllib.parse.urlparse('tel:+31641044153')
1239 self.assertEqual(p2.scheme, 'tel')
1240 self.assertEqual(p2.path, '+31641044153')
1241
1242 def test_invalid_bracketed_hosts(self):
1243 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[192.0.2.146]/Path?Query')
1244 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[important.com:8000]/Path?Query')
1245 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[v123r.IP]/Path?Query')
1246 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[v12ae]/Path?Query')
1247 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[v.IP]/Path?Query')
1248 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[v123.]/Path?Query')
1249 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[v]/Path?Query')
1250 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[0439:23af::2309::fae7:1234]/Path?Query')
1251 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@[0439:23af:2309::fae7:1234:2342:438e:192.0.2.146]/Path?Query')
1252 self.assertRaises(ValueError, urllib.parse.urlsplit, 'Scheme://user@]v6a.ip[/Path')
1253 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[v6a.ip]')
1254 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[v6a.ip].suffix')
1255 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[v6a.ip]/')
1256 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[v6a.ip].suffix/')
1257 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[v6a.ip]?')
1258 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[v6a.ip].suffix?')
1259 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]')
1260 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix')
1261 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]/')
1262 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix/')
1263 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]?')
1264 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix?')
1265 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]:a')
1266 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix:a')
1267 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]:a1')
1268 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix:a1')
1269 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]:1a')
1270 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix:1a')
1271 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]:')
1272 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[::1].suffix:/')
1273 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[::1]:?')
1274 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://user@prefix.[v6a.ip]')
1275 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://user@[v6a.ip].suffix')
1276 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://[v6a.ip')
1277 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://v6a.ip]')
1278 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://]v6a.ip[')
1279 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://]v6a.ip')
1280 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://v6a.ip[')
1281 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix.[v6a.ip')
1282 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://v6a.ip].suffix')
1283 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix]v6a.ip[suffix')
1284 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://prefix]v6a.ip')
1285 self.assertRaises(ValueError, urllib.parse.urlsplit, 'scheme://v6a.ip[suffix')
1286
1287 def test_splitting_bracketed_hosts(self):
1288 p1 = urllib.parse.urlsplit('scheme://user@[v6a.ip]:1234/path?query')
1289 self.assertEqual(p1.hostname, 'v6a.ip')
1290 self.assertEqual(p1.username, 'user')
1291 self.assertEqual(p1.path, '/path')
1292 self.assertEqual(p1.port, 1234)
1293 p2 = urllib.parse.urlsplit('scheme://user@[0439:23af:2309::fae7%test]/path?query')
1294 self.assertEqual(p2.hostname, '0439:23af:2309::fae7%test')
1295 self.assertEqual(p2.username, 'user')
1296 self.assertEqual(p2.path, '/path')
1297 self.assertIs(p2.port, None)
1298 p3 = urllib.parse.urlsplit('scheme://user@[0439:23af:2309::fae7:1234:192.0.2.146%test]/path?query')
1299 self.assertEqual(p3.hostname, '0439:23af:2309::fae7:1234:192.0.2.146%test')
1300 self.assertEqual(p3.username, 'user')
1301 self.assertEqual(p3.path, '/path')
1302
1303 def test_port_casting_failure_message(self):
1304 message = "Port could not be cast to integer value as 'oracle'"
1305 p1 = urllib.parse.urlparse('http://Server=sde; Service=sde:oracle')
1306 with self.assertRaisesRegex(ValueError, message):
1307 p1.port
1308
1309 p2 = urllib.parse.urlsplit('http://Server=sde; Service=sde:oracle')
1310 with self.assertRaisesRegex(ValueError, message):
1311 p2.port
1312
1313 def test_telurl_params(self):
1314 p1 = urllib.parse.urlparse('tel:123-4;phone-context=+1-650-516')
1315 self.assertEqual(p1.scheme, 'tel')
1316 self.assertEqual(p1.path, '123-4')
1317 self.assertEqual(p1.params, 'phone-context=+1-650-516')
1318
1319 p1 = urllib.parse.urlparse('tel:+1-201-555-0123')
1320 self.assertEqual(p1.scheme, 'tel')
1321 self.assertEqual(p1.path, '+1-201-555-0123')
1322 self.assertEqual(p1.params, '')
1323
1324 p1 = urllib.parse.urlparse('tel:7042;phone-context=example.com')
1325 self.assertEqual(p1.scheme, 'tel')
1326 self.assertEqual(p1.path, '7042')
1327 self.assertEqual(p1.params, 'phone-context=example.com')
1328
1329 p1 = urllib.parse.urlparse('tel:863-1234;phone-context=+1-914-555')
1330 self.assertEqual(p1.scheme, 'tel')
1331 self.assertEqual(p1.path, '863-1234')
1332 self.assertEqual(p1.params, 'phone-context=+1-914-555')
1333
1334 def test_Quoter_repr(self):
1335 quoter = urllib.parse._Quoter(urllib.parse._ALWAYS_SAFE)
1336 self.assertIn('Quoter', repr(quoter))
1337
1338 def test_clear_cache_for_code_coverage(self):
1339 urllib.parse.clear_cache()
1340
1341 def test_urllib_parse_getattr_failure(self):
1342 """Test that urllib.parse.__getattr__() fails correctly."""
1343 with self.assertRaises(AttributeError):
1344 unused = urllib.parse.this_does_not_exist
1345
1346 def test_all(self):
1347 expected = []
1348 undocumented = {
1349 'splitattr', 'splithost', 'splitnport', 'splitpasswd',
1350 'splitport', 'splitquery', 'splittag', 'splittype', 'splituser',
1351 'splitvalue',
1352 'ResultBase', 'clear_cache', 'to_bytes', 'unwrap',
1353 }
1354 for name in dir(urllib.parse):
1355 if name.startswith('_') or name in undocumented:
1356 continue
1357 object = getattr(urllib.parse, name)
1358 if getattr(object, '__module__', None) == 'urllib.parse':
1359 expected.append(name)
1360 self.assertCountEqual(urllib.parse.__all__, expected)
1361
1362 def test_urlsplit_normalization(self):
1363 # Certain characters should never occur in the netloc,
1364 # including under normalization.
1365 # Ensure that ALL of them are detected and cause an error
1366 illegal_chars = '/:#?@'
1367 hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars}
1368 denorm_chars = [
1369 c for c in map(chr, range(128, sys.maxunicode))
1370 if unicodedata.decomposition(c)
1371 and (hex_chars & set(unicodedata.decomposition(c).split()))
1372 and c not in illegal_chars
1373 ]
1374 # Sanity check that we found at least one such character
1375 self.assertIn('\u2100', denorm_chars)
1376 self.assertIn('\uFF03', denorm_chars)
1377
1378 # bpo-36742: Verify port separators are ignored when they
1379 # existed prior to decomposition
1380 urllib.parse.urlsplit('http://\u30d5\u309a:80')
1381 with self.assertRaises(ValueError):
1382 urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380')
1383
1384 for scheme in ["http", "https", "ftp"]:
1385 for netloc in ["netloc{}false.netloc", "n{}user@netloc"]:
1386 for c in denorm_chars:
1387 url = "{}://{}/path".format(scheme, netloc.format(c))
1388 with self.subTest(url=url, char='{:04X}'.format(ord(c))):
1389 with self.assertRaises(ValueError):
1390 urllib.parse.urlsplit(url)
1391
1392 class Utility_Tests(unittest.TestCase):
1393 """Testcase to test the various utility functions in the urllib."""
1394 # In Python 2 this test class was in test_urllib.
1395
1396 def test_splittype(self):
1397 splittype = urllib.parse._splittype
1398 self.assertEqual(splittype('type:opaquestring'), ('type', 'opaquestring'))
1399 self.assertEqual(splittype('opaquestring'), (None, 'opaquestring'))
1400 self.assertEqual(splittype(':opaquestring'), (None, ':opaquestring'))
1401 self.assertEqual(splittype('type:'), ('type', ''))
1402 self.assertEqual(splittype('type:opaque:string'), ('type', 'opaque:string'))
1403
1404 def test_splithost(self):
1405 splithost = urllib.parse._splithost
1406 self.assertEqual(splithost('//www.example.org:80/foo/bar/baz.html'),
1407 ('www.example.org:80', '/foo/bar/baz.html'))
1408 self.assertEqual(splithost('//www.example.org:80'),
1409 ('www.example.org:80', ''))
1410 self.assertEqual(splithost('/foo/bar/baz.html'),
1411 (None, '/foo/bar/baz.html'))
1412
1413 # bpo-30500: # starts a fragment.
1414 self.assertEqual(splithost('//127.0.0.1#@host.com'),
1415 ('127.0.0.1', '/#@host.com'))
1416 self.assertEqual(splithost('//127.0.0.1#@host.com:80'),
1417 ('127.0.0.1', '/#@host.com:80'))
1418 self.assertEqual(splithost('//127.0.0.1:80#@host.com'),
1419 ('127.0.0.1:80', '/#@host.com'))
1420
1421 # Empty host is returned as empty string.
1422 self.assertEqual(splithost("///file"),
1423 ('', '/file'))
1424
1425 # Trailing semicolon, question mark and hash symbol are kept.
1426 self.assertEqual(splithost("//example.net/file;"),
1427 ('example.net', '/file;'))
1428 self.assertEqual(splithost("//example.net/file?"),
1429 ('example.net', '/file?'))
1430 self.assertEqual(splithost("//example.net/file#"),
1431 ('example.net', '/file#'))
1432
1433 def test_splituser(self):
1434 splituser = urllib.parse._splituser
1435 self.assertEqual(splituser('User:[email protected]:080'),
1436 ('User:Pass', 'www.python.org:080'))
1437 self.assertEqual(splituser('@www.python.org:080'),
1438 ('', 'www.python.org:080'))
1439 self.assertEqual(splituser('www.python.org:080'),
1440 (None, 'www.python.org:080'))
1441 self.assertEqual(splituser('User:Pass@'),
1442 ('User:Pass', ''))
1443 self.assertEqual(splituser('[email protected]:[email protected]:080'),
1444 ('[email protected]:Pass', 'www.python.org:080'))
1445
1446 def test_splitpasswd(self):
1447 # Some of the password examples are not sensible, but it is added to
1448 # confirming to RFC2617 and addressing issue4675.
1449 splitpasswd = urllib.parse._splitpasswd
1450 self.assertEqual(splitpasswd('user:ab'), ('user', 'ab'))
1451 self.assertEqual(splitpasswd('user:a\nb'), ('user', 'a\nb'))
1452 self.assertEqual(splitpasswd('user:a\tb'), ('user', 'a\tb'))
1453 self.assertEqual(splitpasswd('user:a\rb'), ('user', 'a\rb'))
1454 self.assertEqual(splitpasswd('user:a\fb'), ('user', 'a\fb'))
1455 self.assertEqual(splitpasswd('user:a\vb'), ('user', 'a\vb'))
1456 self.assertEqual(splitpasswd('user:a:b'), ('user', 'a:b'))
1457 self.assertEqual(splitpasswd('user:a b'), ('user', 'a b'))
1458 self.assertEqual(splitpasswd('user 2:ab'), ('user 2', 'ab'))
1459 self.assertEqual(splitpasswd('user+1:a+b'), ('user+1', 'a+b'))
1460 self.assertEqual(splitpasswd('user:'), ('user', ''))
1461 self.assertEqual(splitpasswd('user'), ('user', None))
1462 self.assertEqual(splitpasswd(':ab'), ('', 'ab'))
1463
1464 def test_splitport(self):
1465 splitport = urllib.parse._splitport
1466 self.assertEqual(splitport('parrot:88'), ('parrot', '88'))
1467 self.assertEqual(splitport('parrot'), ('parrot', None))
1468 self.assertEqual(splitport('parrot:'), ('parrot', None))
1469 self.assertEqual(splitport('127.0.0.1'), ('127.0.0.1', None))
1470 self.assertEqual(splitport('parrot:cheese'), ('parrot:cheese', None))
1471 self.assertEqual(splitport('[::1]:88'), ('[::1]', '88'))
1472 self.assertEqual(splitport('[::1]'), ('[::1]', None))
1473 self.assertEqual(splitport(':88'), ('', '88'))
1474
1475 def test_splitnport(self):
1476 splitnport = urllib.parse._splitnport
1477 self.assertEqual(splitnport('parrot:88'), ('parrot', 88))
1478 self.assertEqual(splitnport('parrot'), ('parrot', -1))
1479 self.assertEqual(splitnport('parrot', 55), ('parrot', 55))
1480 self.assertEqual(splitnport('parrot:'), ('parrot', -1))
1481 self.assertEqual(splitnport('parrot:', 55), ('parrot', 55))
1482 self.assertEqual(splitnport('127.0.0.1'), ('127.0.0.1', -1))
1483 self.assertEqual(splitnport('127.0.0.1', 55), ('127.0.0.1', 55))
1484 self.assertEqual(splitnport('parrot:cheese'), ('parrot', None))
1485 self.assertEqual(splitnport('parrot:cheese', 55), ('parrot', None))
1486 self.assertEqual(splitnport('parrot: +1_0 '), ('parrot', None))
1487
1488 def test_splitquery(self):
1489 # Normal cases are exercised by other tests; ensure that we also
1490 # catch cases with no port specified (testcase ensuring coverage)
1491 splitquery = urllib.parse._splitquery
1492 self.assertEqual(splitquery('http://python.org/fake?foo=bar'),
1493 ('http://python.org/fake', 'foo=bar'))
1494 self.assertEqual(splitquery('http://python.org/fake?foo=bar?'),
1495 ('http://python.org/fake?foo=bar', ''))
1496 self.assertEqual(splitquery('http://python.org/fake'),
1497 ('http://python.org/fake', None))
1498 self.assertEqual(splitquery('?foo=bar'), ('', 'foo=bar'))
1499
1500 def test_splittag(self):
1501 splittag = urllib.parse._splittag
1502 self.assertEqual(splittag('http://example.com?foo=bar#baz'),
1503 ('http://example.com?foo=bar', 'baz'))
1504 self.assertEqual(splittag('http://example.com?foo=bar#'),
1505 ('http://example.com?foo=bar', ''))
1506 self.assertEqual(splittag('#baz'), ('', 'baz'))
1507 self.assertEqual(splittag('http://example.com?foo=bar'),
1508 ('http://example.com?foo=bar', None))
1509 self.assertEqual(splittag('http://example.com?foo=bar#baz#boo'),
1510 ('http://example.com?foo=bar#baz', 'boo'))
1511
1512 def test_splitattr(self):
1513 splitattr = urllib.parse._splitattr
1514 self.assertEqual(splitattr('/path;attr1=value1;attr2=value2'),
1515 ('/path', ['attr1=value1', 'attr2=value2']))
1516 self.assertEqual(splitattr('/path;'), ('/path', ['']))
1517 self.assertEqual(splitattr(';attr1=value1;attr2=value2'),
1518 ('', ['attr1=value1', 'attr2=value2']))
1519 self.assertEqual(splitattr('/path'), ('/path', []))
1520
1521 def test_splitvalue(self):
1522 # Normal cases are exercised by other tests; test pathological cases
1523 # with no key/value pairs. (testcase ensuring coverage)
1524 splitvalue = urllib.parse._splitvalue
1525 self.assertEqual(splitvalue('foo=bar'), ('foo', 'bar'))
1526 self.assertEqual(splitvalue('foo='), ('foo', ''))
1527 self.assertEqual(splitvalue('=bar'), ('', 'bar'))
1528 self.assertEqual(splitvalue('foobar'), ('foobar', None))
1529 self.assertEqual(splitvalue('foo=bar=baz'), ('foo', 'bar=baz'))
1530
1531 def test_to_bytes(self):
1532 result = urllib.parse._to_bytes('http://www.python.org')
1533 self.assertEqual(result, 'http://www.python.org')
1534 self.assertRaises(UnicodeError, urllib.parse._to_bytes,
1535 'http://www.python.org/medi\u00e6val')
1536
1537 @support.subTests('wrapped_url',
1538 ('<URL:scheme://host/path>', '<scheme://host/path>',
1539 'URL:scheme://host/path', 'scheme://host/path'))
1540 def test_unwrap(self, wrapped_url):
1541 url = urllib.parse.unwrap(wrapped_url)
1542 self.assertEqual(url, 'scheme://host/path')
1543
1544
1545 class DeprecationTest(unittest.TestCase):
1546
1547 def test_Quoter_deprecation(self):
1548 with self.assertWarns(DeprecationWarning) as cm:
1549 old_class = urllib.parse.Quoter
1550 self.assertIs(old_class, urllib.parse._Quoter)
1551 self.assertIn('Quoter will be removed', str(cm.warning))
1552
1553 def test_splittype_deprecation(self):
1554 with self.assertWarns(DeprecationWarning) as cm:
1555 urllib.parse.splittype('')
1556 self.assertEqual(str(cm.warning),
1557 'urllib.parse.splittype() is deprecated as of 3.8, '
1558 'use urllib.parse.urlparse() instead')
1559
1560 def test_splithost_deprecation(self):
1561 with self.assertWarns(DeprecationWarning) as cm:
1562 urllib.parse.splithost('')
1563 self.assertEqual(str(cm.warning),
1564 'urllib.parse.splithost() is deprecated as of 3.8, '
1565 'use urllib.parse.urlparse() instead')
1566
1567 def test_splituser_deprecation(self):
1568 with self.assertWarns(DeprecationWarning) as cm:
1569 urllib.parse.splituser('')
1570 self.assertEqual(str(cm.warning),
1571 'urllib.parse.splituser() is deprecated as of 3.8, '
1572 'use urllib.parse.urlparse() instead')
1573
1574 def test_splitpasswd_deprecation(self):
1575 with self.assertWarns(DeprecationWarning) as cm:
1576 urllib.parse.splitpasswd('')
1577 self.assertEqual(str(cm.warning),
1578 'urllib.parse.splitpasswd() is deprecated as of 3.8, '
1579 'use urllib.parse.urlparse() instead')
1580
1581 def test_splitport_deprecation(self):
1582 with self.assertWarns(DeprecationWarning) as cm:
1583 urllib.parse.splitport('')
1584 self.assertEqual(str(cm.warning),
1585 'urllib.parse.splitport() is deprecated as of 3.8, '
1586 'use urllib.parse.urlparse() instead')
1587
1588 def test_splitnport_deprecation(self):
1589 with self.assertWarns(DeprecationWarning) as cm:
1590 urllib.parse.splitnport('')
1591 self.assertEqual(str(cm.warning),
1592 'urllib.parse.splitnport() is deprecated as of 3.8, '
1593 'use urllib.parse.urlparse() instead')
1594
1595 def test_splitquery_deprecation(self):
1596 with self.assertWarns(DeprecationWarning) as cm:
1597 urllib.parse.splitquery('')
1598 self.assertEqual(str(cm.warning),
1599 'urllib.parse.splitquery() is deprecated as of 3.8, '
1600 'use urllib.parse.urlparse() instead')
1601
1602 def test_splittag_deprecation(self):
1603 with self.assertWarns(DeprecationWarning) as cm:
1604 urllib.parse.splittag('')
1605 self.assertEqual(str(cm.warning),
1606 'urllib.parse.splittag() is deprecated as of 3.8, '
1607 'use urllib.parse.urlparse() instead')
1608
1609 def test_splitattr_deprecation(self):
1610 with self.assertWarns(DeprecationWarning) as cm:
1611 urllib.parse.splitattr('')
1612 self.assertEqual(str(cm.warning),
1613 'urllib.parse.splitattr() is deprecated as of 3.8, '
1614 'use urllib.parse.urlparse() instead')
1615
1616 def test_splitvalue_deprecation(self):
1617 with self.assertWarns(DeprecationWarning) as cm:
1618 urllib.parse.splitvalue('')
1619 self.assertEqual(str(cm.warning),
1620 'urllib.parse.splitvalue() is deprecated as of 3.8, '
1621 'use urllib.parse.parse_qsl() instead')
1622
1623 def test_to_bytes_deprecation(self):
1624 with self.assertWarns(DeprecationWarning) as cm:
1625 urllib.parse.to_bytes('')
1626 self.assertEqual(str(cm.warning),
1627 'urllib.parse.to_bytes() is deprecated as of 3.8')
1628
1629
1630 def str_encode(s):
1631 return s.encode('ascii')
1632
1633 def tuple_encode(t):
1634 return tuple(str_encode(x) for x in t)
1635
1636 if __name__ == "__main__":
1637 unittest.main()