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.

818 lines
36 KiB

10 years ago
10 years ago
10 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. DateRange,
  19. detect_exe_version,
  20. determine_ext,
  21. dict_get,
  22. encode_compat_str,
  23. encodeFilename,
  24. escape_rfc3986,
  25. escape_url,
  26. ExtractorError,
  27. find_xpath_attr,
  28. fix_xml_ampersands,
  29. InAdvancePagedList,
  30. intlist_to_bytes,
  31. is_html,
  32. js_to_json,
  33. limit_length,
  34. ohdave_rsa_encrypt,
  35. OnDemandPagedList,
  36. orderedSet,
  37. parse_duration,
  38. parse_filesize,
  39. parse_iso8601,
  40. read_batch_urls,
  41. sanitize_filename,
  42. sanitize_path,
  43. prepend_extension,
  44. replace_extension,
  45. remove_quotes,
  46. shell_quote,
  47. smuggle_url,
  48. str_to_int,
  49. strip_jsonp,
  50. struct_unpack,
  51. timeconvert,
  52. unescapeHTML,
  53. unified_strdate,
  54. unsmuggle_url,
  55. uppercase_escape,
  56. lowercase_escape,
  57. url_basename,
  58. urlencode_postdata,
  59. version_tuple,
  60. xpath_with_ns,
  61. xpath_element,
  62. xpath_text,
  63. xpath_attr,
  64. render_table,
  65. match_str,
  66. parse_dfxp_time_expr,
  67. dfxp2srt,
  68. cli_option,
  69. cli_valueless_option,
  70. cli_bool_option,
  71. )
  72. from youtube_dl.compat import (
  73. compat_etree_fromstring,
  74. )
  75. class TestUtil(unittest.TestCase):
  76. def test_timeconvert(self):
  77. self.assertTrue(timeconvert('') is None)
  78. self.assertTrue(timeconvert('bougrg') is None)
  79. def test_sanitize_filename(self):
  80. self.assertEqual(sanitize_filename('abc'), 'abc')
  81. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  82. self.assertEqual(sanitize_filename('123'), '123')
  83. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  84. self.assertFalse('/' in sanitize_filename('abc/de///'))
  85. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  86. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  87. self.assertEqual('yes no', sanitize_filename('yes? no'))
  88. self.assertEqual('this - that', sanitize_filename('this: that'))
  89. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  90. aumlaut = 'ä'
  91. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  92. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  93. self.assertEqual(sanitize_filename(tests), tests)
  94. self.assertEqual(
  95. sanitize_filename('New World record at 0:12:34'),
  96. 'New World record at 0_12_34')
  97. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  98. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  99. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  100. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  101. forbidden = '"\0\\/'
  102. for fc in forbidden:
  103. for fbc in forbidden:
  104. self.assertTrue(fbc not in sanitize_filename(fc))
  105. def test_sanitize_filename_restricted(self):
  106. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  107. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  108. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  109. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  110. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  111. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  112. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  113. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  114. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  115. tests = 'a\xe4b\u4e2d\u56fd\u7684c'
  116. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  117. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  118. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  119. for fc in forbidden:
  120. for fbc in forbidden:
  121. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  122. # Handle a common case more neatly
  123. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  124. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  125. # .. but make sure the file name is never empty
  126. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  127. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  128. def test_sanitize_ids(self):
  129. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  130. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  131. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  132. def test_sanitize_path(self):
  133. if sys.platform != 'win32':
  134. return
  135. self.assertEqual(sanitize_path('abc'), 'abc')
  136. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  137. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  138. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  139. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  140. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  141. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  142. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  143. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  144. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  145. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  146. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  147. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  148. self.assertEqual(
  149. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  150. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  151. self.assertEqual(
  152. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  153. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  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('../abc'), '..\\abc')
  158. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  159. self.assertEqual(sanitize_path('./abc'), 'abc')
  160. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  161. def test_prepend_extension(self):
  162. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  163. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  164. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  165. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  166. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  167. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  168. def test_replace_extension(self):
  169. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  170. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  171. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  172. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  173. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  174. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  175. def test_remove_quotes(self):
  176. self.assertEqual(remove_quotes(None), None)
  177. self.assertEqual(remove_quotes('"'), '"')
  178. self.assertEqual(remove_quotes("'"), "'")
  179. self.assertEqual(remove_quotes(';'), ';')
  180. self.assertEqual(remove_quotes('";'), '";')
  181. self.assertEqual(remove_quotes('""'), '')
  182. self.assertEqual(remove_quotes('";"'), ';')
  183. def test_ordered_set(self):
  184. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  185. self.assertEqual(orderedSet([]), [])
  186. self.assertEqual(orderedSet([1]), [1])
  187. # keep the list ordered
  188. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  189. def test_unescape_html(self):
  190. self.assertEqual(unescapeHTML('%20;'), '%20;')
  191. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  192. self.assertEqual(unescapeHTML('&#47;'), '/')
  193. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  194. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  195. def test_daterange(self):
  196. _20century = DateRange("19000101", "20000101")
  197. self.assertFalse("17890714" in _20century)
  198. _ac = DateRange("00010101")
  199. self.assertTrue("19690721" in _ac)
  200. _firstmilenium = DateRange(end="10000101")
  201. self.assertTrue("07110427" in _firstmilenium)
  202. def test_unified_dates(self):
  203. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  204. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  205. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  206. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  207. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  208. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  209. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  210. self.assertEqual(
  211. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  212. '20141126')
  213. self.assertEqual(
  214. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  215. '20150202')
  216. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  217. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  218. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  219. def test_determine_ext(self):
  220. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  221. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  222. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  223. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  224. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  225. def test_find_xpath_attr(self):
  226. testxml = '''<root>
  227. <node/>
  228. <node x="a"/>
  229. <node x="a" y="c" />
  230. <node x="b" y="d" />
  231. <node x="" />
  232. </root>'''
  233. doc = compat_etree_fromstring(testxml)
  234. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  235. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  236. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  237. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  238. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  239. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  240. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  241. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  242. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  243. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  244. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  245. def test_xpath_with_ns(self):
  246. testxml = '''<root xmlns:media="http://example.com/">
  247. <media:song>
  248. <media:author>The Author</media:author>
  249. <url>http://server.com/download.mp3</url>
  250. </media:song>
  251. </root>'''
  252. doc = compat_etree_fromstring(testxml)
  253. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  254. self.assertTrue(find('media:song') is not None)
  255. self.assertEqual(find('media:song/media:author').text, 'The Author')
  256. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  257. def test_xpath_element(self):
  258. doc = xml.etree.ElementTree.Element('root')
  259. div = xml.etree.ElementTree.SubElement(doc, 'div')
  260. p = xml.etree.ElementTree.SubElement(div, 'p')
  261. p.text = 'Foo'
  262. self.assertEqual(xpath_element(doc, 'div/p'), p)
  263. self.assertEqual(xpath_element(doc, ['div/p']), p)
  264. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  265. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  266. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  267. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  268. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  269. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  270. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  271. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  272. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  273. def test_xpath_text(self):
  274. testxml = '''<root>
  275. <div>
  276. <p>Foo</p>
  277. </div>
  278. </root>'''
  279. doc = compat_etree_fromstring(testxml)
  280. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  281. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  282. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  283. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  284. def test_xpath_attr(self):
  285. testxml = '''<root>
  286. <div>
  287. <p x="a">Foo</p>
  288. </div>
  289. </root>'''
  290. doc = compat_etree_fromstring(testxml)
  291. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  292. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  293. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  294. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  295. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  296. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  297. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  298. def test_smuggle_url(self):
  299. data = {"ö": "ö", "abc": [3]}
  300. url = 'https://foo.bar/baz?x=y#a'
  301. smug_url = smuggle_url(url, data)
  302. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  303. self.assertEqual(url, unsmug_url)
  304. self.assertEqual(data, unsmug_data)
  305. res_url, res_data = unsmuggle_url(url)
  306. self.assertEqual(res_url, url)
  307. self.assertEqual(res_data, None)
  308. def test_shell_quote(self):
  309. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  310. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  311. def test_str_to_int(self):
  312. self.assertEqual(str_to_int('123,456'), 123456)
  313. self.assertEqual(str_to_int('123.456'), 123456)
  314. def test_url_basename(self):
  315. self.assertEqual(url_basename('http://foo.de/'), '')
  316. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  317. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  318. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  319. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  320. self.assertEqual(
  321. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  322. 'trailer.mp4')
  323. def test_parse_duration(self):
  324. self.assertEqual(parse_duration(None), None)
  325. self.assertEqual(parse_duration(False), None)
  326. self.assertEqual(parse_duration('invalid'), None)
  327. self.assertEqual(parse_duration('1'), 1)
  328. self.assertEqual(parse_duration('1337:12'), 80232)
  329. self.assertEqual(parse_duration('9:12:43'), 33163)
  330. self.assertEqual(parse_duration('12:00'), 720)
  331. self.assertEqual(parse_duration('00:01:01'), 61)
  332. self.assertEqual(parse_duration('x:y'), None)
  333. self.assertEqual(parse_duration('3h11m53s'), 11513)
  334. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  335. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  336. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  337. self.assertEqual(parse_duration('62m45s'), 3765)
  338. self.assertEqual(parse_duration('6m59s'), 419)
  339. self.assertEqual(parse_duration('49s'), 49)
  340. self.assertEqual(parse_duration('0h0m0s'), 0)
  341. self.assertEqual(parse_duration('0m0s'), 0)
  342. self.assertEqual(parse_duration('0s'), 0)
  343. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  344. self.assertEqual(parse_duration('T30M38S'), 1838)
  345. self.assertEqual(parse_duration('5 s'), 5)
  346. self.assertEqual(parse_duration('3 min'), 180)
  347. self.assertEqual(parse_duration('2.5 hours'), 9000)
  348. self.assertEqual(parse_duration('02:03:04'), 7384)
  349. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  350. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  351. self.assertEqual(parse_duration('87 Min.'), 5220)
  352. def test_fix_xml_ampersands(self):
  353. self.assertEqual(
  354. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  355. self.assertEqual(
  356. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  357. '"&amp;x=y&amp;wrong;&amp;z=a')
  358. self.assertEqual(
  359. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  360. '&amp;&apos;&gt;&lt;&quot;')
  361. self.assertEqual(
  362. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  363. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  364. def test_paged_list(self):
  365. def testPL(size, pagesize, sliceargs, expected):
  366. def get_page(pagenum):
  367. firstid = pagenum * pagesize
  368. upto = min(size, pagenum * pagesize + pagesize)
  369. for i in range(firstid, upto):
  370. yield i
  371. pl = OnDemandPagedList(get_page, pagesize)
  372. got = pl.getslice(*sliceargs)
  373. self.assertEqual(got, expected)
  374. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  375. got = iapl.getslice(*sliceargs)
  376. self.assertEqual(got, expected)
  377. testPL(5, 2, (), [0, 1, 2, 3, 4])
  378. testPL(5, 2, (1,), [1, 2, 3, 4])
  379. testPL(5, 2, (2,), [2, 3, 4])
  380. testPL(5, 2, (4,), [4])
  381. testPL(5, 2, (0, 3), [0, 1, 2])
  382. testPL(5, 2, (1, 4), [1, 2, 3])
  383. testPL(5, 2, (2, 99), [2, 3, 4])
  384. testPL(5, 2, (20, 99), [])
  385. def test_struct_unpack(self):
  386. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  387. def test_read_batch_urls(self):
  388. f = io.StringIO('''\xef\xbb\xbf foo
  389. bar\r
  390. baz
  391. # More after this line\r
  392. ; or after this
  393. bam''')
  394. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  395. def test_urlencode_postdata(self):
  396. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  397. self.assertTrue(isinstance(data, bytes))
  398. def test_dict_get(self):
  399. FALSE_VALUES = {
  400. 'none': None,
  401. 'false': False,
  402. 'zero': 0,
  403. 'empty_string': '',
  404. 'empty_list': [],
  405. }
  406. d = FALSE_VALUES.copy()
  407. d['a'] = 42
  408. self.assertEqual(dict_get(d, 'a'), 42)
  409. self.assertEqual(dict_get(d, 'b'), None)
  410. self.assertEqual(dict_get(d, 'b', 42), 42)
  411. self.assertEqual(dict_get(d, ('a', )), 42)
  412. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  413. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  414. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  415. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  416. for key, false_value in FALSE_VALUES.items():
  417. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  418. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  419. def test_encode_compat_str(self):
  420. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  421. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  422. def test_parse_iso8601(self):
  423. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  424. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  425. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  426. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  427. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  428. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  429. def test_strip_jsonp(self):
  430. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  431. d = json.loads(stripped)
  432. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  433. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  434. d = json.loads(stripped)
  435. self.assertEqual(d, {'STATUS': 'OK'})
  436. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  437. d = json.loads(stripped)
  438. self.assertEqual(d, {'status': 'success'})
  439. def test_uppercase_escape(self):
  440. self.assertEqual(uppercase_escape(''), '')
  441. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  442. def test_lowercase_escape(self):
  443. self.assertEqual(lowercase_escape(''), '')
  444. self.assertEqual(lowercase_escape('\\u0026'), '&')
  445. def test_limit_length(self):
  446. self.assertEqual(limit_length(None, 12), None)
  447. self.assertEqual(limit_length('foo', 12), 'foo')
  448. self.assertTrue(
  449. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  450. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  451. def test_escape_rfc3986(self):
  452. reserved = "!*'();:@&=+$,/?#[]"
  453. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  454. self.assertEqual(escape_rfc3986(reserved), reserved)
  455. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  456. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  457. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  458. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  459. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  460. def test_escape_url(self):
  461. self.assertEqual(
  462. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  463. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  464. )
  465. self.assertEqual(
  466. 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'),
  467. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  468. )
  469. self.assertEqual(
  470. escape_url('http://тест.рф/фрагмент'),
  471. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  472. )
  473. self.assertEqual(
  474. escape_url('http://тест.рф/абв?абв=абв#абв'),
  475. 'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  476. )
  477. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  478. def test_js_to_json_realworld(self):
  479. inp = '''{
  480. 'clip':{'provider':'pseudo'}
  481. }'''
  482. self.assertEqual(js_to_json(inp), '''{
  483. "clip":{"provider":"pseudo"}
  484. }''')
  485. json.loads(js_to_json(inp))
  486. inp = '''{
  487. 'playlist':[{'controls':{'all':null}}]
  488. }'''
  489. self.assertEqual(js_to_json(inp), '''{
  490. "playlist":[{"controls":{"all":null}}]
  491. }''')
  492. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  493. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  494. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  495. json_code = js_to_json(inp)
  496. self.assertEqual(json.loads(json_code), json.loads(inp))
  497. def test_js_to_json_edgecases(self):
  498. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  499. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  500. on = js_to_json('{"abc": true}')
  501. self.assertEqual(json.loads(on), {'abc': True})
  502. # Ignore JavaScript code as well
  503. on = js_to_json('''{
  504. "x": 1,
  505. y: "a",
  506. z: some.code
  507. }''')
  508. d = json.loads(on)
  509. self.assertEqual(d['x'], 1)
  510. self.assertEqual(d['y'], 'a')
  511. on = js_to_json('["abc", "def",]')
  512. self.assertEqual(json.loads(on), ['abc', 'def'])
  513. on = js_to_json('{"abc": "def",}')
  514. self.assertEqual(json.loads(on), {'abc': 'def'})
  515. def test_clean_html(self):
  516. self.assertEqual(clean_html('a:\nb'), 'a: b')
  517. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  518. def test_intlist_to_bytes(self):
  519. self.assertEqual(
  520. intlist_to_bytes([0, 1, 127, 128, 255]),
  521. b'\x00\x01\x7f\x80\xff')
  522. def test_args_to_str(self):
  523. self.assertEqual(
  524. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  525. 'foo ba/r -baz \'2 be\' \'\''
  526. )
  527. def test_parse_filesize(self):
  528. self.assertEqual(parse_filesize(None), None)
  529. self.assertEqual(parse_filesize(''), None)
  530. self.assertEqual(parse_filesize('91 B'), 91)
  531. self.assertEqual(parse_filesize('foobar'), None)
  532. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  533. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  534. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  535. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  536. def test_version_tuple(self):
  537. self.assertEqual(version_tuple('1'), (1,))
  538. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  539. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  540. def test_detect_exe_version(self):
  541. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  542. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  543. configuration: --prefix=/usr --extra-'''), '1.2.1')
  544. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  545. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  546. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  547. Trying to open render node...
  548. Success at /dev/dri/renderD128.
  549. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  550. def test_age_restricted(self):
  551. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  552. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  553. self.assertFalse(age_restricted(8, 10))
  554. self.assertTrue(age_restricted(18, 14))
  555. self.assertFalse(age_restricted(18, 18))
  556. def test_is_html(self):
  557. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  558. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  559. self.assertTrue(is_html( # UTF-8 with BOM
  560. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  561. self.assertTrue(is_html( # UTF-16-LE
  562. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  563. ))
  564. self.assertTrue(is_html( # UTF-16-BE
  565. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  566. ))
  567. self.assertTrue(is_html( # UTF-32-BE
  568. 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'))
  569. self.assertTrue(is_html( # UTF-32-LE
  570. 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'))
  571. def test_render_table(self):
  572. self.assertEqual(
  573. render_table(
  574. ['a', 'bcd'],
  575. [[123, 4], [9999, 51]]),
  576. 'a bcd\n'
  577. '123 4\n'
  578. '9999 51')
  579. def test_match_str(self):
  580. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  581. self.assertFalse(match_str('xy', {'x': 1200}))
  582. self.assertTrue(match_str('!xy', {'x': 1200}))
  583. self.assertTrue(match_str('x', {'x': 1200}))
  584. self.assertFalse(match_str('!x', {'x': 1200}))
  585. self.assertTrue(match_str('x', {'x': 0}))
  586. self.assertFalse(match_str('x>0', {'x': 0}))
  587. self.assertFalse(match_str('x>0', {}))
  588. self.assertTrue(match_str('x>?0', {}))
  589. self.assertTrue(match_str('x>1K', {'x': 1200}))
  590. self.assertFalse(match_str('x>2K', {'x': 1200}))
  591. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  592. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  593. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  594. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  595. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  596. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  597. self.assertFalse(match_str(
  598. 'like_count > 100 & dislike_count <? 50 & description',
  599. {'like_count': 90, 'description': 'foo'}))
  600. self.assertTrue(match_str(
  601. 'like_count > 100 & dislike_count <? 50 & description',
  602. {'like_count': 190, 'description': 'foo'}))
  603. self.assertFalse(match_str(
  604. 'like_count > 100 & dislike_count <? 50 & description',
  605. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  606. self.assertFalse(match_str(
  607. 'like_count > 100 & dislike_count <? 50 & description',
  608. {'like_count': 190, 'dislike_count': 10}))
  609. def test_parse_dfxp_time_expr(self):
  610. self.assertEqual(parse_dfxp_time_expr(None), None)
  611. self.assertEqual(parse_dfxp_time_expr(''), None)
  612. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  613. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  614. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  615. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  616. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  617. def test_dfxp2srt(self):
  618. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  619. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  620. <body>
  621. <div xml:lang="en">
  622. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  623. <p begin="1" end="2"><br/></p>
  624. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  625. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  626. <p begin="-1" end="-1">Ignore, two</p>
  627. <p begin="3" dur="-1">Ignored, three</p>
  628. </div>
  629. </body>
  630. </tt>'''
  631. srt_data = '''1
  632. 00:00:00,000 --> 00:00:01,000
  633. The following line contains Chinese characters and special symbols
  634. 2
  635. 00:00:01,000 --> 00:00:02,000
  636. 3
  637. 00:00:02,000 --> 00:00:03,000
  638. Third
  639. Line
  640. '''
  641. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  642. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  643. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  644. <body>
  645. <div xml:lang="en">
  646. <p begin="0" end="1">The first line</p>
  647. </div>
  648. </body>
  649. </tt>'''
  650. srt_data = '''1
  651. 00:00:00,000 --> 00:00:01,000
  652. The first line
  653. '''
  654. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  655. def test_cli_option(self):
  656. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  657. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  658. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  659. def test_cli_valueless_option(self):
  660. self.assertEqual(cli_valueless_option(
  661. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  662. self.assertEqual(cli_valueless_option(
  663. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  664. self.assertEqual(cli_valueless_option(
  665. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  666. self.assertEqual(cli_valueless_option(
  667. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  668. self.assertEqual(cli_valueless_option(
  669. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  670. self.assertEqual(cli_valueless_option(
  671. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  672. def test_cli_bool_option(self):
  673. self.assertEqual(
  674. cli_bool_option(
  675. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  676. ['--no-check-certificate', 'true'])
  677. self.assertEqual(
  678. cli_bool_option(
  679. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  680. ['--no-check-certificate=true'])
  681. self.assertEqual(
  682. cli_bool_option(
  683. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  684. ['--check-certificate', 'false'])
  685. self.assertEqual(
  686. cli_bool_option(
  687. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  688. ['--check-certificate=false'])
  689. self.assertEqual(
  690. cli_bool_option(
  691. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  692. ['--check-certificate', 'true'])
  693. self.assertEqual(
  694. cli_bool_option(
  695. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  696. ['--check-certificate=true'])
  697. def test_ohdave_rsa_encrypt(self):
  698. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  699. e = 65537
  700. self.assertEqual(
  701. ohdave_rsa_encrypt(b'aa111222', e, N),
  702. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  703. def test_encode_base_n(self):
  704. self.assertEqual(encode_base_n(0, 30), '0')
  705. self.assertEqual(encode_base_n(80, 30), '2k')
  706. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  707. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  708. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  709. self.assertRaises(ValueError, encode_base_n, 0, 70)
  710. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  711. if __name__ == '__main__':
  712. unittest.main()