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.

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