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.

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