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.

730 lines
31 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/bar', default='default'), 'default')
  239. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  240. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  241. def test_xpath_text(self):
  242. testxml = '''<root>
  243. <div>
  244. <p>Foo</p>
  245. </div>
  246. </root>'''
  247. doc = xml.etree.ElementTree.fromstring(testxml)
  248. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  249. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  250. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  251. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  252. def test_xpath_attr(self):
  253. testxml = '''<root>
  254. <div>
  255. <p x="a">Foo</p>
  256. </div>
  257. </root>'''
  258. doc = xml.etree.ElementTree.fromstring(testxml)
  259. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  260. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  261. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  262. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  263. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  264. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  265. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  266. def test_smuggle_url(self):
  267. data = {"ö": "ö", "abc": [3]}
  268. url = 'https://foo.bar/baz?x=y#a'
  269. smug_url = smuggle_url(url, data)
  270. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  271. self.assertEqual(url, unsmug_url)
  272. self.assertEqual(data, unsmug_data)
  273. res_url, res_data = unsmuggle_url(url)
  274. self.assertEqual(res_url, url)
  275. self.assertEqual(res_data, None)
  276. def test_shell_quote(self):
  277. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  278. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  279. def test_str_to_int(self):
  280. self.assertEqual(str_to_int('123,456'), 123456)
  281. self.assertEqual(str_to_int('123.456'), 123456)
  282. def test_url_basename(self):
  283. self.assertEqual(url_basename('http://foo.de/'), '')
  284. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  285. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  286. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  287. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  288. self.assertEqual(
  289. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  290. 'trailer.mp4')
  291. def test_parse_duration(self):
  292. self.assertEqual(parse_duration(None), None)
  293. self.assertEqual(parse_duration(False), None)
  294. self.assertEqual(parse_duration('invalid'), None)
  295. self.assertEqual(parse_duration('1'), 1)
  296. self.assertEqual(parse_duration('1337:12'), 80232)
  297. self.assertEqual(parse_duration('9:12:43'), 33163)
  298. self.assertEqual(parse_duration('12:00'), 720)
  299. self.assertEqual(parse_duration('00:01:01'), 61)
  300. self.assertEqual(parse_duration('x:y'), None)
  301. self.assertEqual(parse_duration('3h11m53s'), 11513)
  302. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  303. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  304. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  305. self.assertEqual(parse_duration('62m45s'), 3765)
  306. self.assertEqual(parse_duration('6m59s'), 419)
  307. self.assertEqual(parse_duration('49s'), 49)
  308. self.assertEqual(parse_duration('0h0m0s'), 0)
  309. self.assertEqual(parse_duration('0m0s'), 0)
  310. self.assertEqual(parse_duration('0s'), 0)
  311. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  312. self.assertEqual(parse_duration('T30M38S'), 1838)
  313. self.assertEqual(parse_duration('5 s'), 5)
  314. self.assertEqual(parse_duration('3 min'), 180)
  315. self.assertEqual(parse_duration('2.5 hours'), 9000)
  316. self.assertEqual(parse_duration('02:03:04'), 7384)
  317. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  318. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  319. self.assertEqual(parse_duration('87 Min.'), 5220)
  320. def test_fix_xml_ampersands(self):
  321. self.assertEqual(
  322. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  323. self.assertEqual(
  324. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  325. '"&amp;x=y&amp;wrong;&amp;z=a')
  326. self.assertEqual(
  327. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  328. '&amp;&apos;&gt;&lt;&quot;')
  329. self.assertEqual(
  330. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  331. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  332. def test_paged_list(self):
  333. def testPL(size, pagesize, sliceargs, expected):
  334. def get_page(pagenum):
  335. firstid = pagenum * pagesize
  336. upto = min(size, pagenum * pagesize + pagesize)
  337. for i in range(firstid, upto):
  338. yield i
  339. pl = OnDemandPagedList(get_page, pagesize)
  340. got = pl.getslice(*sliceargs)
  341. self.assertEqual(got, expected)
  342. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  343. got = iapl.getslice(*sliceargs)
  344. self.assertEqual(got, expected)
  345. testPL(5, 2, (), [0, 1, 2, 3, 4])
  346. testPL(5, 2, (1,), [1, 2, 3, 4])
  347. testPL(5, 2, (2,), [2, 3, 4])
  348. testPL(5, 2, (4,), [4])
  349. testPL(5, 2, (0, 3), [0, 1, 2])
  350. testPL(5, 2, (1, 4), [1, 2, 3])
  351. testPL(5, 2, (2, 99), [2, 3, 4])
  352. testPL(5, 2, (20, 99), [])
  353. def test_struct_unpack(self):
  354. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  355. def test_read_batch_urls(self):
  356. f = io.StringIO('''\xef\xbb\xbf foo
  357. bar\r
  358. baz
  359. # More after this line\r
  360. ; or after this
  361. bam''')
  362. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  363. def test_urlencode_postdata(self):
  364. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  365. self.assertTrue(isinstance(data, bytes))
  366. def test_parse_iso8601(self):
  367. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  368. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  369. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  370. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  371. def test_strip_jsonp(self):
  372. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  373. d = json.loads(stripped)
  374. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  375. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  376. d = json.loads(stripped)
  377. self.assertEqual(d, {'STATUS': 'OK'})
  378. def test_uppercase_escape(self):
  379. self.assertEqual(uppercase_escape(''), '')
  380. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  381. def test_lowercase_escape(self):
  382. self.assertEqual(lowercase_escape(''), '')
  383. self.assertEqual(lowercase_escape('\\u0026'), '&')
  384. def test_limit_length(self):
  385. self.assertEqual(limit_length(None, 12), None)
  386. self.assertEqual(limit_length('foo', 12), 'foo')
  387. self.assertTrue(
  388. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  389. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  390. def test_escape_rfc3986(self):
  391. reserved = "!*'();:@&=+$,/?#[]"
  392. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  393. self.assertEqual(escape_rfc3986(reserved), reserved)
  394. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  395. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  396. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  397. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  398. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  399. def test_escape_url(self):
  400. self.assertEqual(
  401. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  402. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  403. )
  404. self.assertEqual(
  405. 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'),
  406. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  407. )
  408. self.assertEqual(
  409. escape_url('http://тест.рф/фрагмент'),
  410. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  411. )
  412. self.assertEqual(
  413. escape_url('http://тест.рф/абв?абв=абв#абв'),
  414. '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'
  415. )
  416. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  417. def test_js_to_json_realworld(self):
  418. inp = '''{
  419. 'clip':{'provider':'pseudo'}
  420. }'''
  421. self.assertEqual(js_to_json(inp), '''{
  422. "clip":{"provider":"pseudo"}
  423. }''')
  424. json.loads(js_to_json(inp))
  425. inp = '''{
  426. 'playlist':[{'controls':{'all':null}}]
  427. }'''
  428. self.assertEqual(js_to_json(inp), '''{
  429. "playlist":[{"controls":{"all":null}}]
  430. }''')
  431. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  432. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  433. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  434. json_code = js_to_json(inp)
  435. self.assertEqual(json.loads(json_code), json.loads(inp))
  436. def test_js_to_json_edgecases(self):
  437. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  438. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  439. on = js_to_json('{"abc": true}')
  440. self.assertEqual(json.loads(on), {'abc': True})
  441. # Ignore JavaScript code as well
  442. on = js_to_json('''{
  443. "x": 1,
  444. y: "a",
  445. z: some.code
  446. }''')
  447. d = json.loads(on)
  448. self.assertEqual(d['x'], 1)
  449. self.assertEqual(d['y'], 'a')
  450. on = js_to_json('["abc", "def",]')
  451. self.assertEqual(json.loads(on), ['abc', 'def'])
  452. on = js_to_json('{"abc": "def",}')
  453. self.assertEqual(json.loads(on), {'abc': 'def'})
  454. def test_clean_html(self):
  455. self.assertEqual(clean_html('a:\nb'), 'a: b')
  456. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  457. def test_intlist_to_bytes(self):
  458. self.assertEqual(
  459. intlist_to_bytes([0, 1, 127, 128, 255]),
  460. b'\x00\x01\x7f\x80\xff')
  461. def test_args_to_str(self):
  462. self.assertEqual(
  463. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  464. 'foo ba/r -baz \'2 be\' \'\''
  465. )
  466. def test_parse_filesize(self):
  467. self.assertEqual(parse_filesize(None), None)
  468. self.assertEqual(parse_filesize(''), None)
  469. self.assertEqual(parse_filesize('91 B'), 91)
  470. self.assertEqual(parse_filesize('foobar'), None)
  471. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  472. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  473. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  474. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  475. def test_version_tuple(self):
  476. self.assertEqual(version_tuple('1'), (1,))
  477. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  478. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  479. def test_detect_exe_version(self):
  480. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  481. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  482. configuration: --prefix=/usr --extra-'''), '1.2.1')
  483. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  484. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  485. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  486. Trying to open render node...
  487. Success at /dev/dri/renderD128.
  488. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  489. def test_age_restricted(self):
  490. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  491. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  492. self.assertFalse(age_restricted(8, 10))
  493. self.assertTrue(age_restricted(18, 14))
  494. self.assertFalse(age_restricted(18, 18))
  495. def test_is_html(self):
  496. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  497. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  498. self.assertTrue(is_html( # UTF-8 with BOM
  499. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  500. self.assertTrue(is_html( # UTF-16-LE
  501. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  502. ))
  503. self.assertTrue(is_html( # UTF-16-BE
  504. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  505. ))
  506. self.assertTrue(is_html( # UTF-32-BE
  507. 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'))
  508. self.assertTrue(is_html( # UTF-32-LE
  509. 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'))
  510. def test_render_table(self):
  511. self.assertEqual(
  512. render_table(
  513. ['a', 'bcd'],
  514. [[123, 4], [9999, 51]]),
  515. 'a bcd\n'
  516. '123 4\n'
  517. '9999 51')
  518. def test_match_str(self):
  519. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  520. self.assertFalse(match_str('xy', {'x': 1200}))
  521. self.assertTrue(match_str('!xy', {'x': 1200}))
  522. self.assertTrue(match_str('x', {'x': 1200}))
  523. self.assertFalse(match_str('!x', {'x': 1200}))
  524. self.assertTrue(match_str('x', {'x': 0}))
  525. self.assertFalse(match_str('x>0', {'x': 0}))
  526. self.assertFalse(match_str('x>0', {}))
  527. self.assertTrue(match_str('x>?0', {}))
  528. self.assertTrue(match_str('x>1K', {'x': 1200}))
  529. self.assertFalse(match_str('x>2K', {'x': 1200}))
  530. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  531. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  532. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  533. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  534. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  535. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  536. self.assertFalse(match_str(
  537. 'like_count > 100 & dislike_count <? 50 & description',
  538. {'like_count': 90, 'description': 'foo'}))
  539. self.assertTrue(match_str(
  540. 'like_count > 100 & dislike_count <? 50 & description',
  541. {'like_count': 190, 'description': 'foo'}))
  542. self.assertFalse(match_str(
  543. 'like_count > 100 & dislike_count <? 50 & description',
  544. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  545. self.assertFalse(match_str(
  546. 'like_count > 100 & dislike_count <? 50 & description',
  547. {'like_count': 190, 'dislike_count': 10}))
  548. def test_parse_dfxp_time_expr(self):
  549. self.assertEqual(parse_dfxp_time_expr(None), 0.0)
  550. self.assertEqual(parse_dfxp_time_expr(''), 0.0)
  551. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  552. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  553. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  554. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  555. def test_dfxp2srt(self):
  556. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  557. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  558. <body>
  559. <div xml:lang="en">
  560. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  561. <p begin="1" end="2"><br/></p>
  562. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  563. </div>
  564. </body>
  565. </tt>'''
  566. srt_data = '''1
  567. 00:00:00,000 --> 00:00:01,000
  568. The following line contains Chinese characters and special symbols
  569. 2
  570. 00:00:01,000 --> 00:00:02,000
  571. 3
  572. 00:00:02,000 --> 00:00:03,000
  573. Third
  574. Line
  575. '''
  576. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  577. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  578. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  579. <body>
  580. <div xml:lang="en">
  581. <p begin="0" end="1">The first line</p>
  582. </div>
  583. </body>
  584. </tt>'''
  585. srt_data = '''1
  586. 00:00:00,000 --> 00:00:01,000
  587. The first line
  588. '''
  589. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  590. def test_cli_option(self):
  591. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  592. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  593. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  594. def test_cli_valueless_option(self):
  595. self.assertEqual(cli_valueless_option(
  596. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  597. self.assertEqual(cli_valueless_option(
  598. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  599. self.assertEqual(cli_valueless_option(
  600. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  601. self.assertEqual(cli_valueless_option(
  602. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  603. self.assertEqual(cli_valueless_option(
  604. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  605. self.assertEqual(cli_valueless_option(
  606. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  607. def test_cli_bool_option(self):
  608. self.assertEqual(
  609. cli_bool_option(
  610. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  611. ['--no-check-certificate', 'true'])
  612. self.assertEqual(
  613. cli_bool_option(
  614. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  615. ['--no-check-certificate=true'])
  616. self.assertEqual(
  617. cli_bool_option(
  618. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  619. ['--check-certificate', 'false'])
  620. self.assertEqual(
  621. cli_bool_option(
  622. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  623. ['--check-certificate=false'])
  624. self.assertEqual(
  625. cli_bool_option(
  626. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  627. ['--check-certificate', 'true'])
  628. self.assertEqual(
  629. cli_bool_option(
  630. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  631. ['--check-certificate=true'])
  632. if __name__ == '__main__':
  633. unittest.main()