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.

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