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.

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