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.

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