Debian Codegraph @

lib-python/3/test/test_urlparse.py

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