test_utils.py 25 KB

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