logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

test_utils.py (100667B)


  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. # Allow direct execution
  5. import os
  6. import sys
  7. import unittest
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. # Various small unit tests
  10. import io
  11. import itertools
  12. import json
  13. import re
  14. import xml.etree.ElementTree
  15. from youtube_dl.utils import (
  16. age_restricted,
  17. args_to_str,
  18. base_url,
  19. caesar,
  20. clean_html,
  21. clean_podcast_url,
  22. date_from_str,
  23. DateRange,
  24. detect_exe_version,
  25. determine_ext,
  26. dict_get,
  27. encode_base_n,
  28. encode_compat_str,
  29. encodeFilename,
  30. escape_rfc3986,
  31. escape_url,
  32. expand_path,
  33. extract_attributes,
  34. ExtractorError,
  35. find_xpath_attr,
  36. fix_xml_ampersands,
  37. float_or_none,
  38. get_element_by_class,
  39. get_element_by_attribute,
  40. get_elements_by_class,
  41. get_elements_by_attribute,
  42. get_first,
  43. InAdvancePagedList,
  44. int_or_none,
  45. intlist_to_bytes,
  46. is_html,
  47. join_nonempty,
  48. js_to_json,
  49. LazyList,
  50. limit_length,
  51. lowercase_escape,
  52. merge_dicts,
  53. mimetype2ext,
  54. month_by_name,
  55. multipart_encode,
  56. ohdave_rsa_encrypt,
  57. OnDemandPagedList,
  58. orderedSet,
  59. parse_age_limit,
  60. parse_bitrate,
  61. parse_duration,
  62. parse_filesize,
  63. parse_codecs,
  64. parse_count,
  65. parse_iso8601,
  66. parse_resolution,
  67. parse_qs,
  68. pkcs1pad,
  69. prepend_extension,
  70. read_batch_urls,
  71. remove_start,
  72. remove_end,
  73. remove_quotes,
  74. replace_extension,
  75. rot47,
  76. sanitize_filename,
  77. sanitize_path,
  78. sanitize_url,
  79. sanitized_Request,
  80. shell_quote,
  81. smuggle_url,
  82. str_or_none,
  83. str_to_int,
  84. strip_jsonp,
  85. strip_or_none,
  86. subtitles_filename,
  87. T,
  88. timeconvert,
  89. traverse_obj,
  90. try_call,
  91. unescapeHTML,
  92. unified_strdate,
  93. unified_timestamp,
  94. unsmuggle_url,
  95. uppercase_escape,
  96. url_basename,
  97. url_or_none,
  98. urljoin,
  99. urlencode_postdata,
  100. urshift,
  101. update_url_query,
  102. variadic,
  103. version_tuple,
  104. xpath_with_ns,
  105. xpath_element,
  106. xpath_text,
  107. xpath_attr,
  108. render_table,
  109. match_str,
  110. parse_dfxp_time_expr,
  111. dfxp2srt,
  112. cli_option,
  113. cli_valueless_option,
  114. cli_bool_option,
  115. YoutubeDLHandler,
  116. )
  117. from youtube_dl.compat import (
  118. compat_chr,
  119. compat_etree_fromstring,
  120. compat_getenv,
  121. compat_os_name,
  122. compat_setenv,
  123. compat_str,
  124. compat_urlparse,
  125. )
  126. class TestUtil(unittest.TestCase):
  127. # yt-dlp shim
  128. def assertCountEqual(self, expected, got, msg='count should be the same'):
  129. return self.assertEqual(len(tuple(expected)), len(tuple(got)), msg=msg)
  130. def test_timeconvert(self):
  131. self.assertTrue(timeconvert('') is None)
  132. self.assertTrue(timeconvert('bougrg') is None)
  133. def test_sanitize_filename(self):
  134. self.assertEqual(sanitize_filename('abc'), 'abc')
  135. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  136. self.assertEqual(sanitize_filename('123'), '123')
  137. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  138. self.assertFalse('/' in sanitize_filename('abc/de///'))
  139. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  140. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  141. self.assertEqual('yes no', sanitize_filename('yes? no'))
  142. self.assertEqual('this - that', sanitize_filename('this: that'))
  143. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  144. aumlaut = 'ä'
  145. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  146. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  147. self.assertEqual(sanitize_filename(tests), tests)
  148. self.assertEqual(
  149. sanitize_filename('New World record at 0:12:34'),
  150. 'New World record at 0_12_34')
  151. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  152. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  153. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  154. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  155. forbidden = '"\0\\/'
  156. for fc in forbidden:
  157. for fbc in forbidden:
  158. self.assertTrue(fbc not in sanitize_filename(fc))
  159. def test_sanitize_filename_restricted(self):
  160. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  161. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  162. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  163. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  164. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  165. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  166. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  167. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  168. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  169. tests = 'aäb\u4e2d\u56fd\u7684c'
  170. self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
  171. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  172. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  173. for fc in forbidden:
  174. for fbc in forbidden:
  175. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  176. # Handle a common case more neatly
  177. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  178. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  179. # .. but make sure the file name is never empty
  180. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  181. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  182. self.assertEqual(sanitize_filename(
  183. 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
  184. 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
  185. def test_sanitize_ids(self):
  186. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  187. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  188. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  189. def test_sanitize_path(self):
  190. if sys.platform != 'win32':
  191. return
  192. self.assertEqual(sanitize_path('abc'), 'abc')
  193. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  194. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  195. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  196. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  197. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  198. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  199. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  200. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  201. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  202. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  203. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  204. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  205. self.assertEqual(
  206. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  207. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  208. self.assertEqual(
  209. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  210. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  211. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  212. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  213. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  214. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  215. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  216. self.assertEqual(sanitize_path('./abc'), 'abc')
  217. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  218. def test_sanitize_url(self):
  219. self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
  220. self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
  221. self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
  222. self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
  223. self.assertEqual(sanitize_url('foo bar'), 'foo bar')
  224. def test_sanitized_Request(self):
  225. self.assertFalse(sanitized_Request('http://foo.bar').has_header('Authorization'))
  226. self.assertFalse(sanitized_Request('http://:foo.bar').has_header('Authorization'))
  227. self.assertEqual(sanitized_Request('http://@foo.bar').get_header('Authorization'),
  228. 'Basic Og==')
  229. self.assertEqual(sanitized_Request('http://:pass@foo.bar').get_header('Authorization'),
  230. 'Basic OnBhc3M=')
  231. self.assertEqual(sanitized_Request('http://user:@foo.bar').get_header('Authorization'),
  232. 'Basic dXNlcjo=')
  233. self.assertEqual(sanitized_Request('http://user:pass@foo.bar').get_header('Authorization'),
  234. 'Basic dXNlcjpwYXNz')
  235. def test_expand_path(self):
  236. def env(var):
  237. return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
  238. compat_setenv('YOUTUBE_DL_EXPATH_PATH', 'expanded')
  239. self.assertEqual(expand_path(env('YOUTUBE_DL_EXPATH_PATH')), 'expanded')
  240. self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
  241. self.assertEqual(expand_path('~'), compat_getenv('HOME'))
  242. self.assertEqual(
  243. expand_path('~/%s' % env('YOUTUBE_DL_EXPATH_PATH')),
  244. '%s/expanded' % compat_getenv('HOME'))
  245. def test_prepend_extension(self):
  246. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  247. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  248. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  249. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  250. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  251. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  252. def test_replace_extension(self):
  253. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  254. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  255. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  256. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  257. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  258. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  259. def test_subtitles_filename(self):
  260. self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
  261. self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
  262. self.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
  263. def test_remove_start(self):
  264. self.assertEqual(remove_start(None, 'A - '), None)
  265. self.assertEqual(remove_start('A - B', 'A - '), 'B')
  266. self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
  267. def test_remove_end(self):
  268. self.assertEqual(remove_end(None, ' - B'), None)
  269. self.assertEqual(remove_end('A - B', ' - B'), 'A')
  270. self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
  271. def test_remove_quotes(self):
  272. self.assertEqual(remove_quotes(None), None)
  273. self.assertEqual(remove_quotes('"'), '"')
  274. self.assertEqual(remove_quotes("'"), "'")
  275. self.assertEqual(remove_quotes(';'), ';')
  276. self.assertEqual(remove_quotes('";'), '";')
  277. self.assertEqual(remove_quotes('""'), '')
  278. self.assertEqual(remove_quotes('";"'), ';')
  279. def test_ordered_set(self):
  280. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  281. self.assertEqual(orderedSet([]), [])
  282. self.assertEqual(orderedSet([1]), [1])
  283. # keep the list ordered
  284. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  285. def test_unescape_html(self):
  286. self.assertEqual(unescapeHTML('%20;'), '%20;')
  287. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  288. self.assertEqual(unescapeHTML('&#47;'), '/')
  289. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  290. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  291. self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
  292. # HTML5 entities
  293. self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
  294. def test_date_from_str(self):
  295. self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
  296. self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
  297. self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
  298. self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
  299. self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
  300. def test_daterange(self):
  301. _20century = DateRange("19000101", "20000101")
  302. self.assertFalse("17890714" in _20century)
  303. _ac = DateRange("00010101")
  304. self.assertTrue("19690721" in _ac)
  305. _firstmilenium = DateRange(end="10000101")
  306. self.assertTrue("07110427" in _firstmilenium)
  307. def test_unified_dates(self):
  308. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  309. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  310. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  311. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  312. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  313. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  314. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  315. self.assertEqual(
  316. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  317. '20141126')
  318. self.assertEqual(
  319. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  320. '20150202')
  321. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  322. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  323. self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
  324. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  325. self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
  326. self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
  327. self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
  328. self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
  329. self.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
  330. self.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
  331. def test_unified_timestamps(self):
  332. self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
  333. self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
  334. self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
  335. self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
  336. self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
  337. self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
  338. self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
  339. self.assertEqual(
  340. unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
  341. 1417001400)
  342. self.assertEqual(
  343. unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
  344. 1422902860)
  345. self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
  346. self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
  347. self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
  348. self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
  349. self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
  350. self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
  351. self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
  352. self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
  353. self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
  354. self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
  355. self.assertEqual(unified_timestamp('December 31 1969 20:00:01 EDT'), 1)
  356. self.assertEqual(unified_timestamp('Wednesday 31 December 1969 18:01:26 MDT'), 86)
  357. self.assertEqual(unified_timestamp('12/31/1969 20:01:18 EDT', False), 78)
  358. def test_determine_ext(self):
  359. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  360. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  361. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  362. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  363. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  364. self.assertEqual(determine_ext('foobar', None), None)
  365. def test_find_xpath_attr(self):
  366. testxml = '''<root>
  367. <node/>
  368. <node x="a"/>
  369. <node x="a" y="c" />
  370. <node x="b" y="d" />
  371. <node x="" />
  372. </root>'''
  373. doc = compat_etree_fromstring(testxml)
  374. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  375. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  376. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  377. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  378. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  379. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  380. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  381. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  382. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  383. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  384. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  385. def test_xpath_with_ns(self):
  386. testxml = '''<root xmlns:media="http://example.com/">
  387. <media:song>
  388. <media:author>The Author</media:author>
  389. <url>http://server.com/download.mp3</url>
  390. </media:song>
  391. </root>'''
  392. doc = compat_etree_fromstring(testxml)
  393. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  394. self.assertTrue(find('media:song') is not None)
  395. self.assertEqual(find('media:song/media:author').text, 'The Author')
  396. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  397. def test_xpath_element(self):
  398. doc = xml.etree.ElementTree.Element('root')
  399. div = xml.etree.ElementTree.SubElement(doc, 'div')
  400. p = xml.etree.ElementTree.SubElement(div, 'p')
  401. p.text = 'Foo'
  402. self.assertEqual(xpath_element(doc, 'div/p'), p)
  403. self.assertEqual(xpath_element(doc, ['div/p']), p)
  404. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  405. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  406. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  407. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  408. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  409. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  410. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  411. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  412. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  413. def test_xpath_text(self):
  414. testxml = '''<root>
  415. <div>
  416. <p>Foo</p>
  417. </div>
  418. </root>'''
  419. doc = compat_etree_fromstring(testxml)
  420. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  421. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  422. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  423. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  424. def test_xpath_attr(self):
  425. testxml = '''<root>
  426. <div>
  427. <p x="a">Foo</p>
  428. </div>
  429. </root>'''
  430. doc = compat_etree_fromstring(testxml)
  431. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  432. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  433. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  434. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  435. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  436. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  437. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  438. def test_smuggle_url(self):
  439. data = {"ö": "ö", "abc": [3]}
  440. url = 'https://foo.bar/baz?x=y#a'
  441. smug_url = smuggle_url(url, data)
  442. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  443. self.assertEqual(url, unsmug_url)
  444. self.assertEqual(data, unsmug_data)
  445. res_url, res_data = unsmuggle_url(url)
  446. self.assertEqual(res_url, url)
  447. self.assertEqual(res_data, None)
  448. smug_url = smuggle_url(url, {'a': 'b'})
  449. smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
  450. res_url, res_data = unsmuggle_url(smug_smug_url)
  451. self.assertEqual(res_url, url)
  452. self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
  453. def test_shell_quote(self):
  454. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  455. self.assertEqual(
  456. shell_quote(args),
  457. """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
  458. def test_float_or_none(self):
  459. self.assertEqual(float_or_none('42.42'), 42.42)
  460. self.assertEqual(float_or_none('42'), 42.0)
  461. self.assertEqual(float_or_none(''), None)
  462. self.assertEqual(float_or_none(None), None)
  463. self.assertEqual(float_or_none([]), None)
  464. self.assertEqual(float_or_none(set()), None)
  465. def test_int_or_none(self):
  466. self.assertEqual(int_or_none(42), 42)
  467. self.assertEqual(int_or_none('42'), 42)
  468. self.assertEqual(int_or_none(''), None)
  469. self.assertEqual(int_or_none(None), None)
  470. self.assertEqual(int_or_none([]), None)
  471. self.assertEqual(int_or_none(set()), None)
  472. self.assertEqual(int_or_none('42', base=8), 34)
  473. self.assertRaises(TypeError, int_or_none(42, base=8))
  474. def test_str_to_int(self):
  475. self.assertEqual(str_to_int('123,456'), 123456)
  476. self.assertEqual(str_to_int('123.456'), 123456)
  477. self.assertEqual(str_to_int(523), 523)
  478. # Python 3 has no long
  479. if sys.version_info < (3, 0):
  480. eval('self.assertEqual(str_to_int(123456L), 123456)')
  481. self.assertEqual(str_to_int('noninteger'), None)
  482. self.assertEqual(str_to_int([]), None)
  483. def test_url_basename(self):
  484. self.assertEqual(url_basename('http://foo.de/'), '')
  485. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  486. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  487. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  488. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  489. self.assertEqual(
  490. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  491. 'trailer.mp4')
  492. def test_base_url(self):
  493. self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
  494. self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
  495. self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
  496. self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
  497. self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
  498. def test_urljoin(self):
  499. self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  500. self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  501. self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  502. self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  503. self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
  504. self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  505. self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  506. self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  507. self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  508. self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  509. self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  510. self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  511. self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  512. self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  513. self.assertEqual(urljoin('http://foo.de/', None), None)
  514. self.assertEqual(urljoin('http://foo.de/', ''), None)
  515. self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
  516. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
  517. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
  518. self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
  519. def test_url_or_none(self):
  520. self.assertEqual(url_or_none(None), None)
  521. self.assertEqual(url_or_none(''), None)
  522. self.assertEqual(url_or_none('foo'), None)
  523. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  524. self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
  525. self.assertEqual(url_or_none('http$://foo.de'), None)
  526. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  527. self.assertEqual(url_or_none('//foo.de'), '//foo.de')
  528. self.assertEqual(url_or_none('s3://foo.de'), None)
  529. self.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
  530. self.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
  531. self.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
  532. self.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
  533. def test_parse_age_limit(self):
  534. self.assertEqual(parse_age_limit(None), None)
  535. self.assertEqual(parse_age_limit(False), None)
  536. self.assertEqual(parse_age_limit('invalid'), None)
  537. self.assertEqual(parse_age_limit(0), 0)
  538. self.assertEqual(parse_age_limit(18), 18)
  539. self.assertEqual(parse_age_limit(21), 21)
  540. self.assertEqual(parse_age_limit(22), None)
  541. self.assertEqual(parse_age_limit('18'), 18)
  542. self.assertEqual(parse_age_limit('18+'), 18)
  543. self.assertEqual(parse_age_limit('PG-13'), 13)
  544. self.assertEqual(parse_age_limit('TV-14'), 14)
  545. self.assertEqual(parse_age_limit('TV-MA'), 17)
  546. self.assertEqual(parse_age_limit('TV14'), 14)
  547. self.assertEqual(parse_age_limit('TV_G'), 0)
  548. def test_parse_duration(self):
  549. self.assertEqual(parse_duration(None), None)
  550. self.assertEqual(parse_duration(False), None)
  551. self.assertEqual(parse_duration('invalid'), None)
  552. self.assertEqual(parse_duration('1'), 1)
  553. self.assertEqual(parse_duration('1337:12'), 80232)
  554. self.assertEqual(parse_duration('9:12:43'), 33163)
  555. self.assertEqual(parse_duration('12:00'), 720)
  556. self.assertEqual(parse_duration('00:01:01'), 61)
  557. self.assertEqual(parse_duration('x:y'), None)
  558. self.assertEqual(parse_duration('3h11m53s'), 11513)
  559. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  560. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  561. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  562. self.assertEqual(parse_duration('62m45s'), 3765)
  563. self.assertEqual(parse_duration('6m59s'), 419)
  564. self.assertEqual(parse_duration('49s'), 49)
  565. self.assertEqual(parse_duration('0h0m0s'), 0)
  566. self.assertEqual(parse_duration('0m0s'), 0)
  567. self.assertEqual(parse_duration('0s'), 0)
  568. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  569. self.assertEqual(parse_duration('T30M38S'), 1838)
  570. self.assertEqual(parse_duration('5 s'), 5)
  571. self.assertEqual(parse_duration('3 min'), 180)
  572. self.assertEqual(parse_duration('2.5 hours'), 9000)
  573. self.assertEqual(parse_duration('02:03:04'), 7384)
  574. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  575. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  576. self.assertEqual(parse_duration('87 Min.'), 5220)
  577. self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
  578. self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
  579. self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
  580. def test_fix_xml_ampersands(self):
  581. self.assertEqual(
  582. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  583. self.assertEqual(
  584. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  585. '"&amp;x=y&amp;wrong;&amp;z=a')
  586. self.assertEqual(
  587. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  588. '&amp;&apos;&gt;&lt;&quot;')
  589. self.assertEqual(
  590. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  591. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  592. def test_paged_list(self):
  593. def testPL(size, pagesize, sliceargs, expected):
  594. def get_page(pagenum):
  595. firstid = pagenum * pagesize
  596. upto = min(size, pagenum * pagesize + pagesize)
  597. for i in range(firstid, upto):
  598. yield i
  599. pl = OnDemandPagedList(get_page, pagesize)
  600. got = pl.getslice(*sliceargs)
  601. self.assertEqual(got, expected)
  602. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  603. got = iapl.getslice(*sliceargs)
  604. self.assertEqual(got, expected)
  605. testPL(5, 2, (), [0, 1, 2, 3, 4])
  606. testPL(5, 2, (1,), [1, 2, 3, 4])
  607. testPL(5, 2, (2,), [2, 3, 4])
  608. testPL(5, 2, (4,), [4])
  609. testPL(5, 2, (0, 3), [0, 1, 2])
  610. testPL(5, 2, (1, 4), [1, 2, 3])
  611. testPL(5, 2, (2, 99), [2, 3, 4])
  612. testPL(5, 2, (20, 99), [])
  613. def test_read_batch_urls(self):
  614. f = io.StringIO('''\xef\xbb\xbf foo
  615. bar\r
  616. baz
  617. # More after this line\r
  618. ; or after this
  619. bam''')
  620. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  621. def test_urlencode_postdata(self):
  622. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  623. self.assertTrue(isinstance(data, bytes))
  624. def test_update_url_query(self):
  625. self.assertEqual(parse_qs(update_url_query(
  626. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  627. parse_qs('http://example.com/path?quality=HD&format=mp4'))
  628. self.assertEqual(parse_qs(update_url_query(
  629. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  630. parse_qs('http://example.com/path?system=LINUX&system=WINDOWS'))
  631. self.assertEqual(parse_qs(update_url_query(
  632. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  633. parse_qs('http://example.com/path?fields=id,formats,subtitles'))
  634. self.assertEqual(parse_qs(update_url_query(
  635. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  636. parse_qs('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  637. self.assertEqual(parse_qs(update_url_query(
  638. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  639. parse_qs('http://example.com/path'))
  640. self.assertEqual(parse_qs(update_url_query(
  641. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  642. parse_qs('http://example.com/path?system=LINUX'))
  643. self.assertEqual(parse_qs(update_url_query(
  644. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  645. parse_qs('http://example.com/path?fields=id,formats,subtitles'))
  646. self.assertEqual(parse_qs(update_url_query(
  647. 'http://example.com/path', {'width': 1080, 'height': 720})),
  648. parse_qs('http://example.com/path?width=1080&height=720'))
  649. self.assertEqual(parse_qs(update_url_query(
  650. 'http://example.com/path', {'bitrate': 5020.43})),
  651. parse_qs('http://example.com/path?bitrate=5020.43'))
  652. self.assertEqual(parse_qs(update_url_query(
  653. 'http://example.com/path', {'test': '第二行тест'})),
  654. parse_qs('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  655. def test_multipart_encode(self):
  656. self.assertEqual(
  657. multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
  658. b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
  659. self.assertEqual(
  660. multipart_encode({'欄位'.encode('utf-8'): '值'.encode('utf-8')}, boundary='AAAAAA')[0],
  661. b'--AAAAAA\r\nContent-Disposition: form-data; name="\xe6\xac\x84\xe4\xbd\x8d"\r\n\r\n\xe5\x80\xbc\r\n--AAAAAA--\r\n')
  662. self.assertRaises(
  663. ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
  664. def test_dict_get(self):
  665. FALSE_VALUES = {
  666. 'none': None,
  667. 'false': False,
  668. 'zero': 0,
  669. 'empty_string': '',
  670. 'empty_list': [],
  671. }
  672. d = FALSE_VALUES.copy()
  673. d['a'] = 42
  674. self.assertEqual(dict_get(d, 'a'), 42)
  675. self.assertEqual(dict_get(d, 'b'), None)
  676. self.assertEqual(dict_get(d, 'b', 42), 42)
  677. self.assertEqual(dict_get(d, ('a', )), 42)
  678. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  679. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  680. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  681. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  682. for key, false_value in FALSE_VALUES.items():
  683. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  684. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  685. def test_merge_dicts(self):
  686. self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
  687. self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
  688. self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
  689. self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
  690. self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
  691. self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
  692. self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
  693. self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  694. self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  695. def test_encode_compat_str(self):
  696. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  697. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  698. def test_parse_iso8601(self):
  699. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  700. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  701. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  702. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  703. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  704. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  705. def test_strip_jsonp(self):
  706. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  707. d = json.loads(stripped)
  708. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  709. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  710. d = json.loads(stripped)
  711. self.assertEqual(d, {'STATUS': 'OK'})
  712. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  713. d = json.loads(stripped)
  714. self.assertEqual(d, {'status': 'success'})
  715. stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
  716. d = json.loads(stripped)
  717. self.assertEqual(d, {'status': 'success'})
  718. stripped = strip_jsonp('window.cb && cb({"status": "success"});')
  719. d = json.loads(stripped)
  720. self.assertEqual(d, {'status': 'success'})
  721. stripped = strip_jsonp('({"status": "success"});')
  722. d = json.loads(stripped)
  723. self.assertEqual(d, {'status': 'success'})
  724. def test_strip_or_none(self):
  725. self.assertEqual(strip_or_none(' abc'), 'abc')
  726. self.assertEqual(strip_or_none('abc '), 'abc')
  727. self.assertEqual(strip_or_none(' abc '), 'abc')
  728. self.assertEqual(strip_or_none('\tabc\t'), 'abc')
  729. self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
  730. self.assertEqual(strip_or_none('abc'), 'abc')
  731. self.assertEqual(strip_or_none(''), '')
  732. self.assertEqual(strip_or_none(None), None)
  733. self.assertEqual(strip_or_none(42), None)
  734. self.assertEqual(strip_or_none([]), None)
  735. def test_uppercase_escape(self):
  736. self.assertEqual(uppercase_escape('aä'), 'aä')
  737. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  738. def test_lowercase_escape(self):
  739. self.assertEqual(lowercase_escape('aä'), 'aä')
  740. self.assertEqual(lowercase_escape('\\u0026'), '&')
  741. def test_limit_length(self):
  742. self.assertEqual(limit_length(None, 12), None)
  743. self.assertEqual(limit_length('foo', 12), 'foo')
  744. self.assertTrue(
  745. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  746. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  747. def test_mimetype2ext(self):
  748. self.assertEqual(mimetype2ext(None), None)
  749. self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
  750. self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
  751. self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
  752. self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
  753. self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
  754. self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
  755. self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
  756. def test_month_by_name(self):
  757. self.assertEqual(month_by_name(None), None)
  758. self.assertEqual(month_by_name('December', 'en'), 12)
  759. self.assertEqual(month_by_name('décembre', 'fr'), 12)
  760. self.assertEqual(month_by_name('December'), 12)
  761. self.assertEqual(month_by_name('décembre'), None)
  762. self.assertEqual(month_by_name('Unknown', 'unknown'), None)
  763. def test_parse_codecs(self):
  764. self.assertEqual(parse_codecs(''), {})
  765. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  766. 'vcodec': 'avc1.77.30',
  767. 'acodec': 'mp4a.40.2',
  768. })
  769. self.assertEqual(parse_codecs('mp4a.40.2'), {
  770. 'vcodec': 'none',
  771. 'acodec': 'mp4a.40.2',
  772. })
  773. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  774. 'vcodec': 'avc1.42001e',
  775. 'acodec': 'mp4a.40.5',
  776. })
  777. self.assertEqual(parse_codecs('avc3.640028'), {
  778. 'vcodec': 'avc3.640028',
  779. 'acodec': 'none',
  780. })
  781. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  782. 'vcodec': 'h264',
  783. 'acodec': 'aac',
  784. })
  785. self.assertEqual(parse_codecs('av01.0.05M.08'), {
  786. 'vcodec': 'av01.0.05M.08',
  787. 'acodec': 'none',
  788. })
  789. self.assertEqual(parse_codecs('theora, vorbis'), {
  790. 'vcodec': 'theora',
  791. 'acodec': 'vorbis',
  792. })
  793. self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
  794. 'vcodec': 'unknownvcodec',
  795. 'acodec': 'unknownacodec',
  796. })
  797. self.assertEqual(parse_codecs('unknown'), {})
  798. def test_escape_rfc3986(self):
  799. reserved = "!*'();:@&=+$,/?#[]"
  800. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  801. self.assertEqual(escape_rfc3986(reserved), reserved)
  802. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  803. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  804. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  805. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  806. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  807. def test_escape_url(self):
  808. self.assertEqual(
  809. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  810. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  811. )
  812. self.assertEqual(
  813. escape_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
  814. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  815. )
  816. self.assertEqual(
  817. escape_url('http://тест.рф/фрагмент'),
  818. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  819. )
  820. self.assertEqual(
  821. escape_url('http://тест.рф/абв?абв=абв#абв'),
  822. 'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  823. )
  824. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  825. def test_remove_dot_segments(self):
  826. def remove_dot_segments(p):
  827. q = '' if p.startswith('/') else '/'
  828. p = 'http://example.com' + q + p
  829. p = compat_urlparse.urlsplit(YoutubeDLHandler._fix_path(p)).path
  830. return p[1:] if q else p
  831. self.assertEqual(remove_dot_segments('/a/b/c/./../../g'), '/a/g')
  832. self.assertEqual(remove_dot_segments('mid/content=5/../6'), 'mid/6')
  833. self.assertEqual(remove_dot_segments('/ad/../cd'), '/cd')
  834. self.assertEqual(remove_dot_segments('/ad/../cd/'), '/cd/')
  835. self.assertEqual(remove_dot_segments('/..'), '/')
  836. self.assertEqual(remove_dot_segments('/./'), '/')
  837. self.assertEqual(remove_dot_segments('/./a'), '/a')
  838. self.assertEqual(remove_dot_segments('/abc/./.././d/././e/.././f/./../../ghi'), '/ghi')
  839. self.assertEqual(remove_dot_segments('/'), '/')
  840. self.assertEqual(remove_dot_segments('/t'), '/t')
  841. self.assertEqual(remove_dot_segments('t'), 't')
  842. self.assertEqual(remove_dot_segments(''), '')
  843. self.assertEqual(remove_dot_segments('/../a/b/c'), '/a/b/c')
  844. self.assertEqual(remove_dot_segments('../a'), 'a')
  845. self.assertEqual(remove_dot_segments('./a'), 'a')
  846. self.assertEqual(remove_dot_segments('.'), '')
  847. self.assertEqual(remove_dot_segments('////'), '////')
  848. def test_js_to_json_vars_strings(self):
  849. self.assertDictEqual(
  850. json.loads(js_to_json(
  851. '''{
  852. 'null': a,
  853. 'nullStr': b,
  854. 'true': c,
  855. 'trueStr': d,
  856. 'false': e,
  857. 'falseStr': f,
  858. 'unresolvedVar': g,
  859. }''',
  860. {
  861. 'a': 'null',
  862. 'b': '"null"',
  863. 'c': 'true',
  864. 'd': '"true"',
  865. 'e': 'false',
  866. 'f': '"false"',
  867. 'g': 'var',
  868. }
  869. )),
  870. {
  871. 'null': None,
  872. 'nullStr': 'null',
  873. 'true': True,
  874. 'trueStr': 'true',
  875. 'false': False,
  876. 'falseStr': 'false',
  877. 'unresolvedVar': 'var'
  878. }
  879. )
  880. self.assertDictEqual(
  881. json.loads(js_to_json(
  882. '''{
  883. 'int': a,
  884. 'intStr': b,
  885. 'float': c,
  886. 'floatStr': d,
  887. }''',
  888. {
  889. 'a': '123',
  890. 'b': '"123"',
  891. 'c': '1.23',
  892. 'd': '"1.23"',
  893. }
  894. )),
  895. {
  896. 'int': 123,
  897. 'intStr': '123',
  898. 'float': 1.23,
  899. 'floatStr': '1.23',
  900. }
  901. )
  902. self.assertDictEqual(
  903. json.loads(js_to_json(
  904. '''{
  905. 'object': a,
  906. 'objectStr': b,
  907. 'array': c,
  908. 'arrayStr': d,
  909. }''',
  910. {
  911. 'a': '{}',
  912. 'b': '"{}"',
  913. 'c': '[]',
  914. 'd': '"[]"',
  915. }
  916. )),
  917. {
  918. 'object': {},
  919. 'objectStr': '{}',
  920. 'array': [],
  921. 'arrayStr': '[]',
  922. }
  923. )
  924. def test_js_to_json_realworld(self):
  925. inp = '''{
  926. 'clip':{'provider':'pseudo'}
  927. }'''
  928. self.assertEqual(js_to_json(inp), '''{
  929. "clip":{"provider":"pseudo"}
  930. }''')
  931. json.loads(js_to_json(inp))
  932. inp = '''{
  933. 'playlist':[{'controls':{'all':null}}]
  934. }'''
  935. self.assertEqual(js_to_json(inp), '''{
  936. "playlist":[{"controls":{"all":null}}]
  937. }''')
  938. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  939. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  940. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  941. json_code = js_to_json(inp)
  942. self.assertEqual(json.loads(json_code), json.loads(inp))
  943. inp = '''{
  944. 0:{src:'skipped', type: 'application/dash+xml'},
  945. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  946. }'''
  947. self.assertEqual(js_to_json(inp), '''{
  948. "0":{"src":"skipped", "type": "application/dash+xml"},
  949. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  950. }''')
  951. inp = '''{"foo":101}'''
  952. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  953. inp = '''{"duration": "00:01:07"}'''
  954. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  955. inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
  956. self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
  957. def test_js_to_json_edgecases(self):
  958. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  959. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  960. on = js_to_json('{"abc": true}')
  961. self.assertEqual(json.loads(on), {'abc': True})
  962. # Ignore JavaScript code as well
  963. on = js_to_json('''{
  964. "x": 1,
  965. y: "a",
  966. z: some.code
  967. }''')
  968. d = json.loads(on)
  969. self.assertEqual(d['x'], 1)
  970. self.assertEqual(d['y'], 'a')
  971. # Just drop ! prefix for now though this results in a wrong value
  972. on = js_to_json('''{
  973. a: !0,
  974. b: !1,
  975. c: !!0,
  976. d: !!42.42,
  977. e: !!![],
  978. f: !"abc",
  979. g: !"",
  980. !42: 42
  981. }''')
  982. self.assertEqual(json.loads(on), {
  983. 'a': True,
  984. 'b': False,
  985. 'c': False,
  986. 'd': True,
  987. 'e': [],
  988. 'f': "abc",
  989. 'g': "",
  990. '42': 42
  991. })
  992. on = js_to_json('["abc", "def",]')
  993. self.assertEqual(json.loads(on), ['abc', 'def'])
  994. on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
  995. self.assertEqual(json.loads(on), ['abc', 'def'])
  996. on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
  997. self.assertEqual(json.loads(on), ['abc', 'def'])
  998. on = js_to_json('{"abc": "def",}')
  999. self.assertEqual(json.loads(on), {'abc': 'def'})
  1000. on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
  1001. self.assertEqual(json.loads(on), {'abc': 'def'})
  1002. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  1003. self.assertEqual(json.loads(on), {'0': ',]'})
  1004. on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
  1005. self.assertEqual(json.loads(on), {'0': ',]'})
  1006. on = js_to_json('{ 0: // comment\n1 }')
  1007. self.assertEqual(json.loads(on), {'0': 1})
  1008. on = js_to_json(r'["<p>x<\/p>"]')
  1009. self.assertEqual(json.loads(on), ['<p>x</p>'])
  1010. on = js_to_json(r'["\xaa"]')
  1011. self.assertEqual(json.loads(on), ['\u00aa'])
  1012. on = js_to_json("['a\\\nb']")
  1013. self.assertEqual(json.loads(on), ['ab'])
  1014. on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
  1015. self.assertEqual(json.loads(on), ['ab'])
  1016. on = js_to_json('{0xff:0xff}')
  1017. self.assertEqual(json.loads(on), {'255': 255})
  1018. on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
  1019. self.assertEqual(json.loads(on), {'255': 255})
  1020. on = js_to_json('{077:077}')
  1021. self.assertEqual(json.loads(on), {'63': 63})
  1022. on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
  1023. self.assertEqual(json.loads(on), {'63': 63})
  1024. on = js_to_json('{42:42}')
  1025. self.assertEqual(json.loads(on), {'42': 42})
  1026. on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
  1027. self.assertEqual(json.loads(on), {'42': 42})
  1028. on = js_to_json('{42:4.2e1}')
  1029. self.assertEqual(json.loads(on), {'42': 42.0})
  1030. on = js_to_json('{ "0x40": "0x40" }')
  1031. self.assertEqual(json.loads(on), {'0x40': '0x40'})
  1032. on = js_to_json('{ "040": "040" }')
  1033. self.assertEqual(json.loads(on), {'040': '040'})
  1034. on = js_to_json('[1,//{},\n2]')
  1035. self.assertEqual(json.loads(on), [1, 2])
  1036. on = js_to_json(r'"\^\$\#"')
  1037. self.assertEqual(json.loads(on), R'^$#', msg='Unnecessary escapes should be stripped')
  1038. on = js_to_json('\'"\\""\'')
  1039. self.assertEqual(json.loads(on), '"""', msg='Unnecessary quote escape should be escaped')
  1040. def test_js_to_json_malformed(self):
  1041. self.assertEqual(js_to_json('42a1'), '42"a1"')
  1042. self.assertEqual(js_to_json('42a-1'), '42"a"-1')
  1043. def test_js_to_json_template_literal(self):
  1044. self.assertEqual(js_to_json('`Hello ${name}`', {'name': '"world"'}), '"Hello world"')
  1045. self.assertEqual(js_to_json('`${name}${name}`', {'name': '"X"'}), '"XX"')
  1046. self.assertEqual(js_to_json('`${name}${name}`', {'name': '5'}), '"55"')
  1047. self.assertEqual(js_to_json('`${name}"${name}"`', {'name': '5'}), '"5\\"5\\""')
  1048. self.assertEqual(js_to_json('`${name}`', {}), '"name"')
  1049. def test_extract_attributes(self):
  1050. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  1051. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  1052. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  1053. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  1054. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  1055. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  1056. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  1057. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  1058. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  1059. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  1060. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  1061. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  1062. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  1063. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  1064. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  1065. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  1066. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  1067. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  1068. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  1069. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  1070. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  1071. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  1072. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  1073. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  1074. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  1075. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  1076. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  1077. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  1078. # "Narrow" Python builds don't support unicode code points outside BMP.
  1079. try:
  1080. compat_chr(0x10000)
  1081. supports_outside_bmp = True
  1082. except ValueError:
  1083. supports_outside_bmp = False
  1084. if supports_outside_bmp:
  1085. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  1086. # Malformed HTML should not break attributes extraction on older Python
  1087. self.assertEqual(extract_attributes('<mal"formed/>'), {})
  1088. def test_clean_html(self):
  1089. self.assertEqual(clean_html('a:\nb'), 'a: b')
  1090. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  1091. self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
  1092. def test_intlist_to_bytes(self):
  1093. self.assertEqual(
  1094. intlist_to_bytes([0, 1, 127, 128, 255]),
  1095. b'\x00\x01\x7f\x80\xff')
  1096. def test_args_to_str(self):
  1097. self.assertEqual(
  1098. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  1099. 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
  1100. )
  1101. def test_parse_filesize(self):
  1102. self.assertEqual(parse_filesize(None), None)
  1103. self.assertEqual(parse_filesize(''), None)
  1104. self.assertEqual(parse_filesize('91 B'), 91)
  1105. self.assertEqual(parse_filesize('foobar'), None)
  1106. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  1107. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  1108. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  1109. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  1110. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  1111. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  1112. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  1113. def test_parse_count(self):
  1114. self.assertEqual(parse_count(None), None)
  1115. self.assertEqual(parse_count(''), None)
  1116. self.assertEqual(parse_count('0'), 0)
  1117. self.assertEqual(parse_count('1000'), 1000)
  1118. self.assertEqual(parse_count('1.000'), 1000)
  1119. self.assertEqual(parse_count('1.1k'), 1100)
  1120. self.assertEqual(parse_count('1.1kk'), 1100000)
  1121. self.assertEqual(parse_count('1.1kk '), 1100000)
  1122. self.assertEqual(parse_count('1.1kk views'), 1100000)
  1123. def test_parse_resolution(self):
  1124. self.assertEqual(parse_resolution(None), {})
  1125. self.assertEqual(parse_resolution(''), {})
  1126. self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
  1127. self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
  1128. self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
  1129. self.assertEqual(parse_resolution('720p'), {'height': 720})
  1130. self.assertEqual(parse_resolution('4k'), {'height': 2160})
  1131. self.assertEqual(parse_resolution('8K'), {'height': 4320})
  1132. def test_parse_bitrate(self):
  1133. self.assertEqual(parse_bitrate(None), None)
  1134. self.assertEqual(parse_bitrate(''), None)
  1135. self.assertEqual(parse_bitrate('300kbps'), 300)
  1136. self.assertEqual(parse_bitrate('1500kbps'), 1500)
  1137. self.assertEqual(parse_bitrate('300 kbps'), 300)
  1138. def test_version_tuple(self):
  1139. self.assertEqual(version_tuple('1'), (1,))
  1140. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  1141. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  1142. def test_detect_exe_version(self):
  1143. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  1144. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  1145. configuration: --prefix=/usr --extra-'''), '1.2.1')
  1146. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  1147. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  1148. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  1149. Trying to open render node...
  1150. Success at /dev/dri/renderD128.
  1151. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  1152. def test_age_restricted(self):
  1153. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  1154. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  1155. self.assertFalse(age_restricted(8, 10))
  1156. self.assertTrue(age_restricted(18, 14))
  1157. self.assertFalse(age_restricted(18, 18))
  1158. def test_is_html(self):
  1159. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  1160. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  1161. self.assertTrue(is_html( # UTF-8 with BOM
  1162. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  1163. self.assertTrue(is_html( # UTF-16-LE
  1164. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  1165. ))
  1166. self.assertTrue(is_html( # UTF-16-BE
  1167. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  1168. ))
  1169. self.assertTrue(is_html( # UTF-32-BE
  1170. b'\x00\x00\xFE\xFF\x00\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4'))
  1171. self.assertTrue(is_html( # UTF-32-LE
  1172. b'\xFF\xFE\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4\x00\x00\x00'))
  1173. def test_render_table(self):
  1174. self.assertEqual(
  1175. render_table(
  1176. ['a', 'bcd'],
  1177. [[123, 4], [9999, 51]]),
  1178. 'a bcd\n'
  1179. '123 4\n'
  1180. '9999 51')
  1181. def test_match_str(self):
  1182. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  1183. self.assertFalse(match_str('xy', {'x': 1200}))
  1184. self.assertTrue(match_str('!xy', {'x': 1200}))
  1185. self.assertTrue(match_str('x', {'x': 1200}))
  1186. self.assertFalse(match_str('!x', {'x': 1200}))
  1187. self.assertTrue(match_str('x', {'x': 0}))
  1188. self.assertFalse(match_str('x>0', {'x': 0}))
  1189. self.assertFalse(match_str('x>0', {}))
  1190. self.assertTrue(match_str('x>?0', {}))
  1191. self.assertTrue(match_str('x>1K', {'x': 1200}))
  1192. self.assertFalse(match_str('x>2K', {'x': 1200}))
  1193. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  1194. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  1195. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  1196. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  1197. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  1198. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  1199. self.assertFalse(match_str(
  1200. 'like_count > 100 & dislike_count <? 50 & description',
  1201. {'like_count': 90, 'description': 'foo'}))
  1202. self.assertTrue(match_str(
  1203. 'like_count > 100 & dislike_count <? 50 & description',
  1204. {'like_count': 190, 'description': 'foo'}))
  1205. self.assertFalse(match_str(
  1206. 'like_count > 100 & dislike_count <? 50 & description',
  1207. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  1208. self.assertFalse(match_str(
  1209. 'like_count > 100 & dislike_count <? 50 & description',
  1210. {'like_count': 190, 'dislike_count': 10}))
  1211. self.assertTrue(match_str('is_live', {'is_live': True}))
  1212. self.assertFalse(match_str('is_live', {'is_live': False}))
  1213. self.assertFalse(match_str('is_live', {'is_live': None}))
  1214. self.assertFalse(match_str('is_live', {}))
  1215. self.assertFalse(match_str('!is_live', {'is_live': True}))
  1216. self.assertTrue(match_str('!is_live', {'is_live': False}))
  1217. self.assertTrue(match_str('!is_live', {'is_live': None}))
  1218. self.assertTrue(match_str('!is_live', {}))
  1219. self.assertTrue(match_str('title', {'title': 'abc'}))
  1220. self.assertTrue(match_str('title', {'title': ''}))
  1221. self.assertFalse(match_str('!title', {'title': 'abc'}))
  1222. self.assertFalse(match_str('!title', {'title': ''}))
  1223. def test_parse_dfxp_time_expr(self):
  1224. self.assertEqual(parse_dfxp_time_expr(None), None)
  1225. self.assertEqual(parse_dfxp_time_expr(''), None)
  1226. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  1227. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  1228. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  1229. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  1230. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  1231. def test_dfxp2srt(self):
  1232. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  1233. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1234. <body>
  1235. <div xml:lang="en">
  1236. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  1237. <p begin="1" end="2">第二行<br/>♪♪</p>
  1238. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  1239. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  1240. <p begin="-1" end="-1">Ignore, two</p>
  1241. <p begin="3" dur="-1">Ignored, three</p>
  1242. </div>
  1243. </body>
  1244. </tt>'''.encode('utf-8')
  1245. srt_data = '''1
  1246. 00:00:00,000 --> 00:00:01,000
  1247. The following line contains Chinese characters and special symbols
  1248. 2
  1249. 00:00:01,000 --> 00:00:02,000
  1250. 第二行
  1251. ♪♪
  1252. 3
  1253. 00:00:02,000 --> 00:00:03,000
  1254. Third
  1255. Line
  1256. '''
  1257. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  1258. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  1259. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1260. <body>
  1261. <div xml:lang="en">
  1262. <p begin="0" end="1">The first line</p>
  1263. </div>
  1264. </body>
  1265. </tt>'''.encode('utf-8')
  1266. srt_data = '''1
  1267. 00:00:00,000 --> 00:00:01,000
  1268. The first line
  1269. '''
  1270. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  1271. dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
  1272. <tt xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:ttp="http://www.w3.org/2006/10/ttaf1#parameter" ttp:timeBase="media" xmlns:tts="http://www.w3.org/2006/10/ttaf1#style" xml:lang="en" xmlns:ttm="http://www.w3.org/2006/10/ttaf1#metadata">
  1273. <head>
  1274. <styling>
  1275. <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
  1276. <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
  1277. <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
  1278. <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
  1279. </styling>
  1280. </head>
  1281. <body tts:textAlign="center" style="s0">
  1282. <div>
  1283. <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
  1284. <p style="s2" begin="00:00:02.08" id="p0" end="00:00:05.84"><span tts:color="lime">part 1<br /></span><span tts:color="cyan">part 2</span></p>
  1285. <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
  1286. <p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
  1287. </div>
  1288. </body>
  1289. </tt>'''.encode('utf-8')
  1290. srt_data = '''1
  1291. 00:00:02,080 --> 00:00:05,839
  1292. <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
  1293. 2
  1294. 00:00:02,080 --> 00:00:05,839
  1295. <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
  1296. </font>part 2</font></b>
  1297. 3
  1298. 00:00:05,839 --> 00:00:09,560
  1299. <u><font color="lime">line 3
  1300. part 3</font></u>
  1301. 4
  1302. 00:00:09,560 --> 00:00:12,359
  1303. <i><u><font color="yellow"><font color="lime">inner
  1304. </font>style</font></u></i>
  1305. '''
  1306. self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
  1307. dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
  1308. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1309. <body>
  1310. <div xml:lang="en">
  1311. <p begin="0" end="1">Line 1</p>
  1312. <p begin="1" end="2">第二行</p>
  1313. </div>
  1314. </body>
  1315. </tt>'''.encode('utf-16')
  1316. srt_data = '''1
  1317. 00:00:00,000 --> 00:00:01,000
  1318. Line 1
  1319. 2
  1320. 00:00:01,000 --> 00:00:02,000
  1321. 第二行
  1322. '''
  1323. self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
  1324. def test_cli_option(self):
  1325. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  1326. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  1327. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  1328. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  1329. def test_cli_valueless_option(self):
  1330. self.assertEqual(cli_valueless_option(
  1331. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  1332. self.assertEqual(cli_valueless_option(
  1333. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  1334. self.assertEqual(cli_valueless_option(
  1335. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  1336. self.assertEqual(cli_valueless_option(
  1337. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  1338. self.assertEqual(cli_valueless_option(
  1339. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  1340. self.assertEqual(cli_valueless_option(
  1341. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  1342. def test_cli_bool_option(self):
  1343. self.assertEqual(
  1344. cli_bool_option(
  1345. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  1346. ['--no-check-certificate', 'true'])
  1347. self.assertEqual(
  1348. cli_bool_option(
  1349. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  1350. ['--no-check-certificate=true'])
  1351. self.assertEqual(
  1352. cli_bool_option(
  1353. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1354. ['--check-certificate', 'false'])
  1355. self.assertEqual(
  1356. cli_bool_option(
  1357. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1358. ['--check-certificate=false'])
  1359. self.assertEqual(
  1360. cli_bool_option(
  1361. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1362. ['--check-certificate', 'true'])
  1363. self.assertEqual(
  1364. cli_bool_option(
  1365. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1366. ['--check-certificate=true'])
  1367. self.assertEqual(
  1368. cli_bool_option(
  1369. {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1370. [])
  1371. def test_ohdave_rsa_encrypt(self):
  1372. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  1373. e = 65537
  1374. self.assertEqual(
  1375. ohdave_rsa_encrypt(b'aa111222', e, N),
  1376. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  1377. def test_pkcs1pad(self):
  1378. data = [1, 2, 3]
  1379. padded_data = pkcs1pad(data, 32)
  1380. self.assertEqual(padded_data[:2], [0, 2])
  1381. self.assertEqual(padded_data[28:], [0, 1, 2, 3])
  1382. self.assertRaises(ValueError, pkcs1pad, data, 8)
  1383. def test_encode_base_n(self):
  1384. self.assertEqual(encode_base_n(0, 30), '0')
  1385. self.assertEqual(encode_base_n(80, 30), '2k')
  1386. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  1387. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  1388. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  1389. self.assertRaises(ValueError, encode_base_n, 0, 70)
  1390. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  1391. def test_caesar(self):
  1392. self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
  1393. self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
  1394. self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
  1395. self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
  1396. self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
  1397. self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
  1398. self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
  1399. self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
  1400. def test_rot47(self):
  1401. self.assertEqual(rot47('youtube-dl'), r'J@FEF36\5=')
  1402. self.assertEqual(rot47('YOUTUBE-DL'), r'*~&%&qt\s{')
  1403. def test_urshift(self):
  1404. self.assertEqual(urshift(3, 1), 1)
  1405. self.assertEqual(urshift(-3, 1), 2147483646)
  1406. def test_get_element_by_class(self):
  1407. html = '''
  1408. <span class="foo bar">nice</span>
  1409. '''
  1410. self.assertEqual(get_element_by_class('foo', html), 'nice')
  1411. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1412. def test_get_element_by_attribute(self):
  1413. html = '''
  1414. <span class="foo bar">nice</span>
  1415. '''
  1416. self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
  1417. self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
  1418. self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
  1419. html = '''
  1420. <div itemprop="author" itemscope>foo</div>
  1421. '''
  1422. self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
  1423. def test_get_elements_by_class(self):
  1424. html = '''
  1425. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1426. '''
  1427. self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
  1428. self.assertEqual(get_elements_by_class('no-such-class', html), [])
  1429. def test_get_elements_by_attribute(self):
  1430. html = '''
  1431. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1432. '''
  1433. self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
  1434. self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
  1435. self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
  1436. def test_clean_podcast_url(self):
  1437. self.assertEqual(clean_podcast_url('https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW7835899191.mp3'), 'https://traffic.megaphone.fm/HSW7835899191.mp3')
  1438. self.assertEqual(clean_podcast_url('https://play.podtrac.com/npr-344098539/edge1.pod.npr.org/anon.npr-podcasts/podcast/npr/waitwait/2020/10/20201003_waitwait_wwdtmpodcast201003-015621a5-f035-4eca-a9a1-7c118d90bc3c.mp3'), 'https://edge1.pod.npr.org/anon.npr-podcasts/podcast/npr/waitwait/2020/10/20201003_waitwait_wwdtmpodcast201003-015621a5-f035-4eca-a9a1-7c118d90bc3c.mp3')
  1439. def test_LazyList(self):
  1440. it = list(range(10))
  1441. self.assertEqual(list(LazyList(it)), it)
  1442. self.assertEqual(LazyList(it).exhaust(), it)
  1443. self.assertEqual(LazyList(it)[5], it[5])
  1444. self.assertEqual(LazyList(it)[5:], it[5:])
  1445. self.assertEqual(LazyList(it)[:5], it[:5])
  1446. self.assertEqual(LazyList(it)[::2], it[::2])
  1447. self.assertEqual(LazyList(it)[1::2], it[1::2])
  1448. self.assertEqual(LazyList(it)[5::-1], it[5::-1])
  1449. self.assertEqual(LazyList(it)[6:2:-2], it[6:2:-2])
  1450. self.assertEqual(LazyList(it)[::-1], it[::-1])
  1451. self.assertTrue(LazyList(it))
  1452. self.assertFalse(LazyList(range(0)))
  1453. self.assertEqual(len(LazyList(it)), len(it))
  1454. self.assertEqual(repr(LazyList(it)), repr(it))
  1455. self.assertEqual(compat_str(LazyList(it)), compat_str(it))
  1456. self.assertEqual(list(LazyList(it, reverse=True)), it[::-1])
  1457. self.assertEqual(list(reversed(LazyList(it))[::-1]), it)
  1458. self.assertEqual(list(reversed(LazyList(it))[1:3:7]), it[::-1][1:3:7])
  1459. def test_LazyList_laziness(self):
  1460. def test(ll, idx, val, cache):
  1461. self.assertEqual(ll[idx], val)
  1462. self.assertEqual(ll._cache, list(cache))
  1463. ll = LazyList(range(10))
  1464. test(ll, 0, 0, range(1))
  1465. test(ll, 5, 5, range(6))
  1466. test(ll, -3, 7, range(10))
  1467. ll = LazyList(range(10), reverse=True)
  1468. test(ll, -1, 0, range(1))
  1469. test(ll, 3, 6, range(10))
  1470. ll = LazyList(itertools.count())
  1471. test(ll, 10, 10, range(11))
  1472. ll = reversed(ll)
  1473. test(ll, -15, 14, range(15))
  1474. def test_try_call(self):
  1475. def total(*x, **kwargs):
  1476. return sum(x) + sum(kwargs.values())
  1477. self.assertEqual(try_call(None), None,
  1478. msg='not a fn should give None')
  1479. self.assertEqual(try_call(lambda: 1), 1,
  1480. msg='int fn with no expected_type should give int')
  1481. self.assertEqual(try_call(lambda: 1, expected_type=int), 1,
  1482. msg='int fn with expected_type int should give int')
  1483. self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
  1484. msg='int fn with wrong expected_type should give None')
  1485. self.assertEqual(try_call(total, args=(0, 1, 0, ), expected_type=int), 1,
  1486. msg='fn should accept arglist')
  1487. self.assertEqual(try_call(total, kwargs={'a': 0, 'b': 1, 'c': 0}, expected_type=int), 1,
  1488. msg='fn should accept kwargs')
  1489. self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
  1490. msg='int fn with no expected_type should give None')
  1491. self.assertEqual(try_call(lambda x: {}, total, args=(42, ), expected_type=int), 42,
  1492. msg='expect first int result with expected_type int')
  1493. def test_variadic(self):
  1494. self.assertEqual(variadic(None), (None, ))
  1495. self.assertEqual(variadic('spam'), ('spam', ))
  1496. self.assertEqual(variadic('spam', allowed_types=dict), 'spam')
  1497. self.assertEqual(variadic('spam', allowed_types=[dict]), 'spam')
  1498. def test_traverse_obj(self):
  1499. str = compat_str
  1500. _TEST_DATA = {
  1501. 100: 100,
  1502. 1.2: 1.2,
  1503. 'str': 'str',
  1504. 'None': None,
  1505. '...': Ellipsis,
  1506. 'urls': [
  1507. {'index': 0, 'url': 'https://www.example.com/0'},
  1508. {'index': 1, 'url': 'https://www.example.com/1'},
  1509. ],
  1510. 'data': (
  1511. {'index': 2},
  1512. {'index': 3},
  1513. ),
  1514. 'dict': {},
  1515. }
  1516. # define a pukka Iterable
  1517. def iter_range(stop):
  1518. for from_ in range(stop):
  1519. yield from_
  1520. # Test base functionality
  1521. self.assertEqual(traverse_obj(_TEST_DATA, ('str',)), 'str',
  1522. msg='allow tuple path')
  1523. self.assertEqual(traverse_obj(_TEST_DATA, ['str']), 'str',
  1524. msg='allow list path')
  1525. self.assertEqual(traverse_obj(_TEST_DATA, (value for value in ("str",))), 'str',
  1526. msg='allow iterable path')
  1527. self.assertEqual(traverse_obj(_TEST_DATA, 'str'), 'str',
  1528. msg='single items should be treated as a path')
  1529. self.assertEqual(traverse_obj(_TEST_DATA, None), _TEST_DATA)
  1530. self.assertEqual(traverse_obj(_TEST_DATA, 100), 100)
  1531. self.assertEqual(traverse_obj(_TEST_DATA, 1.2), 1.2)
  1532. # Test Ellipsis behavior
  1533. self.assertCountEqual(traverse_obj(_TEST_DATA, Ellipsis),
  1534. (item for item in _TEST_DATA.values() if item not in (None, {})),
  1535. msg='`...` should give all non-discarded values')
  1536. self.assertCountEqual(traverse_obj(_TEST_DATA, ('urls', 0, Ellipsis)), _TEST_DATA['urls'][0].values(),
  1537. msg='`...` selection for dicts should select all values')
  1538. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, Ellipsis, 'url')),
  1539. ['https://www.example.com/0', 'https://www.example.com/1'],
  1540. msg='nested `...` queries should work')
  1541. self.assertCountEqual(traverse_obj(_TEST_DATA, (Ellipsis, Ellipsis, 'index')), iter_range(4),
  1542. msg='`...` query result should be flattened')
  1543. self.assertEqual(traverse_obj(iter(range(4)), Ellipsis), list(range(4)),
  1544. msg='`...` should accept iterables')
  1545. # Test function as key
  1546. self.assertEqual(traverse_obj(_TEST_DATA, lambda x, y: x == 'urls' and isinstance(y, list)),
  1547. [_TEST_DATA['urls']],
  1548. msg='function as query key should perform a filter based on (key, value)')
  1549. self.assertCountEqual(traverse_obj(_TEST_DATA, lambda _, x: isinstance(x[0], str)), set(('str',)),
  1550. msg='exceptions in the query function should be caught')
  1551. self.assertEqual(traverse_obj(iter(range(4)), lambda _, x: x % 2 == 0), [0, 2],
  1552. msg='function key should accept iterables')
  1553. if __debug__:
  1554. with self.assertRaises(Exception, msg='Wrong function signature should raise in debug'):
  1555. traverse_obj(_TEST_DATA, lambda a: Ellipsis)
  1556. with self.assertRaises(Exception, msg='Wrong function signature should raise in debug'):
  1557. traverse_obj(_TEST_DATA, lambda a, b, c: Ellipsis)
  1558. # Test set as key (transformation/type, like `expected_type`)
  1559. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str.upper), )), ['STR'],
  1560. msg='Function in set should be a transformation')
  1561. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str))), ['str'],
  1562. msg='Type in set should be a type filter')
  1563. self.assertEqual(traverse_obj(_TEST_DATA, T(dict)), _TEST_DATA,
  1564. msg='A single set should be wrapped into a path')
  1565. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str.upper))), ['STR'],
  1566. msg='Transformation function should not raise')
  1567. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, T(str_or_none))),
  1568. [item for item in map(str_or_none, _TEST_DATA.values()) if item is not None],
  1569. msg='Function in set should be a transformation')
  1570. if __debug__:
  1571. with self.assertRaises(Exception, msg='Sets with length != 1 should raise in debug'):
  1572. traverse_obj(_TEST_DATA, set())
  1573. with self.assertRaises(Exception, msg='Sets with length != 1 should raise in debug'):
  1574. traverse_obj(_TEST_DATA, set((str.upper, str)))
  1575. # Test `slice` as a key
  1576. _SLICE_DATA = [0, 1, 2, 3, 4]
  1577. self.assertEqual(traverse_obj(_TEST_DATA, ('dict', slice(1))), None,
  1578. msg='slice on a dictionary should not throw')
  1579. self.assertEqual(traverse_obj(_SLICE_DATA, slice(1)), _SLICE_DATA[:1],
  1580. msg='slice key should apply slice to sequence')
  1581. self.assertEqual(traverse_obj(_SLICE_DATA, slice(1, 2)), _SLICE_DATA[1:2],
  1582. msg='slice key should apply slice to sequence')
  1583. self.assertEqual(traverse_obj(_SLICE_DATA, slice(1, 4, 2)), _SLICE_DATA[1:4:2],
  1584. msg='slice key should apply slice to sequence')
  1585. # Test alternative paths
  1586. self.assertEqual(traverse_obj(_TEST_DATA, 'fail', 'str'), 'str',
  1587. msg='multiple `paths` should be treated as alternative paths')
  1588. self.assertEqual(traverse_obj(_TEST_DATA, 'str', 100), 'str',
  1589. msg='alternatives should exit early')
  1590. self.assertEqual(traverse_obj(_TEST_DATA, 'fail', 'fail'), None,
  1591. msg='alternatives should return `default` if exhausted')
  1592. self.assertEqual(traverse_obj(_TEST_DATA, (Ellipsis, 'fail'), 100), 100,
  1593. msg='alternatives should track their own branching return')
  1594. self.assertEqual(traverse_obj(_TEST_DATA, ('dict', Ellipsis), ('data', Ellipsis)), list(_TEST_DATA['data']),
  1595. msg='alternatives on empty objects should search further')
  1596. # Test branch and path nesting
  1597. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', (3, 0), 'url')), ['https://www.example.com/0'],
  1598. msg='tuple as key should be treated as branches')
  1599. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', [3, 0], 'url')), ['https://www.example.com/0'],
  1600. msg='list as key should be treated as branches')
  1601. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', ((1, 'fail'), (0, 'url')))), ['https://www.example.com/0'],
  1602. msg='double nesting in path should be treated as paths')
  1603. self.assertEqual(traverse_obj(['0', [1, 2]], [(0, 1), 0]), [1],
  1604. msg='do not fail early on branching')
  1605. self.assertCountEqual(traverse_obj(_TEST_DATA, ('urls', ((1, ('fail', 'url')), (0, 'url')))),
  1606. ['https://www.example.com/0', 'https://www.example.com/1'],
  1607. msg='triple nesting in path should be treated as branches')
  1608. self.assertEqual(traverse_obj(_TEST_DATA, ('urls', ('fail', (Ellipsis, 'url')))),
  1609. ['https://www.example.com/0', 'https://www.example.com/1'],
  1610. msg='ellipsis as branch path start gets flattened')
  1611. # Test dictionary as key
  1612. self.assertEqual(traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}), {0: 100, 1: 1.2},
  1613. msg='dict key should result in a dict with the same keys')
  1614. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', 0, 'url')}),
  1615. {0: 'https://www.example.com/0'},
  1616. msg='dict key should allow paths')
  1617. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', (3, 0), 'url')}),
  1618. {0: ['https://www.example.com/0']},
  1619. msg='tuple in dict path should be treated as branches')
  1620. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', ((1, 'fail'), (0, 'url')))}),
  1621. {0: ['https://www.example.com/0']},
  1622. msg='double nesting in dict path should be treated as paths')
  1623. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('urls', ((1, ('fail', 'url')), (0, 'url')))}),
  1624. {0: ['https://www.example.com/1', 'https://www.example.com/0']},
  1625. msg='triple nesting in dict path should be treated as branches')
  1626. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'fail'}), {},
  1627. msg='remove `None` values when top level dict key fails')
  1628. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'fail'}, default=Ellipsis), {0: Ellipsis},
  1629. msg='use `default` if key fails and `default`')
  1630. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'dict'}), {},
  1631. msg='remove empty values when dict key')
  1632. self.assertEqual(traverse_obj(_TEST_DATA, {0: 'dict'}, default=Ellipsis), {0: Ellipsis},
  1633. msg='use `default` when dict key and a default')
  1634. self.assertEqual(traverse_obj(_TEST_DATA, {0: {0: 'fail'}}), {},
  1635. msg='remove empty values when nested dict key fails')
  1636. self.assertEqual(traverse_obj(None, {0: 'fail'}), {},
  1637. msg='default to dict if pruned')
  1638. self.assertEqual(traverse_obj(None, {0: 'fail'}, default=Ellipsis), {0: Ellipsis},
  1639. msg='default to dict if pruned and default is given')
  1640. self.assertEqual(traverse_obj(_TEST_DATA, {0: {0: 'fail'}}, default=Ellipsis), {0: {0: Ellipsis}},
  1641. msg='use nested `default` when nested dict key fails and `default`')
  1642. self.assertEqual(traverse_obj(_TEST_DATA, {0: ('dict', Ellipsis)}), {},
  1643. msg='remove key if branch in dict key not successful')
  1644. # Testing default parameter behavior
  1645. _DEFAULT_DATA = {'None': None, 'int': 0, 'list': []}
  1646. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'fail'), None,
  1647. msg='default value should be `None`')
  1648. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'fail', 'fail', default=Ellipsis), Ellipsis,
  1649. msg='chained fails should result in default')
  1650. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'None', 'int'), 0,
  1651. msg='should not short cirquit on `None`')
  1652. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'fail', default=1), 1,
  1653. msg='invalid dict key should result in `default`')
  1654. self.assertEqual(traverse_obj(_DEFAULT_DATA, 'None', default=1), 1,
  1655. msg='`None` is a deliberate sentinel and should become `default`')
  1656. self.assertEqual(traverse_obj(_DEFAULT_DATA, ('list', 10)), None,
  1657. msg='`IndexError` should result in `default`')
  1658. self.assertEqual(traverse_obj(_DEFAULT_DATA, (Ellipsis, 'fail'), default=1), 1,
  1659. msg='if branched but not successful return `default` if defined, not `[]`')
  1660. self.assertEqual(traverse_obj(_DEFAULT_DATA, (Ellipsis, 'fail'), default=None), None,
  1661. msg='if branched but not successful return `default` even if `default` is `None`')
  1662. self.assertEqual(traverse_obj(_DEFAULT_DATA, (Ellipsis, 'fail')), [],
  1663. msg='if branched but not successful return `[]`, not `default`')
  1664. self.assertEqual(traverse_obj(_DEFAULT_DATA, ('list', Ellipsis)), [],
  1665. msg='if branched but object is empty return `[]`, not `default`')
  1666. self.assertEqual(traverse_obj(None, Ellipsis), [],
  1667. msg='if branched but object is `None` return `[]`, not `default`')
  1668. self.assertEqual(traverse_obj({0: None}, (0, Ellipsis)), [],
  1669. msg='if branched but state is `None` return `[]`, not `default`')
  1670. branching_paths = [
  1671. ('fail', Ellipsis),
  1672. (Ellipsis, 'fail'),
  1673. 100 * ('fail',) + (Ellipsis,),
  1674. (Ellipsis,) + 100 * ('fail',),
  1675. ]
  1676. for branching_path in branching_paths:
  1677. self.assertEqual(traverse_obj({}, branching_path), [],
  1678. msg='if branched but state is `None`, return `[]` (not `default`)')
  1679. self.assertEqual(traverse_obj({}, 'fail', branching_path), [],
  1680. msg='if branching in last alternative and previous did not match, return `[]` (not `default`)')
  1681. self.assertEqual(traverse_obj({0: 'x'}, 0, branching_path), 'x',
  1682. msg='if branching in last alternative and previous did match, return single value')
  1683. self.assertEqual(traverse_obj({0: 'x'}, branching_path, 0), 'x',
  1684. msg='if branching in first alternative and non-branching path does match, return single value')
  1685. self.assertEqual(traverse_obj({}, branching_path, 'fail'), None,
  1686. msg='if branching in first alternative and non-branching path does not match, return `default`')
  1687. # Testing expected_type behavior
  1688. _EXPECTED_TYPE_DATA = {'str': 'str', 'int': 0}
  1689. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=str),
  1690. 'str', msg='accept matching `expected_type` type')
  1691. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=int),
  1692. None, msg='reject non-matching `expected_type` type')
  1693. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'int', expected_type=lambda x: str(x)),
  1694. '0', msg='transform type using type function')
  1695. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, 'str', expected_type=lambda _: 1 / 0),
  1696. None, msg='wrap expected_type function in try_call')
  1697. self.assertEqual(traverse_obj(_EXPECTED_TYPE_DATA, Ellipsis, expected_type=str),
  1698. ['str'], msg='eliminate items that expected_type fails on')
  1699. self.assertEqual(traverse_obj(_TEST_DATA, {0: 100, 1: 1.2}, expected_type=int),
  1700. {0: 100}, msg='type as expected_type should filter dict values')
  1701. self.assertEqual(traverse_obj(_TEST_DATA, {0: 100, 1: 1.2, 2: 'None'}, expected_type=str_or_none),
  1702. {0: '100', 1: '1.2'}, msg='function as expected_type should transform dict values')
  1703. self.assertEqual(traverse_obj(_TEST_DATA, ({0: 1.2}, 0, set((int_or_none,))), expected_type=int),
  1704. 1, msg='expected_type should not filter non-final dict values')
  1705. self.assertEqual(traverse_obj(_TEST_DATA, {0: {0: 100, 1: 'str'}}, expected_type=int),
  1706. {0: {0: 100}}, msg='expected_type should transform deep dict values')
  1707. self.assertEqual(traverse_obj(_TEST_DATA, [({0: '...'}, {0: '...'})], expected_type=type(Ellipsis)),
  1708. [{0: Ellipsis}, {0: Ellipsis}], msg='expected_type should transform branched dict values')
  1709. self.assertEqual(traverse_obj({1: {3: 4}}, [(1, 2), 3], expected_type=int),
  1710. [4], msg='expected_type regression for type matching in tuple branching')
  1711. self.assertEqual(traverse_obj(_TEST_DATA, ['data', Ellipsis], expected_type=int),
  1712. [], msg='expected_type regression for type matching in dict result')
  1713. # Test get_all behavior
  1714. _GET_ALL_DATA = {'key': [0, 1, 2]}
  1715. self.assertEqual(traverse_obj(_GET_ALL_DATA, ('key', Ellipsis), get_all=False), 0,
  1716. msg='if not `get_all`, return only first matching value')
  1717. self.assertEqual(traverse_obj(_GET_ALL_DATA, Ellipsis, get_all=False), [0, 1, 2],
  1718. msg='do not overflatten if not `get_all`')
  1719. # Test casesense behavior
  1720. _CASESENSE_DATA = {
  1721. 'KeY': 'value0',
  1722. 0: {
  1723. 'KeY': 'value1',
  1724. 0: {'KeY': 'value2'},
  1725. },
  1726. # FULLWIDTH LATIN CAPITAL LETTER K
  1727. '\uff2bey': 'value3',
  1728. }
  1729. self.assertEqual(traverse_obj(_CASESENSE_DATA, 'key'), None,
  1730. msg='dict keys should be case sensitive unless `casesense`')
  1731. self.assertEqual(traverse_obj(_CASESENSE_DATA, 'keY',
  1732. casesense=False), 'value0',
  1733. msg='allow non matching key case if `casesense`')
  1734. self.assertEqual(traverse_obj(_CASESENSE_DATA, '\uff4bey', # FULLWIDTH LATIN SMALL LETTER K
  1735. casesense=False), 'value3',
  1736. msg='allow non matching Unicode key case if `casesense`')
  1737. self.assertEqual(traverse_obj(_CASESENSE_DATA, (0, ('keY',)),
  1738. casesense=False), ['value1'],
  1739. msg='allow non matching key case in branch if `casesense`')
  1740. self.assertEqual(traverse_obj(_CASESENSE_DATA, (0, ((0, 'keY'),)),
  1741. casesense=False), ['value2'],
  1742. msg='allow non matching key case in branch path if `casesense`')
  1743. # Test traverse_string behavior
  1744. _TRAVERSE_STRING_DATA = {'str': 'str', 1.2: 1.2}
  1745. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0)), None,
  1746. msg='do not traverse into string if not `traverse_string`')
  1747. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', 0),
  1748. _traverse_string=True), 's',
  1749. msg='traverse into string if `traverse_string`')
  1750. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, (1.2, 1),
  1751. _traverse_string=True), '.',
  1752. msg='traverse into converted data if `traverse_string`')
  1753. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', Ellipsis),
  1754. _traverse_string=True), 'str',
  1755. msg='`...` should result in string (same value) if `traverse_string`')
  1756. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', slice(0, None, 2)),
  1757. _traverse_string=True), 'sr',
  1758. msg='`slice` should result in string if `traverse_string`')
  1759. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', lambda i, v: i or v == 's'),
  1760. _traverse_string=True), 'str',
  1761. msg='function should result in string if `traverse_string`')
  1762. self.assertEqual(traverse_obj(_TRAVERSE_STRING_DATA, ('str', (0, 2)),
  1763. _traverse_string=True), ['s', 'r'],
  1764. msg='branching should result in list if `traverse_string`')
  1765. self.assertEqual(traverse_obj({}, (0, Ellipsis), _traverse_string=True), [],
  1766. msg='branching should result in list if `traverse_string`')
  1767. self.assertEqual(traverse_obj({}, (0, lambda x, y: True), _traverse_string=True), [],
  1768. msg='branching should result in list if `traverse_string`')
  1769. self.assertEqual(traverse_obj({}, (0, slice(1)), _traverse_string=True), [],
  1770. msg='branching should result in list if `traverse_string`')
  1771. # Test is_user_input behavior
  1772. _IS_USER_INPUT_DATA = {'range8': list(range(8))}
  1773. self.assertEqual(traverse_obj(_IS_USER_INPUT_DATA, ('range8', '3'),
  1774. _is_user_input=True), 3,
  1775. msg='allow for string indexing if `is_user_input`')
  1776. self.assertCountEqual(traverse_obj(_IS_USER_INPUT_DATA, ('range8', '3:'),
  1777. _is_user_input=True), tuple(range(8))[3:],
  1778. msg='allow for string slice if `is_user_input`')
  1779. self.assertCountEqual(traverse_obj(_IS_USER_INPUT_DATA, ('range8', ':4:2'),
  1780. _is_user_input=True), tuple(range(8))[:4:2],
  1781. msg='allow step in string slice if `is_user_input`')
  1782. self.assertCountEqual(traverse_obj(_IS_USER_INPUT_DATA, ('range8', ':'),
  1783. _is_user_input=True), range(8),
  1784. msg='`:` should be treated as `...` if `is_user_input`')
  1785. with self.assertRaises(TypeError, msg='too many params should result in error'):
  1786. traverse_obj(_IS_USER_INPUT_DATA, ('range8', ':::'), _is_user_input=True)
  1787. # Test re.Match as input obj
  1788. mobj = re.match(r'^0(12)(?P<group>3)(4)?$', '0123')
  1789. self.assertEqual(traverse_obj(mobj, Ellipsis), [x for x in mobj.groups() if x is not None],
  1790. msg='`...` on a `re.Match` should give its `groups()`')
  1791. self.assertEqual(traverse_obj(mobj, lambda k, _: k in (0, 2)), ['0123', '3'],
  1792. msg='function on a `re.Match` should give groupno, value starting at 0')
  1793. self.assertEqual(traverse_obj(mobj, 'group'), '3',
  1794. msg='str key on a `re.Match` should give group with that name')
  1795. self.assertEqual(traverse_obj(mobj, 2), '3',
  1796. msg='int key on a `re.Match` should give group with that name')
  1797. self.assertEqual(traverse_obj(mobj, 'gRoUp', casesense=False), '3',
  1798. msg='str key on a `re.Match` should respect casesense')
  1799. self.assertEqual(traverse_obj(mobj, 'fail'), None,
  1800. msg='failing str key on a `re.Match` should return `default`')
  1801. self.assertEqual(traverse_obj(mobj, 'gRoUpS', casesense=False), None,
  1802. msg='failing str key on a `re.Match` should return `default`')
  1803. self.assertEqual(traverse_obj(mobj, 8), None,
  1804. msg='failing int key on a `re.Match` should return `default`')
  1805. self.assertEqual(traverse_obj(mobj, lambda k, _: k in (0, 'group')), ['0123', '3'],
  1806. msg='function on a `re.Match` should give group name as well')
  1807. def test_get_first(self):
  1808. self.assertEqual(get_first([{'a': None}, {'a': 'spam'}], 'a'), 'spam')
  1809. def test_join_nonempty(self):
  1810. self.assertEqual(join_nonempty('a', 'b'), 'a-b')
  1811. self.assertEqual(join_nonempty(
  1812. 'a', 'b', 'c', 'd',
  1813. from_dict={'a': 'c', 'c': [], 'b': 'd', 'd': None}), 'c-d')
  1814. if __name__ == '__main__':
  1815. unittest.main()