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.

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