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.

1060 lines
48 KiB

10 years ago
10 years ago
10 years ago
8 years ago
8 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. clean_html,
  18. date_from_str,
  19. DateRange,
  20. detect_exe_version,
  21. determine_ext,
  22. dict_get,
  23. encode_compat_str,
  24. encodeFilename,
  25. escape_rfc3986,
  26. escape_url,
  27. extract_attributes,
  28. ExtractorError,
  29. find_xpath_attr,
  30. fix_xml_ampersands,
  31. get_element_by_class,
  32. InAdvancePagedList,
  33. intlist_to_bytes,
  34. is_html,
  35. js_to_json,
  36. limit_length,
  37. mimetype2ext,
  38. ohdave_rsa_encrypt,
  39. OnDemandPagedList,
  40. orderedSet,
  41. parse_age_limit,
  42. parse_duration,
  43. parse_filesize,
  44. parse_count,
  45. parse_iso8601,
  46. read_batch_urls,
  47. sanitize_filename,
  48. sanitize_path,
  49. prepend_extension,
  50. replace_extension,
  51. remove_start,
  52. remove_end,
  53. remove_quotes,
  54. shell_quote,
  55. smuggle_url,
  56. str_to_int,
  57. strip_jsonp,
  58. timeconvert,
  59. unescapeHTML,
  60. unified_strdate,
  61. unified_timestamp,
  62. unsmuggle_url,
  63. uppercase_escape,
  64. lowercase_escape,
  65. url_basename,
  66. urlencode_postdata,
  67. urshift,
  68. update_url_query,
  69. version_tuple,
  70. xpath_with_ns,
  71. xpath_element,
  72. xpath_text,
  73. xpath_attr,
  74. render_table,
  75. match_str,
  76. parse_dfxp_time_expr,
  77. dfxp2srt,
  78. cli_option,
  79. cli_valueless_option,
  80. cli_bool_option,
  81. parse_codecs,
  82. )
  83. from youtube_dl.compat import (
  84. compat_chr,
  85. compat_etree_fromstring,
  86. compat_urlparse,
  87. compat_parse_qs,
  88. )
  89. class TestUtil(unittest.TestCase):
  90. def test_timeconvert(self):
  91. self.assertTrue(timeconvert('') is None)
  92. self.assertTrue(timeconvert('bougrg') is None)
  93. def test_sanitize_filename(self):
  94. self.assertEqual(sanitize_filename('abc'), 'abc')
  95. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  96. self.assertEqual(sanitize_filename('123'), '123')
  97. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  98. self.assertFalse('/' in sanitize_filename('abc/de///'))
  99. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  100. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  101. self.assertEqual('yes no', sanitize_filename('yes? no'))
  102. self.assertEqual('this - that', sanitize_filename('this: that'))
  103. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  104. aumlaut = 'ä'
  105. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  106. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  107. self.assertEqual(sanitize_filename(tests), tests)
  108. self.assertEqual(
  109. sanitize_filename('New World record at 0:12:34'),
  110. 'New World record at 0_12_34')
  111. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  112. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  113. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  114. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  115. forbidden = '"\0\\/'
  116. for fc in forbidden:
  117. for fbc in forbidden:
  118. self.assertTrue(fbc not in sanitize_filename(fc))
  119. def test_sanitize_filename_restricted(self):
  120. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  121. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  122. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  123. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  124. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  125. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  126. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  127. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  128. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  129. tests = 'aäb\u4e2d\u56fd\u7684c'
  130. self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
  131. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  132. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  133. for fc in forbidden:
  134. for fbc in forbidden:
  135. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  136. # Handle a common case more neatly
  137. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  138. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  139. # .. but make sure the file name is never empty
  140. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  141. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  142. self.assertEqual(sanitize_filename(
  143. 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
  144. 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
  145. def test_sanitize_ids(self):
  146. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  147. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  148. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  149. def test_sanitize_path(self):
  150. if sys.platform != 'win32':
  151. return
  152. self.assertEqual(sanitize_path('abc'), 'abc')
  153. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  154. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  155. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  156. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  157. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  158. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  159. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  160. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  161. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  162. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  163. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  164. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  165. self.assertEqual(
  166. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  167. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  168. self.assertEqual(
  169. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  170. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  171. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  172. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  173. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  174. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  175. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  176. self.assertEqual(sanitize_path('./abc'), 'abc')
  177. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  178. def test_prepend_extension(self):
  179. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  180. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  181. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  182. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  183. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  184. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  185. def test_replace_extension(self):
  186. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  187. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  188. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  189. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  190. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  191. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  192. def test_remove_start(self):
  193. self.assertEqual(remove_start(None, 'A - '), None)
  194. self.assertEqual(remove_start('A - B', 'A - '), 'B')
  195. self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
  196. def test_remove_end(self):
  197. self.assertEqual(remove_end(None, ' - B'), None)
  198. self.assertEqual(remove_end('A - B', ' - B'), 'A')
  199. self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
  200. def test_remove_quotes(self):
  201. self.assertEqual(remove_quotes(None), None)
  202. self.assertEqual(remove_quotes('"'), '"')
  203. self.assertEqual(remove_quotes("'"), "'")
  204. self.assertEqual(remove_quotes(';'), ';')
  205. self.assertEqual(remove_quotes('";'), '";')
  206. self.assertEqual(remove_quotes('""'), '')
  207. self.assertEqual(remove_quotes('";"'), ';')
  208. def test_ordered_set(self):
  209. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  210. self.assertEqual(orderedSet([]), [])
  211. self.assertEqual(orderedSet([1]), [1])
  212. # keep the list ordered
  213. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  214. def test_unescape_html(self):
  215. self.assertEqual(unescapeHTML('%20;'), '%20;')
  216. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  217. self.assertEqual(unescapeHTML('&#47;'), '/')
  218. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  219. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  220. # HTML5 entities
  221. self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
  222. def test_date_from_str(self):
  223. self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
  224. self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
  225. self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
  226. self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
  227. self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
  228. def test_daterange(self):
  229. _20century = DateRange("19000101", "20000101")
  230. self.assertFalse("17890714" in _20century)
  231. _ac = DateRange("00010101")
  232. self.assertTrue("19690721" in _ac)
  233. _firstmilenium = DateRange(end="10000101")
  234. self.assertTrue("07110427" in _firstmilenium)
  235. def test_unified_dates(self):
  236. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  237. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  238. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  239. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  240. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  241. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  242. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  243. self.assertEqual(
  244. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  245. '20141126')
  246. self.assertEqual(
  247. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  248. '20150202')
  249. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  250. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  251. self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
  252. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  253. def test_unified_timestamps(self):
  254. self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
  255. self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
  256. self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
  257. self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
  258. self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
  259. self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
  260. self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
  261. self.assertEqual(
  262. unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
  263. 1417001400)
  264. self.assertEqual(
  265. unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
  266. 1422902860)
  267. self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
  268. self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
  269. self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
  270. self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
  271. self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
  272. def test_determine_ext(self):
  273. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  274. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  275. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  276. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  277. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  278. def test_find_xpath_attr(self):
  279. testxml = '''<root>
  280. <node/>
  281. <node x="a"/>
  282. <node x="a" y="c" />
  283. <node x="b" y="d" />
  284. <node x="" />
  285. </root>'''
  286. doc = compat_etree_fromstring(testxml)
  287. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  288. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  289. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  290. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  291. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  292. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  293. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  294. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  295. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  296. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  297. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  298. def test_xpath_with_ns(self):
  299. testxml = '''<root xmlns:media="http://example.com/">
  300. <media:song>
  301. <media:author>The Author</media:author>
  302. <url>http://server.com/download.mp3</url>
  303. </media:song>
  304. </root>'''
  305. doc = compat_etree_fromstring(testxml)
  306. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  307. self.assertTrue(find('media:song') is not None)
  308. self.assertEqual(find('media:song/media:author').text, 'The Author')
  309. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  310. def test_xpath_element(self):
  311. doc = xml.etree.ElementTree.Element('root')
  312. div = xml.etree.ElementTree.SubElement(doc, 'div')
  313. p = xml.etree.ElementTree.SubElement(div, 'p')
  314. p.text = 'Foo'
  315. self.assertEqual(xpath_element(doc, 'div/p'), p)
  316. self.assertEqual(xpath_element(doc, ['div/p']), p)
  317. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  318. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  319. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  320. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  321. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  322. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  323. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  324. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  325. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  326. def test_xpath_text(self):
  327. testxml = '''<root>
  328. <div>
  329. <p>Foo</p>
  330. </div>
  331. </root>'''
  332. doc = compat_etree_fromstring(testxml)
  333. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  334. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  335. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  336. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  337. def test_xpath_attr(self):
  338. testxml = '''<root>
  339. <div>
  340. <p x="a">Foo</p>
  341. </div>
  342. </root>'''
  343. doc = compat_etree_fromstring(testxml)
  344. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  345. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  346. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  347. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  348. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  349. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  350. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  351. def test_smuggle_url(self):
  352. data = {"ö": "ö", "abc": [3]}
  353. url = 'https://foo.bar/baz?x=y#a'
  354. smug_url = smuggle_url(url, data)
  355. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  356. self.assertEqual(url, unsmug_url)
  357. self.assertEqual(data, unsmug_data)
  358. res_url, res_data = unsmuggle_url(url)
  359. self.assertEqual(res_url, url)
  360. self.assertEqual(res_data, None)
  361. smug_url = smuggle_url(url, {'a': 'b'})
  362. smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
  363. res_url, res_data = unsmuggle_url(smug_smug_url)
  364. self.assertEqual(res_url, url)
  365. self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
  366. def test_shell_quote(self):
  367. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  368. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  369. def test_str_to_int(self):
  370. self.assertEqual(str_to_int('123,456'), 123456)
  371. self.assertEqual(str_to_int('123.456'), 123456)
  372. def test_url_basename(self):
  373. self.assertEqual(url_basename('http://foo.de/'), '')
  374. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  375. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  376. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  377. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  378. self.assertEqual(
  379. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  380. 'trailer.mp4')
  381. def test_parse_age_limit(self):
  382. self.assertEqual(parse_age_limit(None), None)
  383. self.assertEqual(parse_age_limit(False), None)
  384. self.assertEqual(parse_age_limit('invalid'), None)
  385. self.assertEqual(parse_age_limit(0), 0)
  386. self.assertEqual(parse_age_limit(18), 18)
  387. self.assertEqual(parse_age_limit(21), 21)
  388. self.assertEqual(parse_age_limit(22), None)
  389. self.assertEqual(parse_age_limit('18'), 18)
  390. self.assertEqual(parse_age_limit('18+'), 18)
  391. self.assertEqual(parse_age_limit('PG-13'), 13)
  392. self.assertEqual(parse_age_limit('TV-14'), 14)
  393. self.assertEqual(parse_age_limit('TV-MA'), 17)
  394. def test_parse_duration(self):
  395. self.assertEqual(parse_duration(None), None)
  396. self.assertEqual(parse_duration(False), None)
  397. self.assertEqual(parse_duration('invalid'), None)
  398. self.assertEqual(parse_duration('1'), 1)
  399. self.assertEqual(parse_duration('1337:12'), 80232)
  400. self.assertEqual(parse_duration('9:12:43'), 33163)
  401. self.assertEqual(parse_duration('12:00'), 720)
  402. self.assertEqual(parse_duration('00:01:01'), 61)
  403. self.assertEqual(parse_duration('x:y'), None)
  404. self.assertEqual(parse_duration('3h11m53s'), 11513)
  405. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  406. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  407. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  408. self.assertEqual(parse_duration('62m45s'), 3765)
  409. self.assertEqual(parse_duration('6m59s'), 419)
  410. self.assertEqual(parse_duration('49s'), 49)
  411. self.assertEqual(parse_duration('0h0m0s'), 0)
  412. self.assertEqual(parse_duration('0m0s'), 0)
  413. self.assertEqual(parse_duration('0s'), 0)
  414. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  415. self.assertEqual(parse_duration('T30M38S'), 1838)
  416. self.assertEqual(parse_duration('5 s'), 5)
  417. self.assertEqual(parse_duration('3 min'), 180)
  418. self.assertEqual(parse_duration('2.5 hours'), 9000)
  419. self.assertEqual(parse_duration('02:03:04'), 7384)
  420. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  421. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  422. self.assertEqual(parse_duration('87 Min.'), 5220)
  423. self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
  424. def test_fix_xml_ampersands(self):
  425. self.assertEqual(
  426. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  427. self.assertEqual(
  428. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  429. '"&amp;x=y&amp;wrong;&amp;z=a')
  430. self.assertEqual(
  431. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  432. '&amp;&apos;&gt;&lt;&quot;')
  433. self.assertEqual(
  434. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  435. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  436. def test_paged_list(self):
  437. def testPL(size, pagesize, sliceargs, expected):
  438. def get_page(pagenum):
  439. firstid = pagenum * pagesize
  440. upto = min(size, pagenum * pagesize + pagesize)
  441. for i in range(firstid, upto):
  442. yield i
  443. pl = OnDemandPagedList(get_page, pagesize)
  444. got = pl.getslice(*sliceargs)
  445. self.assertEqual(got, expected)
  446. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  447. got = iapl.getslice(*sliceargs)
  448. self.assertEqual(got, expected)
  449. testPL(5, 2, (), [0, 1, 2, 3, 4])
  450. testPL(5, 2, (1,), [1, 2, 3, 4])
  451. testPL(5, 2, (2,), [2, 3, 4])
  452. testPL(5, 2, (4,), [4])
  453. testPL(5, 2, (0, 3), [0, 1, 2])
  454. testPL(5, 2, (1, 4), [1, 2, 3])
  455. testPL(5, 2, (2, 99), [2, 3, 4])
  456. testPL(5, 2, (20, 99), [])
  457. def test_read_batch_urls(self):
  458. f = io.StringIO('''\xef\xbb\xbf foo
  459. bar\r
  460. baz
  461. # More after this line\r
  462. ; or after this
  463. bam''')
  464. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  465. def test_urlencode_postdata(self):
  466. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  467. self.assertTrue(isinstance(data, bytes))
  468. def test_update_url_query(self):
  469. def query_dict(url):
  470. return compat_parse_qs(compat_urlparse.urlparse(url).query)
  471. self.assertEqual(query_dict(update_url_query(
  472. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  473. query_dict('http://example.com/path?quality=HD&format=mp4'))
  474. self.assertEqual(query_dict(update_url_query(
  475. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  476. query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
  477. self.assertEqual(query_dict(update_url_query(
  478. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  479. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  480. self.assertEqual(query_dict(update_url_query(
  481. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  482. query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  483. self.assertEqual(query_dict(update_url_query(
  484. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  485. query_dict('http://example.com/path'))
  486. self.assertEqual(query_dict(update_url_query(
  487. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  488. query_dict('http://example.com/path?system=LINUX'))
  489. self.assertEqual(query_dict(update_url_query(
  490. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  491. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  492. self.assertEqual(query_dict(update_url_query(
  493. 'http://example.com/path', {'width': 1080, 'height': 720})),
  494. query_dict('http://example.com/path?width=1080&height=720'))
  495. self.assertEqual(query_dict(update_url_query(
  496. 'http://example.com/path', {'bitrate': 5020.43})),
  497. query_dict('http://example.com/path?bitrate=5020.43'))
  498. self.assertEqual(query_dict(update_url_query(
  499. 'http://example.com/path', {'test': '第二行тест'})),
  500. query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  501. def test_dict_get(self):
  502. FALSE_VALUES = {
  503. 'none': None,
  504. 'false': False,
  505. 'zero': 0,
  506. 'empty_string': '',
  507. 'empty_list': [],
  508. }
  509. d = FALSE_VALUES.copy()
  510. d['a'] = 42
  511. self.assertEqual(dict_get(d, 'a'), 42)
  512. self.assertEqual(dict_get(d, 'b'), None)
  513. self.assertEqual(dict_get(d, 'b', 42), 42)
  514. self.assertEqual(dict_get(d, ('a', )), 42)
  515. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  516. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  517. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  518. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  519. for key, false_value in FALSE_VALUES.items():
  520. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  521. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  522. def test_encode_compat_str(self):
  523. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  524. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  525. def test_parse_iso8601(self):
  526. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  527. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  528. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  529. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  530. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  531. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  532. def test_strip_jsonp(self):
  533. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  534. d = json.loads(stripped)
  535. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  536. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  537. d = json.loads(stripped)
  538. self.assertEqual(d, {'STATUS': 'OK'})
  539. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  540. d = json.loads(stripped)
  541. self.assertEqual(d, {'status': 'success'})
  542. def test_uppercase_escape(self):
  543. self.assertEqual(uppercase_escape(''), '')
  544. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  545. def test_lowercase_escape(self):
  546. self.assertEqual(lowercase_escape(''), '')
  547. self.assertEqual(lowercase_escape('\\u0026'), '&')
  548. def test_limit_length(self):
  549. self.assertEqual(limit_length(None, 12), None)
  550. self.assertEqual(limit_length('foo', 12), 'foo')
  551. self.assertTrue(
  552. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  553. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  554. def test_mimetype2ext(self):
  555. self.assertEqual(mimetype2ext(None), None)
  556. self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
  557. self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
  558. self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
  559. self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
  560. self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
  561. def test_parse_codecs(self):
  562. self.assertEqual(parse_codecs(''), {})
  563. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  564. 'vcodec': 'avc1.77.30',
  565. 'acodec': 'mp4a.40.2',
  566. })
  567. self.assertEqual(parse_codecs('mp4a.40.2'), {
  568. 'vcodec': 'none',
  569. 'acodec': 'mp4a.40.2',
  570. })
  571. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  572. 'vcodec': 'avc1.42001e',
  573. 'acodec': 'mp4a.40.5',
  574. })
  575. self.assertEqual(parse_codecs('avc3.640028'), {
  576. 'vcodec': 'avc3.640028',
  577. 'acodec': 'none',
  578. })
  579. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  580. 'vcodec': 'h264',
  581. 'acodec': 'aac',
  582. })
  583. def test_escape_rfc3986(self):
  584. reserved = "!*'();:@&=+$,/?#[]"
  585. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  586. self.assertEqual(escape_rfc3986(reserved), reserved)
  587. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  588. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  589. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  590. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  591. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  592. def test_escape_url(self):
  593. self.assertEqual(
  594. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  595. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  596. )
  597. self.assertEqual(
  598. 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'),
  599. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  600. )
  601. self.assertEqual(
  602. escape_url('http://тест.рф/фрагмент'),
  603. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  604. )
  605. self.assertEqual(
  606. escape_url('http://тест.рф/абв?абв=абв#абв'),
  607. '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'
  608. )
  609. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  610. def test_js_to_json_realworld(self):
  611. inp = '''{
  612. 'clip':{'provider':'pseudo'}
  613. }'''
  614. self.assertEqual(js_to_json(inp), '''{
  615. "clip":{"provider":"pseudo"}
  616. }''')
  617. json.loads(js_to_json(inp))
  618. inp = '''{
  619. 'playlist':[{'controls':{'all':null}}]
  620. }'''
  621. self.assertEqual(js_to_json(inp), '''{
  622. "playlist":[{"controls":{"all":null}}]
  623. }''')
  624. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  625. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  626. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  627. json_code = js_to_json(inp)
  628. self.assertEqual(json.loads(json_code), json.loads(inp))
  629. inp = '''{
  630. 0:{src:'skipped', type: 'application/dash+xml'},
  631. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  632. }'''
  633. self.assertEqual(js_to_json(inp), '''{
  634. "0":{"src":"skipped", "type": "application/dash+xml"},
  635. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  636. }''')
  637. inp = '''{"foo":101}'''
  638. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  639. inp = '''{"duration": "00:01:07"}'''
  640. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  641. def test_js_to_json_edgecases(self):
  642. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  643. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  644. on = js_to_json('{"abc": true}')
  645. self.assertEqual(json.loads(on), {'abc': True})
  646. # Ignore JavaScript code as well
  647. on = js_to_json('''{
  648. "x": 1,
  649. y: "a",
  650. z: some.code
  651. }''')
  652. d = json.loads(on)
  653. self.assertEqual(d['x'], 1)
  654. self.assertEqual(d['y'], 'a')
  655. on = js_to_json('["abc", "def",]')
  656. self.assertEqual(json.loads(on), ['abc', 'def'])
  657. on = js_to_json('{"abc": "def",}')
  658. self.assertEqual(json.loads(on), {'abc': 'def'})
  659. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  660. self.assertEqual(json.loads(on), {'0': ',]'})
  661. on = js_to_json(r'["<p>x<\/p>"]')
  662. self.assertEqual(json.loads(on), ['<p>x</p>'])
  663. on = js_to_json(r'["\xaa"]')
  664. self.assertEqual(json.loads(on), ['\u00aa'])
  665. on = js_to_json("['a\\\nb']")
  666. self.assertEqual(json.loads(on), ['ab'])
  667. on = js_to_json('{0xff:0xff}')
  668. self.assertEqual(json.loads(on), {'255': 255})
  669. on = js_to_json('{077:077}')
  670. self.assertEqual(json.loads(on), {'63': 63})
  671. on = js_to_json('{42:42}')
  672. self.assertEqual(json.loads(on), {'42': 42})
  673. def test_extract_attributes(self):
  674. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  675. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  676. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  677. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  678. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  679. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  680. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  681. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  682. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  683. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  684. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  685. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  686. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  687. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  688. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  689. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  690. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  691. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  692. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  693. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  694. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  695. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  696. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  697. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  698. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  699. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  700. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  701. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  702. # "Narrow" Python builds don't support unicode code points outside BMP.
  703. try:
  704. compat_chr(0x10000)
  705. supports_outside_bmp = True
  706. except ValueError:
  707. supports_outside_bmp = False
  708. if supports_outside_bmp:
  709. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  710. def test_clean_html(self):
  711. self.assertEqual(clean_html('a:\nb'), 'a: b')
  712. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  713. def test_intlist_to_bytes(self):
  714. self.assertEqual(
  715. intlist_to_bytes([0, 1, 127, 128, 255]),
  716. b'\x00\x01\x7f\x80\xff')
  717. def test_args_to_str(self):
  718. self.assertEqual(
  719. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  720. 'foo ba/r -baz \'2 be\' \'\''
  721. )
  722. def test_parse_filesize(self):
  723. self.assertEqual(parse_filesize(None), None)
  724. self.assertEqual(parse_filesize(''), None)
  725. self.assertEqual(parse_filesize('91 B'), 91)
  726. self.assertEqual(parse_filesize('foobar'), None)
  727. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  728. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  729. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  730. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  731. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  732. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  733. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  734. def test_parse_count(self):
  735. self.assertEqual(parse_count(None), None)
  736. self.assertEqual(parse_count(''), None)
  737. self.assertEqual(parse_count('0'), 0)
  738. self.assertEqual(parse_count('1000'), 1000)
  739. self.assertEqual(parse_count('1.000'), 1000)
  740. self.assertEqual(parse_count('1.1k'), 1100)
  741. self.assertEqual(parse_count('1.1kk'), 1100000)
  742. self.assertEqual(parse_count('1.1kk '), 1100000)
  743. self.assertEqual(parse_count('1.1kk views'), 1100000)
  744. def test_version_tuple(self):
  745. self.assertEqual(version_tuple('1'), (1,))
  746. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  747. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  748. def test_detect_exe_version(self):
  749. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  750. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  751. configuration: --prefix=/usr --extra-'''), '1.2.1')
  752. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  753. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  754. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  755. Trying to open render node...
  756. Success at /dev/dri/renderD128.
  757. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  758. def test_age_restricted(self):
  759. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  760. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  761. self.assertFalse(age_restricted(8, 10))
  762. self.assertTrue(age_restricted(18, 14))
  763. self.assertFalse(age_restricted(18, 18))
  764. def test_is_html(self):
  765. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  766. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  767. self.assertTrue(is_html( # UTF-8 with BOM
  768. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  769. self.assertTrue(is_html( # UTF-16-LE
  770. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  771. ))
  772. self.assertTrue(is_html( # UTF-16-BE
  773. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  774. ))
  775. self.assertTrue(is_html( # UTF-32-BE
  776. 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'))
  777. self.assertTrue(is_html( # UTF-32-LE
  778. 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'))
  779. def test_render_table(self):
  780. self.assertEqual(
  781. render_table(
  782. ['a', 'bcd'],
  783. [[123, 4], [9999, 51]]),
  784. 'a bcd\n'
  785. '123 4\n'
  786. '9999 51')
  787. def test_match_str(self):
  788. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  789. self.assertFalse(match_str('xy', {'x': 1200}))
  790. self.assertTrue(match_str('!xy', {'x': 1200}))
  791. self.assertTrue(match_str('x', {'x': 1200}))
  792. self.assertFalse(match_str('!x', {'x': 1200}))
  793. self.assertTrue(match_str('x', {'x': 0}))
  794. self.assertFalse(match_str('x>0', {'x': 0}))
  795. self.assertFalse(match_str('x>0', {}))
  796. self.assertTrue(match_str('x>?0', {}))
  797. self.assertTrue(match_str('x>1K', {'x': 1200}))
  798. self.assertFalse(match_str('x>2K', {'x': 1200}))
  799. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  800. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  801. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  802. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  803. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  804. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  805. self.assertFalse(match_str(
  806. 'like_count > 100 & dislike_count <? 50 & description',
  807. {'like_count': 90, 'description': 'foo'}))
  808. self.assertTrue(match_str(
  809. 'like_count > 100 & dislike_count <? 50 & description',
  810. {'like_count': 190, 'description': 'foo'}))
  811. self.assertFalse(match_str(
  812. 'like_count > 100 & dislike_count <? 50 & description',
  813. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  814. self.assertFalse(match_str(
  815. 'like_count > 100 & dislike_count <? 50 & description',
  816. {'like_count': 190, 'dislike_count': 10}))
  817. def test_parse_dfxp_time_expr(self):
  818. self.assertEqual(parse_dfxp_time_expr(None), None)
  819. self.assertEqual(parse_dfxp_time_expr(''), None)
  820. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  821. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  822. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  823. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  824. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  825. def test_dfxp2srt(self):
  826. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  827. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  828. <body>
  829. <div xml:lang="en">
  830. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  831. <p begin="1" end="2"><br/></p>
  832. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  833. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  834. <p begin="-1" end="-1">Ignore, two</p>
  835. <p begin="3" dur="-1">Ignored, three</p>
  836. </div>
  837. </body>
  838. </tt>'''
  839. srt_data = '''1
  840. 00:00:00,000 --> 00:00:01,000
  841. The following line contains Chinese characters and special symbols
  842. 2
  843. 00:00:01,000 --> 00:00:02,000
  844. 3
  845. 00:00:02,000 --> 00:00:03,000
  846. Third
  847. Line
  848. '''
  849. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  850. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  851. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  852. <body>
  853. <div xml:lang="en">
  854. <p begin="0" end="1">The first line</p>
  855. </div>
  856. </body>
  857. </tt>'''
  858. srt_data = '''1
  859. 00:00:00,000 --> 00:00:01,000
  860. The first line
  861. '''
  862. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  863. def test_cli_option(self):
  864. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  865. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  866. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  867. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  868. def test_cli_valueless_option(self):
  869. self.assertEqual(cli_valueless_option(
  870. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  871. self.assertEqual(cli_valueless_option(
  872. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  873. self.assertEqual(cli_valueless_option(
  874. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  875. self.assertEqual(cli_valueless_option(
  876. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  877. self.assertEqual(cli_valueless_option(
  878. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  879. self.assertEqual(cli_valueless_option(
  880. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  881. def test_cli_bool_option(self):
  882. self.assertEqual(
  883. cli_bool_option(
  884. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  885. ['--no-check-certificate', 'true'])
  886. self.assertEqual(
  887. cli_bool_option(
  888. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  889. ['--no-check-certificate=true'])
  890. self.assertEqual(
  891. cli_bool_option(
  892. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  893. ['--check-certificate', 'false'])
  894. self.assertEqual(
  895. cli_bool_option(
  896. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  897. ['--check-certificate=false'])
  898. self.assertEqual(
  899. cli_bool_option(
  900. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  901. ['--check-certificate', 'true'])
  902. self.assertEqual(
  903. cli_bool_option(
  904. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  905. ['--check-certificate=true'])
  906. def test_ohdave_rsa_encrypt(self):
  907. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  908. e = 65537
  909. self.assertEqual(
  910. ohdave_rsa_encrypt(b'aa111222', e, N),
  911. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  912. def test_encode_base_n(self):
  913. self.assertEqual(encode_base_n(0, 30), '0')
  914. self.assertEqual(encode_base_n(80, 30), '2k')
  915. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  916. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  917. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  918. self.assertRaises(ValueError, encode_base_n, 0, 70)
  919. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  920. def test_urshift(self):
  921. self.assertEqual(urshift(3, 1), 1)
  922. self.assertEqual(urshift(-3, 1), 2147483646)
  923. def test_get_element_by_class(self):
  924. html = '''
  925. <span class="foo bar">nice</span>
  926. '''
  927. self.assertEqual(get_element_by_class('foo', html), 'nice')
  928. self.assertEqual(get_element_by_class('no-such-class', html), None)
  929. if __name__ == '__main__':
  930. unittest.main()