You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1440 lines
66 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
  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 json
  12. import xml.etree.ElementTree
  13. from youtube_dl.utils import (
  14. age_restricted,
  15. args_to_str,
  16. encode_base_n,
  17. caesar,
  18. clean_html,
  19. date_from_str,
  20. DateRange,
  21. detect_exe_version,
  22. determine_ext,
  23. dict_get,
  24. encode_compat_str,
  25. encodeFilename,
  26. escape_rfc3986,
  27. escape_url,
  28. extract_attributes,
  29. ExtractorError,
  30. find_xpath_attr,
  31. fix_xml_ampersands,
  32. float_or_none,
  33. get_element_by_class,
  34. get_element_by_attribute,
  35. get_elements_by_class,
  36. get_elements_by_attribute,
  37. InAdvancePagedList,
  38. int_or_none,
  39. intlist_to_bytes,
  40. is_html,
  41. js_to_json,
  42. limit_length,
  43. merge_dicts,
  44. mimetype2ext,
  45. month_by_name,
  46. multipart_encode,
  47. ohdave_rsa_encrypt,
  48. OnDemandPagedList,
  49. orderedSet,
  50. parse_age_limit,
  51. parse_duration,
  52. parse_filesize,
  53. parse_count,
  54. parse_iso8601,
  55. parse_resolution,
  56. parse_bitrate,
  57. pkcs1pad,
  58. read_batch_urls,
  59. sanitize_filename,
  60. sanitize_path,
  61. sanitize_url,
  62. expand_path,
  63. prepend_extension,
  64. replace_extension,
  65. remove_start,
  66. remove_end,
  67. remove_quotes,
  68. rot47,
  69. shell_quote,
  70. smuggle_url,
  71. str_to_int,
  72. strip_jsonp,
  73. strip_or_none,
  74. subtitles_filename,
  75. timeconvert,
  76. unescapeHTML,
  77. unified_strdate,
  78. unified_timestamp,
  79. unsmuggle_url,
  80. uppercase_escape,
  81. lowercase_escape,
  82. url_basename,
  83. url_or_none,
  84. base_url,
  85. urljoin,
  86. urlencode_postdata,
  87. urshift,
  88. update_url_query,
  89. version_tuple,
  90. xpath_with_ns,
  91. xpath_element,
  92. xpath_text,
  93. xpath_attr,
  94. render_table,
  95. match_str,
  96. parse_dfxp_time_expr,
  97. dfxp2srt,
  98. cli_option,
  99. cli_valueless_option,
  100. cli_bool_option,
  101. parse_codecs,
  102. )
  103. from youtube_dl.compat import (
  104. compat_chr,
  105. compat_etree_fromstring,
  106. compat_getenv,
  107. compat_os_name,
  108. compat_setenv,
  109. compat_urlparse,
  110. compat_parse_qs,
  111. )
  112. class TestUtil(unittest.TestCase):
  113. def test_timeconvert(self):
  114. self.assertTrue(timeconvert('') is None)
  115. self.assertTrue(timeconvert('bougrg') is None)
  116. def test_sanitize_filename(self):
  117. self.assertEqual(sanitize_filename('abc'), 'abc')
  118. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  119. self.assertEqual(sanitize_filename('123'), '123')
  120. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  121. self.assertFalse('/' in sanitize_filename('abc/de///'))
  122. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  123. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  124. self.assertEqual('yes no', sanitize_filename('yes? no'))
  125. self.assertEqual('this - that', sanitize_filename('this: that'))
  126. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  127. aumlaut = 'ä'
  128. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  129. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  130. self.assertEqual(sanitize_filename(tests), tests)
  131. self.assertEqual(
  132. sanitize_filename('New World record at 0:12:34'),
  133. 'New World record at 0_12_34')
  134. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  135. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  136. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  137. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  138. forbidden = '"\0\\/'
  139. for fc in forbidden:
  140. for fbc in forbidden:
  141. self.assertTrue(fbc not in sanitize_filename(fc))
  142. def test_sanitize_filename_restricted(self):
  143. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  144. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  145. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  146. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  147. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  148. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  149. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  150. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  151. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  152. tests = 'aäb\u4e2d\u56fd\u7684c'
  153. self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
  154. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  155. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  156. for fc in forbidden:
  157. for fbc in forbidden:
  158. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  159. # Handle a common case more neatly
  160. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  161. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  162. # .. but make sure the file name is never empty
  163. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  164. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  165. self.assertEqual(sanitize_filename(
  166. 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
  167. 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
  168. def test_sanitize_ids(self):
  169. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  170. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  171. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  172. def test_sanitize_path(self):
  173. if sys.platform != 'win32':
  174. return
  175. self.assertEqual(sanitize_path('abc'), 'abc')
  176. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  177. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  178. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  179. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  180. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  181. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  182. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  183. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  184. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  185. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  186. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  187. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  188. self.assertEqual(
  189. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  190. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  191. self.assertEqual(
  192. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  193. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  194. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  195. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  196. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  197. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  198. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  199. self.assertEqual(sanitize_path('./abc'), 'abc')
  200. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  201. def test_sanitize_url(self):
  202. self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
  203. self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
  204. self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
  205. self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
  206. def test_expand_path(self):
  207. def env(var):
  208. return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
  209. compat_setenv('YOUTUBE_DL_EXPATH_PATH', 'expanded')
  210. self.assertEqual(expand_path(env('YOUTUBE_DL_EXPATH_PATH')), 'expanded')
  211. self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
  212. self.assertEqual(expand_path('~'), compat_getenv('HOME'))
  213. self.assertEqual(
  214. expand_path('~/%s' % env('YOUTUBE_DL_EXPATH_PATH')),
  215. '%s/expanded' % compat_getenv('HOME'))
  216. def test_prepend_extension(self):
  217. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  218. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  219. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  220. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  221. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  222. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  223. def test_replace_extension(self):
  224. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  225. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  226. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  227. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  228. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  229. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  230. def test_subtitles_filename(self):
  231. self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
  232. self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
  233. self.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
  234. def test_remove_start(self):
  235. self.assertEqual(remove_start(None, 'A - '), None)
  236. self.assertEqual(remove_start('A - B', 'A - '), 'B')
  237. self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
  238. def test_remove_end(self):
  239. self.assertEqual(remove_end(None, ' - B'), None)
  240. self.assertEqual(remove_end('A - B', ' - B'), 'A')
  241. self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
  242. def test_remove_quotes(self):
  243. self.assertEqual(remove_quotes(None), None)
  244. self.assertEqual(remove_quotes('"'), '"')
  245. self.assertEqual(remove_quotes("'"), "'")
  246. self.assertEqual(remove_quotes(';'), ';')
  247. self.assertEqual(remove_quotes('";'), '";')
  248. self.assertEqual(remove_quotes('""'), '')
  249. self.assertEqual(remove_quotes('";"'), ';')
  250. def test_ordered_set(self):
  251. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  252. self.assertEqual(orderedSet([]), [])
  253. self.assertEqual(orderedSet([1]), [1])
  254. # keep the list ordered
  255. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  256. def test_unescape_html(self):
  257. self.assertEqual(unescapeHTML('%20;'), '%20;')
  258. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  259. self.assertEqual(unescapeHTML('&#47;'), '/')
  260. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  261. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  262. self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
  263. # HTML5 entities
  264. self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
  265. def test_date_from_str(self):
  266. self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
  267. self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
  268. self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
  269. self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
  270. self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
  271. def test_daterange(self):
  272. _20century = DateRange("19000101", "20000101")
  273. self.assertFalse("17890714" in _20century)
  274. _ac = DateRange("00010101")
  275. self.assertTrue("19690721" in _ac)
  276. _firstmilenium = DateRange(end="10000101")
  277. self.assertTrue("07110427" in _firstmilenium)
  278. def test_unified_dates(self):
  279. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  280. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  281. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  282. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  283. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  284. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  285. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  286. self.assertEqual(
  287. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  288. '20141126')
  289. self.assertEqual(
  290. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  291. '20150202')
  292. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  293. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  294. self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
  295. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  296. self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
  297. self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
  298. self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
  299. self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
  300. self.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
  301. self.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
  302. def test_unified_timestamps(self):
  303. self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
  304. self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
  305. self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
  306. self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
  307. self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
  308. self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
  309. self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
  310. self.assertEqual(
  311. unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
  312. 1417001400)
  313. self.assertEqual(
  314. unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
  315. 1422902860)
  316. self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
  317. self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
  318. self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
  319. self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
  320. self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
  321. self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
  322. self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
  323. self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
  324. self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
  325. self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
  326. def test_determine_ext(self):
  327. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  328. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  329. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  330. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  331. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  332. self.assertEqual(determine_ext('foobar', None), None)
  333. def test_find_xpath_attr(self):
  334. testxml = '''<root>
  335. <node/>
  336. <node x="a"/>
  337. <node x="a" y="c" />
  338. <node x="b" y="d" />
  339. <node x="" />
  340. </root>'''
  341. doc = compat_etree_fromstring(testxml)
  342. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  343. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  344. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  345. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  346. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  347. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  348. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  349. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  350. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  351. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  352. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  353. def test_xpath_with_ns(self):
  354. testxml = '''<root xmlns:media="http://example.com/">
  355. <media:song>
  356. <media:author>The Author</media:author>
  357. <url>http://server.com/download.mp3</url>
  358. </media:song>
  359. </root>'''
  360. doc = compat_etree_fromstring(testxml)
  361. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  362. self.assertTrue(find('media:song') is not None)
  363. self.assertEqual(find('media:song/media:author').text, 'The Author')
  364. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  365. def test_xpath_element(self):
  366. doc = xml.etree.ElementTree.Element('root')
  367. div = xml.etree.ElementTree.SubElement(doc, 'div')
  368. p = xml.etree.ElementTree.SubElement(div, 'p')
  369. p.text = 'Foo'
  370. self.assertEqual(xpath_element(doc, 'div/p'), p)
  371. self.assertEqual(xpath_element(doc, ['div/p']), p)
  372. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  373. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  374. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  375. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  376. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  377. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  378. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  379. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  380. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  381. def test_xpath_text(self):
  382. testxml = '''<root>
  383. <div>
  384. <p>Foo</p>
  385. </div>
  386. </root>'''
  387. doc = compat_etree_fromstring(testxml)
  388. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  389. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  390. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  391. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  392. def test_xpath_attr(self):
  393. testxml = '''<root>
  394. <div>
  395. <p x="a">Foo</p>
  396. </div>
  397. </root>'''
  398. doc = compat_etree_fromstring(testxml)
  399. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  400. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  401. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  402. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  403. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  404. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  405. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  406. def test_smuggle_url(self):
  407. data = {"ö": "ö", "abc": [3]}
  408. url = 'https://foo.bar/baz?x=y#a'
  409. smug_url = smuggle_url(url, data)
  410. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  411. self.assertEqual(url, unsmug_url)
  412. self.assertEqual(data, unsmug_data)
  413. res_url, res_data = unsmuggle_url(url)
  414. self.assertEqual(res_url, url)
  415. self.assertEqual(res_data, None)
  416. smug_url = smuggle_url(url, {'a': 'b'})
  417. smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
  418. res_url, res_data = unsmuggle_url(smug_smug_url)
  419. self.assertEqual(res_url, url)
  420. self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
  421. def test_shell_quote(self):
  422. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  423. self.assertEqual(
  424. shell_quote(args),
  425. """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
  426. def test_float_or_none(self):
  427. self.assertEqual(float_or_none('42.42'), 42.42)
  428. self.assertEqual(float_or_none('42'), 42.0)
  429. self.assertEqual(float_or_none(''), None)
  430. self.assertEqual(float_or_none(None), None)
  431. self.assertEqual(float_or_none([]), None)
  432. self.assertEqual(float_or_none(set()), None)
  433. def test_int_or_none(self):
  434. self.assertEqual(int_or_none('42'), 42)
  435. self.assertEqual(int_or_none(''), None)
  436. self.assertEqual(int_or_none(None), None)
  437. self.assertEqual(int_or_none([]), None)
  438. self.assertEqual(int_or_none(set()), None)
  439. def test_str_to_int(self):
  440. self.assertEqual(str_to_int('123,456'), 123456)
  441. self.assertEqual(str_to_int('123.456'), 123456)
  442. self.assertEqual(str_to_int(523), 523)
  443. # Python 3 has no long
  444. if sys.version_info < (3, 0):
  445. eval('self.assertEqual(str_to_int(123456L), 123456)')
  446. self.assertEqual(str_to_int('noninteger'), None)
  447. self.assertEqual(str_to_int([]), None)
  448. def test_url_basename(self):
  449. self.assertEqual(url_basename('http://foo.de/'), '')
  450. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  451. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  452. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  453. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  454. self.assertEqual(
  455. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  456. 'trailer.mp4')
  457. def test_base_url(self):
  458. self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
  459. self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
  460. self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
  461. self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
  462. self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
  463. def test_urljoin(self):
  464. self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  465. self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  466. self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  467. self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  468. self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
  469. self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  470. self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  471. self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  472. self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  473. self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  474. self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  475. self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  476. self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  477. self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  478. self.assertEqual(urljoin('http://foo.de/', None), None)
  479. self.assertEqual(urljoin('http://foo.de/', ''), None)
  480. self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
  481. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
  482. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
  483. self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
  484. def test_url_or_none(self):
  485. self.assertEqual(url_or_none(None), None)
  486. self.assertEqual(url_or_none(''), None)
  487. self.assertEqual(url_or_none('foo'), None)
  488. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  489. self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
  490. self.assertEqual(url_or_none('http$://foo.de'), None)
  491. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  492. self.assertEqual(url_or_none('//foo.de'), '//foo.de')
  493. def test_parse_age_limit(self):
  494. self.assertEqual(parse_age_limit(None), None)
  495. self.assertEqual(parse_age_limit(False), None)
  496. self.assertEqual(parse_age_limit('invalid'), None)
  497. self.assertEqual(parse_age_limit(0), 0)
  498. self.assertEqual(parse_age_limit(18), 18)
  499. self.assertEqual(parse_age_limit(21), 21)
  500. self.assertEqual(parse_age_limit(22), None)
  501. self.assertEqual(parse_age_limit('18'), 18)
  502. self.assertEqual(parse_age_limit('18+'), 18)
  503. self.assertEqual(parse_age_limit('PG-13'), 13)
  504. self.assertEqual(parse_age_limit('TV-14'), 14)
  505. self.assertEqual(parse_age_limit('TV-MA'), 17)
  506. self.assertEqual(parse_age_limit('TV14'), 14)
  507. self.assertEqual(parse_age_limit('TV_G'), 0)
  508. def test_parse_duration(self):
  509. self.assertEqual(parse_duration(None), None)
  510. self.assertEqual(parse_duration(False), None)
  511. self.assertEqual(parse_duration('invalid'), None)
  512. self.assertEqual(parse_duration('1'), 1)
  513. self.assertEqual(parse_duration('1337:12'), 80232)
  514. self.assertEqual(parse_duration('9:12:43'), 33163)
  515. self.assertEqual(parse_duration('12:00'), 720)
  516. self.assertEqual(parse_duration('00:01:01'), 61)
  517. self.assertEqual(parse_duration('x:y'), None)
  518. self.assertEqual(parse_duration('3h11m53s'), 11513)
  519. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  520. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  521. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  522. self.assertEqual(parse_duration('62m45s'), 3765)
  523. self.assertEqual(parse_duration('6m59s'), 419)
  524. self.assertEqual(parse_duration('49s'), 49)
  525. self.assertEqual(parse_duration('0h0m0s'), 0)
  526. self.assertEqual(parse_duration('0m0s'), 0)
  527. self.assertEqual(parse_duration('0s'), 0)
  528. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  529. self.assertEqual(parse_duration('T30M38S'), 1838)
  530. self.assertEqual(parse_duration('5 s'), 5)
  531. self.assertEqual(parse_duration('3 min'), 180)
  532. self.assertEqual(parse_duration('2.5 hours'), 9000)
  533. self.assertEqual(parse_duration('02:03:04'), 7384)
  534. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  535. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  536. self.assertEqual(parse_duration('87 Min.'), 5220)
  537. self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
  538. self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
  539. self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
  540. def test_fix_xml_ampersands(self):
  541. self.assertEqual(
  542. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  543. self.assertEqual(
  544. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  545. '"&amp;x=y&amp;wrong;&amp;z=a')
  546. self.assertEqual(
  547. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  548. '&amp;&apos;&gt;&lt;&quot;')
  549. self.assertEqual(
  550. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  551. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  552. def test_paged_list(self):
  553. def testPL(size, pagesize, sliceargs, expected):
  554. def get_page(pagenum):
  555. firstid = pagenum * pagesize
  556. upto = min(size, pagenum * pagesize + pagesize)
  557. for i in range(firstid, upto):
  558. yield i
  559. pl = OnDemandPagedList(get_page, pagesize)
  560. got = pl.getslice(*sliceargs)
  561. self.assertEqual(got, expected)
  562. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  563. got = iapl.getslice(*sliceargs)
  564. self.assertEqual(got, expected)
  565. testPL(5, 2, (), [0, 1, 2, 3, 4])
  566. testPL(5, 2, (1,), [1, 2, 3, 4])
  567. testPL(5, 2, (2,), [2, 3, 4])
  568. testPL(5, 2, (4,), [4])
  569. testPL(5, 2, (0, 3), [0, 1, 2])
  570. testPL(5, 2, (1, 4), [1, 2, 3])
  571. testPL(5, 2, (2, 99), [2, 3, 4])
  572. testPL(5, 2, (20, 99), [])
  573. def test_read_batch_urls(self):
  574. f = io.StringIO('''\xef\xbb\xbf foo
  575. bar\r
  576. baz
  577. # More after this line\r
  578. ; or after this
  579. bam''')
  580. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  581. def test_urlencode_postdata(self):
  582. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  583. self.assertTrue(isinstance(data, bytes))
  584. def test_update_url_query(self):
  585. def query_dict(url):
  586. return compat_parse_qs(compat_urlparse.urlparse(url).query)
  587. self.assertEqual(query_dict(update_url_query(
  588. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  589. query_dict('http://example.com/path?quality=HD&format=mp4'))
  590. self.assertEqual(query_dict(update_url_query(
  591. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  592. query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
  593. self.assertEqual(query_dict(update_url_query(
  594. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  595. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  596. self.assertEqual(query_dict(update_url_query(
  597. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  598. query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  599. self.assertEqual(query_dict(update_url_query(
  600. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  601. query_dict('http://example.com/path'))
  602. self.assertEqual(query_dict(update_url_query(
  603. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  604. query_dict('http://example.com/path?system=LINUX'))
  605. self.assertEqual(query_dict(update_url_query(
  606. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  607. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  608. self.assertEqual(query_dict(update_url_query(
  609. 'http://example.com/path', {'width': 1080, 'height': 720})),
  610. query_dict('http://example.com/path?width=1080&height=720'))
  611. self.assertEqual(query_dict(update_url_query(
  612. 'http://example.com/path', {'bitrate': 5020.43})),
  613. query_dict('http://example.com/path?bitrate=5020.43'))
  614. self.assertEqual(query_dict(update_url_query(
  615. 'http://example.com/path', {'test': '第二行тест'})),
  616. query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  617. def test_multipart_encode(self):
  618. self.assertEqual(
  619. multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
  620. b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
  621. self.assertEqual(
  622. multipart_encode({'欄位'.encode('utf-8'): ''.encode('utf-8')}, boundary='AAAAAA')[0],
  623. 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')
  624. self.assertRaises(
  625. ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
  626. def test_dict_get(self):
  627. FALSE_VALUES = {
  628. 'none': None,
  629. 'false': False,
  630. 'zero': 0,
  631. 'empty_string': '',
  632. 'empty_list': [],
  633. }
  634. d = FALSE_VALUES.copy()
  635. d['a'] = 42
  636. self.assertEqual(dict_get(d, 'a'), 42)
  637. self.assertEqual(dict_get(d, 'b'), None)
  638. self.assertEqual(dict_get(d, 'b', 42), 42)
  639. self.assertEqual(dict_get(d, ('a', )), 42)
  640. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  641. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  642. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  643. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  644. for key, false_value in FALSE_VALUES.items():
  645. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  646. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  647. def test_merge_dicts(self):
  648. self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
  649. self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
  650. self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
  651. self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
  652. self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
  653. self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
  654. self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
  655. self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  656. self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  657. def test_encode_compat_str(self):
  658. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  659. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  660. def test_parse_iso8601(self):
  661. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  662. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  663. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  664. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  665. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  666. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  667. def test_strip_jsonp(self):
  668. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  669. d = json.loads(stripped)
  670. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  671. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  672. d = json.loads(stripped)
  673. self.assertEqual(d, {'STATUS': 'OK'})
  674. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  675. d = json.loads(stripped)
  676. self.assertEqual(d, {'status': 'success'})
  677. stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
  678. d = json.loads(stripped)
  679. self.assertEqual(d, {'status': 'success'})
  680. stripped = strip_jsonp('window.cb && cb({"status": "success"});')
  681. d = json.loads(stripped)
  682. self.assertEqual(d, {'status': 'success'})
  683. stripped = strip_jsonp('({"status": "success"});')
  684. d = json.loads(stripped)
  685. self.assertEqual(d, {'status': 'success'})
  686. def test_strip_or_none(self):
  687. self.assertEqual(strip_or_none(' abc'), 'abc')
  688. self.assertEqual(strip_or_none('abc '), 'abc')
  689. self.assertEqual(strip_or_none(' abc '), 'abc')
  690. self.assertEqual(strip_or_none('\tabc\t'), 'abc')
  691. self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
  692. self.assertEqual(strip_or_none('abc'), 'abc')
  693. self.assertEqual(strip_or_none(''), '')
  694. self.assertEqual(strip_or_none(None), None)
  695. self.assertEqual(strip_or_none(42), None)
  696. self.assertEqual(strip_or_none([]), None)
  697. def test_uppercase_escape(self):
  698. self.assertEqual(uppercase_escape(''), '')
  699. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  700. def test_lowercase_escape(self):
  701. self.assertEqual(lowercase_escape(''), '')
  702. self.assertEqual(lowercase_escape('\\u0026'), '&')
  703. def test_limit_length(self):
  704. self.assertEqual(limit_length(None, 12), None)
  705. self.assertEqual(limit_length('foo', 12), 'foo')
  706. self.assertTrue(
  707. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  708. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  709. def test_mimetype2ext(self):
  710. self.assertEqual(mimetype2ext(None), None)
  711. self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
  712. self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
  713. self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
  714. self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
  715. self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
  716. def test_month_by_name(self):
  717. self.assertEqual(month_by_name(None), None)
  718. self.assertEqual(month_by_name('December', 'en'), 12)
  719. self.assertEqual(month_by_name('décembre', 'fr'), 12)
  720. self.assertEqual(month_by_name('December'), 12)
  721. self.assertEqual(month_by_name('décembre'), None)
  722. self.assertEqual(month_by_name('Unknown', 'unknown'), None)
  723. def test_parse_codecs(self):
  724. self.assertEqual(parse_codecs(''), {})
  725. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  726. 'vcodec': 'avc1.77.30',
  727. 'acodec': 'mp4a.40.2',
  728. })
  729. self.assertEqual(parse_codecs('mp4a.40.2'), {
  730. 'vcodec': 'none',
  731. 'acodec': 'mp4a.40.2',
  732. })
  733. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  734. 'vcodec': 'avc1.42001e',
  735. 'acodec': 'mp4a.40.5',
  736. })
  737. self.assertEqual(parse_codecs('avc3.640028'), {
  738. 'vcodec': 'avc3.640028',
  739. 'acodec': 'none',
  740. })
  741. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  742. 'vcodec': 'h264',
  743. 'acodec': 'aac',
  744. })
  745. self.assertEqual(parse_codecs('av01.0.05M.08'), {
  746. 'vcodec': 'av01.0.05M.08',
  747. 'acodec': 'none',
  748. })
  749. self.assertEqual(parse_codecs('theora, vorbis'), {
  750. 'vcodec': 'theora',
  751. 'acodec': 'vorbis',
  752. })
  753. self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
  754. 'vcodec': 'unknownvcodec',
  755. 'acodec': 'unknownacodec',
  756. })
  757. self.assertEqual(parse_codecs('unknown'), {})
  758. def test_escape_rfc3986(self):
  759. reserved = "!*'();:@&=+$,/?#[]"
  760. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  761. self.assertEqual(escape_rfc3986(reserved), reserved)
  762. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  763. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  764. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  765. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  766. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  767. def test_escape_url(self):
  768. self.assertEqual(
  769. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  770. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  771. )
  772. self.assertEqual(
  773. 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'),
  774. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  775. )
  776. self.assertEqual(
  777. escape_url('http://тест.рф/фрагмент'),
  778. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  779. )
  780. self.assertEqual(
  781. escape_url('http://тест.рф/абв?абв=абв#абв'),
  782. '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'
  783. )
  784. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  785. def test_js_to_json_realworld(self):
  786. inp = '''{
  787. 'clip':{'provider':'pseudo'}
  788. }'''
  789. self.assertEqual(js_to_json(inp), '''{
  790. "clip":{"provider":"pseudo"}
  791. }''')
  792. json.loads(js_to_json(inp))
  793. inp = '''{
  794. 'playlist':[{'controls':{'all':null}}]
  795. }'''
  796. self.assertEqual(js_to_json(inp), '''{
  797. "playlist":[{"controls":{"all":null}}]
  798. }''')
  799. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  800. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  801. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  802. json_code = js_to_json(inp)
  803. self.assertEqual(json.loads(json_code), json.loads(inp))
  804. inp = '''{
  805. 0:{src:'skipped', type: 'application/dash+xml'},
  806. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  807. }'''
  808. self.assertEqual(js_to_json(inp), '''{
  809. "0":{"src":"skipped", "type": "application/dash+xml"},
  810. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  811. }''')
  812. inp = '''{"foo":101}'''
  813. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  814. inp = '''{"duration": "00:01:07"}'''
  815. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  816. inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
  817. self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
  818. def test_js_to_json_edgecases(self):
  819. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  820. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  821. on = js_to_json('{"abc": true}')
  822. self.assertEqual(json.loads(on), {'abc': True})
  823. # Ignore JavaScript code as well
  824. on = js_to_json('''{
  825. "x": 1,
  826. y: "a",
  827. z: some.code
  828. }''')
  829. d = json.loads(on)
  830. self.assertEqual(d['x'], 1)
  831. self.assertEqual(d['y'], 'a')
  832. on = js_to_json('["abc", "def",]')
  833. self.assertEqual(json.loads(on), ['abc', 'def'])
  834. on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
  835. self.assertEqual(json.loads(on), ['abc', 'def'])
  836. on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
  837. self.assertEqual(json.loads(on), ['abc', 'def'])
  838. on = js_to_json('{"abc": "def",}')
  839. self.assertEqual(json.loads(on), {'abc': 'def'})
  840. on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
  841. self.assertEqual(json.loads(on), {'abc': 'def'})
  842. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  843. self.assertEqual(json.loads(on), {'0': ',]'})
  844. on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
  845. self.assertEqual(json.loads(on), {'0': ',]'})
  846. on = js_to_json('{ 0: // comment\n1 }')
  847. self.assertEqual(json.loads(on), {'0': 1})
  848. on = js_to_json(r'["<p>x<\/p>"]')
  849. self.assertEqual(json.loads(on), ['<p>x</p>'])
  850. on = js_to_json(r'["\xaa"]')
  851. self.assertEqual(json.loads(on), ['\u00aa'])
  852. on = js_to_json("['a\\\nb']")
  853. self.assertEqual(json.loads(on), ['ab'])
  854. on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
  855. self.assertEqual(json.loads(on), ['ab'])
  856. on = js_to_json('{0xff:0xff}')
  857. self.assertEqual(json.loads(on), {'255': 255})
  858. on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
  859. self.assertEqual(json.loads(on), {'255': 255})
  860. on = js_to_json('{077:077}')
  861. self.assertEqual(json.loads(on), {'63': 63})
  862. on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
  863. self.assertEqual(json.loads(on), {'63': 63})
  864. on = js_to_json('{42:42}')
  865. self.assertEqual(json.loads(on), {'42': 42})
  866. on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
  867. self.assertEqual(json.loads(on), {'42': 42})
  868. on = js_to_json('{42:4.2e1}')
  869. self.assertEqual(json.loads(on), {'42': 42.0})
  870. def test_js_to_json_malformed(self):
  871. self.assertEqual(js_to_json('42a1'), '42"a1"')
  872. self.assertEqual(js_to_json('42a-1'), '42"a"-1')
  873. def test_extract_attributes(self):
  874. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  875. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  876. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  877. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  878. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  879. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  880. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  881. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  882. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  883. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  884. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  885. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  886. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  887. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  888. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  889. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  890. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  891. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  892. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  893. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  894. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  895. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  896. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  897. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  898. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  899. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  900. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  901. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  902. # "Narrow" Python builds don't support unicode code points outside BMP.
  903. try:
  904. compat_chr(0x10000)
  905. supports_outside_bmp = True
  906. except ValueError:
  907. supports_outside_bmp = False
  908. if supports_outside_bmp:
  909. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  910. # Malformed HTML should not break attributes extraction on older Python
  911. self.assertEqual(extract_attributes('<mal"formed/>'), {})
  912. def test_clean_html(self):
  913. self.assertEqual(clean_html('a:\nb'), 'a: b')
  914. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  915. self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
  916. def test_intlist_to_bytes(self):
  917. self.assertEqual(
  918. intlist_to_bytes([0, 1, 127, 128, 255]),
  919. b'\x00\x01\x7f\x80\xff')
  920. def test_args_to_str(self):
  921. self.assertEqual(
  922. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  923. 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
  924. )
  925. def test_parse_filesize(self):
  926. self.assertEqual(parse_filesize(None), None)
  927. self.assertEqual(parse_filesize(''), None)
  928. self.assertEqual(parse_filesize('91 B'), 91)
  929. self.assertEqual(parse_filesize('foobar'), None)
  930. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  931. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  932. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  933. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  934. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  935. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  936. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  937. def test_parse_count(self):
  938. self.assertEqual(parse_count(None), None)
  939. self.assertEqual(parse_count(''), None)
  940. self.assertEqual(parse_count('0'), 0)
  941. self.assertEqual(parse_count('1000'), 1000)
  942. self.assertEqual(parse_count('1.000'), 1000)
  943. self.assertEqual(parse_count('1.1k'), 1100)
  944. self.assertEqual(parse_count('1.1kk'), 1100000)
  945. self.assertEqual(parse_count('1.1kk '), 1100000)
  946. self.assertEqual(parse_count('1.1kk views'), 1100000)
  947. def test_parse_resolution(self):
  948. self.assertEqual(parse_resolution(None), {})
  949. self.assertEqual(parse_resolution(''), {})
  950. self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
  951. self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
  952. self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
  953. self.assertEqual(parse_resolution('720p'), {'height': 720})
  954. self.assertEqual(parse_resolution('4k'), {'height': 2160})
  955. self.assertEqual(parse_resolution('8K'), {'height': 4320})
  956. def test_parse_bitrate(self):
  957. self.assertEqual(parse_bitrate(None), None)
  958. self.assertEqual(parse_bitrate(''), None)
  959. self.assertEqual(parse_bitrate('300kbps'), 300)
  960. self.assertEqual(parse_bitrate('1500kbps'), 1500)
  961. self.assertEqual(parse_bitrate('300 kbps'), 300)
  962. def test_version_tuple(self):
  963. self.assertEqual(version_tuple('1'), (1,))
  964. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  965. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  966. def test_detect_exe_version(self):
  967. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  968. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  969. configuration: --prefix=/usr --extra-'''), '1.2.1')
  970. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  971. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  972. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  973. Trying to open render node...
  974. Success at /dev/dri/renderD128.
  975. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  976. def test_age_restricted(self):
  977. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  978. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  979. self.assertFalse(age_restricted(8, 10))
  980. self.assertTrue(age_restricted(18, 14))
  981. self.assertFalse(age_restricted(18, 18))
  982. def test_is_html(self):
  983. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  984. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  985. self.assertTrue(is_html( # UTF-8 with BOM
  986. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  987. self.assertTrue(is_html( # UTF-16-LE
  988. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  989. ))
  990. self.assertTrue(is_html( # UTF-16-BE
  991. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  992. ))
  993. self.assertTrue(is_html( # UTF-32-BE
  994. 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'))
  995. self.assertTrue(is_html( # UTF-32-LE
  996. 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'))
  997. def test_render_table(self):
  998. self.assertEqual(
  999. render_table(
  1000. ['a', 'bcd'],
  1001. [[123, 4], [9999, 51]]),
  1002. 'a bcd\n'
  1003. '123 4\n'
  1004. '9999 51')
  1005. def test_match_str(self):
  1006. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  1007. self.assertFalse(match_str('xy', {'x': 1200}))
  1008. self.assertTrue(match_str('!xy', {'x': 1200}))
  1009. self.assertTrue(match_str('x', {'x': 1200}))
  1010. self.assertFalse(match_str('!x', {'x': 1200}))
  1011. self.assertTrue(match_str('x', {'x': 0}))
  1012. self.assertFalse(match_str('x>0', {'x': 0}))
  1013. self.assertFalse(match_str('x>0', {}))
  1014. self.assertTrue(match_str('x>?0', {}))
  1015. self.assertTrue(match_str('x>1K', {'x': 1200}))
  1016. self.assertFalse(match_str('x>2K', {'x': 1200}))
  1017. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  1018. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  1019. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  1020. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  1021. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  1022. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  1023. self.assertFalse(match_str(
  1024. 'like_count > 100 & dislike_count <? 50 & description',
  1025. {'like_count': 90, 'description': 'foo'}))
  1026. self.assertTrue(match_str(
  1027. 'like_count > 100 & dislike_count <? 50 & description',
  1028. {'like_count': 190, 'description': 'foo'}))
  1029. self.assertFalse(match_str(
  1030. 'like_count > 100 & dislike_count <? 50 & description',
  1031. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  1032. self.assertFalse(match_str(
  1033. 'like_count > 100 & dislike_count <? 50 & description',
  1034. {'like_count': 190, 'dislike_count': 10}))
  1035. self.assertTrue(match_str('is_live', {'is_live': True}))
  1036. self.assertFalse(match_str('is_live', {'is_live': False}))
  1037. self.assertFalse(match_str('is_live', {'is_live': None}))
  1038. self.assertFalse(match_str('is_live', {}))
  1039. self.assertFalse(match_str('!is_live', {'is_live': True}))
  1040. self.assertTrue(match_str('!is_live', {'is_live': False}))
  1041. self.assertTrue(match_str('!is_live', {'is_live': None}))
  1042. self.assertTrue(match_str('!is_live', {}))
  1043. self.assertTrue(match_str('title', {'title': 'abc'}))
  1044. self.assertTrue(match_str('title', {'title': ''}))
  1045. self.assertFalse(match_str('!title', {'title': 'abc'}))
  1046. self.assertFalse(match_str('!title', {'title': ''}))
  1047. def test_parse_dfxp_time_expr(self):
  1048. self.assertEqual(parse_dfxp_time_expr(None), None)
  1049. self.assertEqual(parse_dfxp_time_expr(''), None)
  1050. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  1051. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  1052. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  1053. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  1054. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  1055. def test_dfxp2srt(self):
  1056. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  1057. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1058. <body>
  1059. <div xml:lang="en">
  1060. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  1061. <p begin="1" end="2"><br/></p>
  1062. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  1063. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  1064. <p begin="-1" end="-1">Ignore, two</p>
  1065. <p begin="3" dur="-1">Ignored, three</p>
  1066. </div>
  1067. </body>
  1068. </tt>'''.encode('utf-8')
  1069. srt_data = '''1
  1070. 00:00:00,000 --> 00:00:01,000
  1071. The following line contains Chinese characters and special symbols
  1072. 2
  1073. 00:00:01,000 --> 00:00:02,000
  1074. 3
  1075. 00:00:02,000 --> 00:00:03,000
  1076. Third
  1077. Line
  1078. '''
  1079. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  1080. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  1081. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1082. <body>
  1083. <div xml:lang="en">
  1084. <p begin="0" end="1">The first line</p>
  1085. </div>
  1086. </body>
  1087. </tt>'''.encode('utf-8')
  1088. srt_data = '''1
  1089. 00:00:00,000 --> 00:00:01,000
  1090. The first line
  1091. '''
  1092. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  1093. dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
  1094. <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">
  1095. <head>
  1096. <styling>
  1097. <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
  1098. <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
  1099. <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
  1100. <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
  1101. </styling>
  1102. </head>
  1103. <body tts:textAlign="center" style="s0">
  1104. <div>
  1105. <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
  1106. <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>
  1107. <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
  1108. <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>
  1109. </div>
  1110. </body>
  1111. </tt>'''.encode('utf-8')
  1112. srt_data = '''1
  1113. 00:00:02,080 --> 00:00:05,839
  1114. <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
  1115. 2
  1116. 00:00:02,080 --> 00:00:05,839
  1117. <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
  1118. </font>part 2</font></b>
  1119. 3
  1120. 00:00:05,839 --> 00:00:09,560
  1121. <u><font color="lime">line 3
  1122. part 3</font></u>
  1123. 4
  1124. 00:00:09,560 --> 00:00:12,359
  1125. <i><u><font color="yellow"><font color="lime">inner
  1126. </font>style</font></u></i>
  1127. '''
  1128. self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
  1129. dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
  1130. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1131. <body>
  1132. <div xml:lang="en">
  1133. <p begin="0" end="1">Line 1</p>
  1134. <p begin="1" end="2"></p>
  1135. </div>
  1136. </body>
  1137. </tt>'''.encode('utf-16')
  1138. srt_data = '''1
  1139. 00:00:00,000 --> 00:00:01,000
  1140. Line 1
  1141. 2
  1142. 00:00:01,000 --> 00:00:02,000
  1143. '''
  1144. self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
  1145. def test_cli_option(self):
  1146. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  1147. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  1148. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  1149. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  1150. def test_cli_valueless_option(self):
  1151. self.assertEqual(cli_valueless_option(
  1152. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  1153. self.assertEqual(cli_valueless_option(
  1154. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  1155. self.assertEqual(cli_valueless_option(
  1156. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  1157. self.assertEqual(cli_valueless_option(
  1158. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  1159. self.assertEqual(cli_valueless_option(
  1160. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  1161. self.assertEqual(cli_valueless_option(
  1162. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  1163. def test_cli_bool_option(self):
  1164. self.assertEqual(
  1165. cli_bool_option(
  1166. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  1167. ['--no-check-certificate', 'true'])
  1168. self.assertEqual(
  1169. cli_bool_option(
  1170. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  1171. ['--no-check-certificate=true'])
  1172. self.assertEqual(
  1173. cli_bool_option(
  1174. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1175. ['--check-certificate', 'false'])
  1176. self.assertEqual(
  1177. cli_bool_option(
  1178. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1179. ['--check-certificate=false'])
  1180. self.assertEqual(
  1181. cli_bool_option(
  1182. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1183. ['--check-certificate', 'true'])
  1184. self.assertEqual(
  1185. cli_bool_option(
  1186. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1187. ['--check-certificate=true'])
  1188. self.assertEqual(
  1189. cli_bool_option(
  1190. {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1191. [])
  1192. def test_ohdave_rsa_encrypt(self):
  1193. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  1194. e = 65537
  1195. self.assertEqual(
  1196. ohdave_rsa_encrypt(b'aa111222', e, N),
  1197. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  1198. def test_pkcs1pad(self):
  1199. data = [1, 2, 3]
  1200. padded_data = pkcs1pad(data, 32)
  1201. self.assertEqual(padded_data[:2], [0, 2])
  1202. self.assertEqual(padded_data[28:], [0, 1, 2, 3])
  1203. self.assertRaises(ValueError, pkcs1pad, data, 8)
  1204. def test_encode_base_n(self):
  1205. self.assertEqual(encode_base_n(0, 30), '0')
  1206. self.assertEqual(encode_base_n(80, 30), '2k')
  1207. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  1208. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  1209. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  1210. self.assertRaises(ValueError, encode_base_n, 0, 70)
  1211. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  1212. def test_caesar(self):
  1213. self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
  1214. self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
  1215. self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
  1216. self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
  1217. self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
  1218. self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
  1219. self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
  1220. self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
  1221. def test_rot47(self):
  1222. self.assertEqual(rot47('youtube-dl'), r'J@FEF36\5=')
  1223. self.assertEqual(rot47('YOUTUBE-DL'), r'*~&%&qt\s{')
  1224. def test_urshift(self):
  1225. self.assertEqual(urshift(3, 1), 1)
  1226. self.assertEqual(urshift(-3, 1), 2147483646)
  1227. def test_get_element_by_class(self):
  1228. html = '''
  1229. <span class="foo bar">nice</span>
  1230. '''
  1231. self.assertEqual(get_element_by_class('foo', html), 'nice')
  1232. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1233. def test_get_element_by_attribute(self):
  1234. html = '''
  1235. <span class="foo bar">nice</span>
  1236. '''
  1237. self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
  1238. self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
  1239. self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
  1240. html = '''
  1241. <div itemprop="author" itemscope>foo</div>
  1242. '''
  1243. self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
  1244. def test_get_elements_by_class(self):
  1245. html = '''
  1246. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1247. '''
  1248. self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
  1249. self.assertEqual(get_elements_by_class('no-such-class', html), [])
  1250. def test_get_elements_by_attribute(self):
  1251. html = '''
  1252. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1253. '''
  1254. self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
  1255. self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
  1256. self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
  1257. if __name__ == '__main__':
  1258. unittest.main()