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.

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