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.

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