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.

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