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.

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