test_urlparse.py 66 KB

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