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.

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