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.

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