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.

855 lines
38 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. encode_base_n,
  17. clean_html,
  18. DateRange,
  19. detect_exe_version,
  20. determine_ext,
  21. dict_get,
  22. encode_compat_str,
  23. encodeFilename,
  24. escape_rfc3986,
  25. escape_url,
  26. ExtractorError,
  27. find_xpath_attr,
  28. fix_xml_ampersands,
  29. InAdvancePagedList,
  30. intlist_to_bytes,
  31. is_html,
  32. js_to_json,
  33. limit_length,
  34. ohdave_rsa_encrypt,
  35. OnDemandPagedList,
  36. orderedSet,
  37. parse_duration,
  38. parse_filesize,
  39. parse_iso8601,
  40. read_batch_urls,
  41. sanitize_filename,
  42. sanitize_path,
  43. prepend_extension,
  44. replace_extension,
  45. remove_quotes,
  46. shell_quote,
  47. smuggle_url,
  48. str_to_int,
  49. strip_jsonp,
  50. struct_unpack,
  51. timeconvert,
  52. unescapeHTML,
  53. unified_strdate,
  54. unsmuggle_url,
  55. uppercase_escape,
  56. lowercase_escape,
  57. url_basename,
  58. urlencode_postdata,
  59. update_url_query,
  60. version_tuple,
  61. xpath_with_ns,
  62. xpath_element,
  63. xpath_text,
  64. xpath_attr,
  65. render_table,
  66. match_str,
  67. parse_dfxp_time_expr,
  68. dfxp2srt,
  69. cli_option,
  70. cli_valueless_option,
  71. cli_bool_option,
  72. )
  73. from youtube_dl.compat import (
  74. compat_etree_fromstring,
  75. compat_urlparse,
  76. compat_parse_qs,
  77. )
  78. class TestUtil(unittest.TestCase):
  79. def test_timeconvert(self):
  80. self.assertTrue(timeconvert('') is None)
  81. self.assertTrue(timeconvert('bougrg') is None)
  82. def test_sanitize_filename(self):
  83. self.assertEqual(sanitize_filename('abc'), 'abc')
  84. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  85. self.assertEqual(sanitize_filename('123'), '123')
  86. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  87. self.assertFalse('/' in sanitize_filename('abc/de///'))
  88. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  89. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  90. self.assertEqual('yes no', sanitize_filename('yes? no'))
  91. self.assertEqual('this - that', sanitize_filename('this: that'))
  92. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  93. aumlaut = 'ä'
  94. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  95. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  96. self.assertEqual(sanitize_filename(tests), tests)
  97. self.assertEqual(
  98. sanitize_filename('New World record at 0:12:34'),
  99. 'New World record at 0_12_34')
  100. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  101. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  102. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  103. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  104. forbidden = '"\0\\/'
  105. for fc in forbidden:
  106. for fbc in forbidden:
  107. self.assertTrue(fbc not in sanitize_filename(fc))
  108. def test_sanitize_filename_restricted(self):
  109. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  110. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  111. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  112. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  113. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  114. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  115. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  116. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  117. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  118. tests = 'a\xe4b\u4e2d\u56fd\u7684c'
  119. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  120. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  121. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  122. for fc in forbidden:
  123. for fbc in forbidden:
  124. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  125. # Handle a common case more neatly
  126. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  127. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  128. # .. but make sure the file name is never empty
  129. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  130. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  131. def test_sanitize_ids(self):
  132. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  133. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  134. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  135. def test_sanitize_path(self):
  136. if sys.platform != 'win32':
  137. return
  138. self.assertEqual(sanitize_path('abc'), 'abc')
  139. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  140. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  141. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  142. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  143. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  144. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  145. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  146. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  147. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  148. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  149. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  150. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  151. self.assertEqual(
  152. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  153. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  154. self.assertEqual(
  155. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  156. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  157. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  158. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  159. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  160. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  161. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  162. self.assertEqual(sanitize_path('./abc'), 'abc')
  163. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  164. def test_prepend_extension(self):
  165. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  166. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  167. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  168. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  169. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  170. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  171. def test_replace_extension(self):
  172. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  173. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  174. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  175. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  176. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  177. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  178. def test_remove_quotes(self):
  179. self.assertEqual(remove_quotes(None), None)
  180. self.assertEqual(remove_quotes('"'), '"')
  181. self.assertEqual(remove_quotes("'"), "'")
  182. self.assertEqual(remove_quotes(';'), ';')
  183. self.assertEqual(remove_quotes('";'), '";')
  184. self.assertEqual(remove_quotes('""'), '')
  185. self.assertEqual(remove_quotes('";"'), ';')
  186. def test_ordered_set(self):
  187. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  188. self.assertEqual(orderedSet([]), [])
  189. self.assertEqual(orderedSet([1]), [1])
  190. # keep the list ordered
  191. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  192. def test_unescape_html(self):
  193. self.assertEqual(unescapeHTML('%20;'), '%20;')
  194. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  195. self.assertEqual(unescapeHTML('&#47;'), '/')
  196. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  197. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  198. def test_daterange(self):
  199. _20century = DateRange("19000101", "20000101")
  200. self.assertFalse("17890714" in _20century)
  201. _ac = DateRange("00010101")
  202. self.assertTrue("19690721" in _ac)
  203. _firstmilenium = DateRange(end="10000101")
  204. self.assertTrue("07110427" in _firstmilenium)
  205. def test_unified_dates(self):
  206. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  207. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  208. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  209. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  210. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  211. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  212. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  213. self.assertEqual(
  214. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  215. '20141126')
  216. self.assertEqual(
  217. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  218. '20150202')
  219. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  220. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  221. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  222. def test_determine_ext(self):
  223. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  224. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  225. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  226. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  227. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  228. def test_find_xpath_attr(self):
  229. testxml = '''<root>
  230. <node/>
  231. <node x="a"/>
  232. <node x="a" y="c" />
  233. <node x="b" y="d" />
  234. <node x="" />
  235. </root>'''
  236. doc = compat_etree_fromstring(testxml)
  237. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  238. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  239. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  240. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  241. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  242. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  243. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  244. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  245. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  246. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  247. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  248. def test_xpath_with_ns(self):
  249. testxml = '''<root xmlns:media="http://example.com/">
  250. <media:song>
  251. <media:author>The Author</media:author>
  252. <url>http://server.com/download.mp3</url>
  253. </media:song>
  254. </root>'''
  255. doc = compat_etree_fromstring(testxml)
  256. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  257. self.assertTrue(find('media:song') is not None)
  258. self.assertEqual(find('media:song/media:author').text, 'The Author')
  259. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  260. def test_xpath_element(self):
  261. doc = xml.etree.ElementTree.Element('root')
  262. div = xml.etree.ElementTree.SubElement(doc, 'div')
  263. p = xml.etree.ElementTree.SubElement(div, 'p')
  264. p.text = 'Foo'
  265. self.assertEqual(xpath_element(doc, 'div/p'), p)
  266. self.assertEqual(xpath_element(doc, ['div/p']), p)
  267. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  268. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  269. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  270. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  271. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  272. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  273. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  274. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  275. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  276. def test_xpath_text(self):
  277. testxml = '''<root>
  278. <div>
  279. <p>Foo</p>
  280. </div>
  281. </root>'''
  282. doc = compat_etree_fromstring(testxml)
  283. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  284. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  285. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  286. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  287. def test_xpath_attr(self):
  288. testxml = '''<root>
  289. <div>
  290. <p x="a">Foo</p>
  291. </div>
  292. </root>'''
  293. doc = compat_etree_fromstring(testxml)
  294. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  295. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  296. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  297. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  298. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  299. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  300. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  301. def test_smuggle_url(self):
  302. data = {"ö": "ö", "abc": [3]}
  303. url = 'https://foo.bar/baz?x=y#a'
  304. smug_url = smuggle_url(url, data)
  305. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  306. self.assertEqual(url, unsmug_url)
  307. self.assertEqual(data, unsmug_data)
  308. res_url, res_data = unsmuggle_url(url)
  309. self.assertEqual(res_url, url)
  310. self.assertEqual(res_data, None)
  311. def test_shell_quote(self):
  312. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  313. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  314. def test_str_to_int(self):
  315. self.assertEqual(str_to_int('123,456'), 123456)
  316. self.assertEqual(str_to_int('123.456'), 123456)
  317. def test_url_basename(self):
  318. self.assertEqual(url_basename('http://foo.de/'), '')
  319. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  320. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  321. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  322. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  323. self.assertEqual(
  324. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  325. 'trailer.mp4')
  326. def test_parse_duration(self):
  327. self.assertEqual(parse_duration(None), None)
  328. self.assertEqual(parse_duration(False), None)
  329. self.assertEqual(parse_duration('invalid'), None)
  330. self.assertEqual(parse_duration('1'), 1)
  331. self.assertEqual(parse_duration('1337:12'), 80232)
  332. self.assertEqual(parse_duration('9:12:43'), 33163)
  333. self.assertEqual(parse_duration('12:00'), 720)
  334. self.assertEqual(parse_duration('00:01:01'), 61)
  335. self.assertEqual(parse_duration('x:y'), None)
  336. self.assertEqual(parse_duration('3h11m53s'), 11513)
  337. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  338. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  339. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  340. self.assertEqual(parse_duration('62m45s'), 3765)
  341. self.assertEqual(parse_duration('6m59s'), 419)
  342. self.assertEqual(parse_duration('49s'), 49)
  343. self.assertEqual(parse_duration('0h0m0s'), 0)
  344. self.assertEqual(parse_duration('0m0s'), 0)
  345. self.assertEqual(parse_duration('0s'), 0)
  346. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  347. self.assertEqual(parse_duration('T30M38S'), 1838)
  348. self.assertEqual(parse_duration('5 s'), 5)
  349. self.assertEqual(parse_duration('3 min'), 180)
  350. self.assertEqual(parse_duration('2.5 hours'), 9000)
  351. self.assertEqual(parse_duration('02:03:04'), 7384)
  352. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  353. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  354. self.assertEqual(parse_duration('87 Min.'), 5220)
  355. def test_fix_xml_ampersands(self):
  356. self.assertEqual(
  357. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  358. self.assertEqual(
  359. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  360. '"&amp;x=y&amp;wrong;&amp;z=a')
  361. self.assertEqual(
  362. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  363. '&amp;&apos;&gt;&lt;&quot;')
  364. self.assertEqual(
  365. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  366. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  367. def test_paged_list(self):
  368. def testPL(size, pagesize, sliceargs, expected):
  369. def get_page(pagenum):
  370. firstid = pagenum * pagesize
  371. upto = min(size, pagenum * pagesize + pagesize)
  372. for i in range(firstid, upto):
  373. yield i
  374. pl = OnDemandPagedList(get_page, pagesize)
  375. got = pl.getslice(*sliceargs)
  376. self.assertEqual(got, expected)
  377. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  378. got = iapl.getslice(*sliceargs)
  379. self.assertEqual(got, expected)
  380. testPL(5, 2, (), [0, 1, 2, 3, 4])
  381. testPL(5, 2, (1,), [1, 2, 3, 4])
  382. testPL(5, 2, (2,), [2, 3, 4])
  383. testPL(5, 2, (4,), [4])
  384. testPL(5, 2, (0, 3), [0, 1, 2])
  385. testPL(5, 2, (1, 4), [1, 2, 3])
  386. testPL(5, 2, (2, 99), [2, 3, 4])
  387. testPL(5, 2, (20, 99), [])
  388. def test_struct_unpack(self):
  389. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  390. def test_read_batch_urls(self):
  391. f = io.StringIO('''\xef\xbb\xbf foo
  392. bar\r
  393. baz
  394. # More after this line\r
  395. ; or after this
  396. bam''')
  397. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  398. def test_urlencode_postdata(self):
  399. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  400. self.assertTrue(isinstance(data, bytes))
  401. def test_update_url_query(self):
  402. def query_dict(url):
  403. return compat_parse_qs(compat_urlparse.urlparse(url).query)
  404. self.assertEqual(query_dict(update_url_query(
  405. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  406. query_dict('http://example.com/path?quality=HD&format=mp4'))
  407. self.assertEqual(query_dict(update_url_query(
  408. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  409. query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
  410. self.assertEqual(query_dict(update_url_query(
  411. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  412. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  413. self.assertEqual(query_dict(update_url_query(
  414. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  415. query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  416. self.assertEqual(query_dict(update_url_query(
  417. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  418. query_dict('http://example.com/path'))
  419. self.assertEqual(query_dict(update_url_query(
  420. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  421. query_dict('http://example.com/path?system=LINUX'))
  422. self.assertEqual(query_dict(update_url_query(
  423. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  424. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  425. self.assertEqual(query_dict(update_url_query(
  426. 'http://example.com/path', {'width': 1080, 'height': 720})),
  427. query_dict('http://example.com/path?width=1080&height=720'))
  428. self.assertEqual(query_dict(update_url_query(
  429. 'http://example.com/path', {'bitrate': 5020.43})),
  430. query_dict('http://example.com/path?bitrate=5020.43'))
  431. self.assertEqual(query_dict(update_url_query(
  432. 'http://example.com/path', {'test': '第二行тест'})),
  433. query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  434. def test_dict_get(self):
  435. FALSE_VALUES = {
  436. 'none': None,
  437. 'false': False,
  438. 'zero': 0,
  439. 'empty_string': '',
  440. 'empty_list': [],
  441. }
  442. d = FALSE_VALUES.copy()
  443. d['a'] = 42
  444. self.assertEqual(dict_get(d, 'a'), 42)
  445. self.assertEqual(dict_get(d, 'b'), None)
  446. self.assertEqual(dict_get(d, 'b', 42), 42)
  447. self.assertEqual(dict_get(d, ('a', )), 42)
  448. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  449. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  450. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  451. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  452. for key, false_value in FALSE_VALUES.items():
  453. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  454. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  455. def test_encode_compat_str(self):
  456. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  457. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  458. def test_parse_iso8601(self):
  459. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  460. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  461. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  462. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  463. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  464. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  465. def test_strip_jsonp(self):
  466. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  467. d = json.loads(stripped)
  468. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  469. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  470. d = json.loads(stripped)
  471. self.assertEqual(d, {'STATUS': 'OK'})
  472. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  473. d = json.loads(stripped)
  474. self.assertEqual(d, {'status': 'success'})
  475. def test_uppercase_escape(self):
  476. self.assertEqual(uppercase_escape(''), '')
  477. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  478. def test_lowercase_escape(self):
  479. self.assertEqual(lowercase_escape(''), '')
  480. self.assertEqual(lowercase_escape('\\u0026'), '&')
  481. def test_limit_length(self):
  482. self.assertEqual(limit_length(None, 12), None)
  483. self.assertEqual(limit_length('foo', 12), 'foo')
  484. self.assertTrue(
  485. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  486. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  487. def test_escape_rfc3986(self):
  488. reserved = "!*'();:@&=+$,/?#[]"
  489. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  490. self.assertEqual(escape_rfc3986(reserved), reserved)
  491. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  492. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  493. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  494. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  495. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  496. def test_escape_url(self):
  497. self.assertEqual(
  498. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  499. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  500. )
  501. self.assertEqual(
  502. 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'),
  503. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  504. )
  505. self.assertEqual(
  506. escape_url('http://тест.рф/фрагмент'),
  507. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  508. )
  509. self.assertEqual(
  510. escape_url('http://тест.рф/абв?абв=абв#абв'),
  511. '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'
  512. )
  513. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  514. def test_js_to_json_realworld(self):
  515. inp = '''{
  516. 'clip':{'provider':'pseudo'}
  517. }'''
  518. self.assertEqual(js_to_json(inp), '''{
  519. "clip":{"provider":"pseudo"}
  520. }''')
  521. json.loads(js_to_json(inp))
  522. inp = '''{
  523. 'playlist':[{'controls':{'all':null}}]
  524. }'''
  525. self.assertEqual(js_to_json(inp), '''{
  526. "playlist":[{"controls":{"all":null}}]
  527. }''')
  528. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  529. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  530. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  531. json_code = js_to_json(inp)
  532. self.assertEqual(json.loads(json_code), json.loads(inp))
  533. def test_js_to_json_edgecases(self):
  534. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  535. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  536. on = js_to_json('{"abc": true}')
  537. self.assertEqual(json.loads(on), {'abc': True})
  538. # Ignore JavaScript code as well
  539. on = js_to_json('''{
  540. "x": 1,
  541. y: "a",
  542. z: some.code
  543. }''')
  544. d = json.loads(on)
  545. self.assertEqual(d['x'], 1)
  546. self.assertEqual(d['y'], 'a')
  547. on = js_to_json('["abc", "def",]')
  548. self.assertEqual(json.loads(on), ['abc', 'def'])
  549. on = js_to_json('{"abc": "def",}')
  550. self.assertEqual(json.loads(on), {'abc': 'def'})
  551. def test_clean_html(self):
  552. self.assertEqual(clean_html('a:\nb'), 'a: b')
  553. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  554. def test_intlist_to_bytes(self):
  555. self.assertEqual(
  556. intlist_to_bytes([0, 1, 127, 128, 255]),
  557. b'\x00\x01\x7f\x80\xff')
  558. def test_args_to_str(self):
  559. self.assertEqual(
  560. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  561. 'foo ba/r -baz \'2 be\' \'\''
  562. )
  563. def test_parse_filesize(self):
  564. self.assertEqual(parse_filesize(None), None)
  565. self.assertEqual(parse_filesize(''), None)
  566. self.assertEqual(parse_filesize('91 B'), 91)
  567. self.assertEqual(parse_filesize('foobar'), None)
  568. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  569. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  570. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  571. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  572. def test_version_tuple(self):
  573. self.assertEqual(version_tuple('1'), (1,))
  574. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  575. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  576. def test_detect_exe_version(self):
  577. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  578. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  579. configuration: --prefix=/usr --extra-'''), '1.2.1')
  580. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  581. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  582. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  583. Trying to open render node...
  584. Success at /dev/dri/renderD128.
  585. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  586. def test_age_restricted(self):
  587. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  588. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  589. self.assertFalse(age_restricted(8, 10))
  590. self.assertTrue(age_restricted(18, 14))
  591. self.assertFalse(age_restricted(18, 18))
  592. def test_is_html(self):
  593. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  594. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  595. self.assertTrue(is_html( # UTF-8 with BOM
  596. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  597. self.assertTrue(is_html( # UTF-16-LE
  598. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  599. ))
  600. self.assertTrue(is_html( # UTF-16-BE
  601. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  602. ))
  603. self.assertTrue(is_html( # UTF-32-BE
  604. 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'))
  605. self.assertTrue(is_html( # UTF-32-LE
  606. 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'))
  607. def test_render_table(self):
  608. self.assertEqual(
  609. render_table(
  610. ['a', 'bcd'],
  611. [[123, 4], [9999, 51]]),
  612. 'a bcd\n'
  613. '123 4\n'
  614. '9999 51')
  615. def test_match_str(self):
  616. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  617. self.assertFalse(match_str('xy', {'x': 1200}))
  618. self.assertTrue(match_str('!xy', {'x': 1200}))
  619. self.assertTrue(match_str('x', {'x': 1200}))
  620. self.assertFalse(match_str('!x', {'x': 1200}))
  621. self.assertTrue(match_str('x', {'x': 0}))
  622. self.assertFalse(match_str('x>0', {'x': 0}))
  623. self.assertFalse(match_str('x>0', {}))
  624. self.assertTrue(match_str('x>?0', {}))
  625. self.assertTrue(match_str('x>1K', {'x': 1200}))
  626. self.assertFalse(match_str('x>2K', {'x': 1200}))
  627. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  628. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  629. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  630. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  631. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  632. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  633. self.assertFalse(match_str(
  634. 'like_count > 100 & dislike_count <? 50 & description',
  635. {'like_count': 90, 'description': 'foo'}))
  636. self.assertTrue(match_str(
  637. 'like_count > 100 & dislike_count <? 50 & description',
  638. {'like_count': 190, 'description': 'foo'}))
  639. self.assertFalse(match_str(
  640. 'like_count > 100 & dislike_count <? 50 & description',
  641. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  642. self.assertFalse(match_str(
  643. 'like_count > 100 & dislike_count <? 50 & description',
  644. {'like_count': 190, 'dislike_count': 10}))
  645. def test_parse_dfxp_time_expr(self):
  646. self.assertEqual(parse_dfxp_time_expr(None), None)
  647. self.assertEqual(parse_dfxp_time_expr(''), None)
  648. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  649. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  650. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  651. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  652. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  653. def test_dfxp2srt(self):
  654. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  655. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  656. <body>
  657. <div xml:lang="en">
  658. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  659. <p begin="1" end="2"><br/></p>
  660. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  661. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  662. <p begin="-1" end="-1">Ignore, two</p>
  663. <p begin="3" dur="-1">Ignored, three</p>
  664. </div>
  665. </body>
  666. </tt>'''
  667. srt_data = '''1
  668. 00:00:00,000 --> 00:00:01,000
  669. The following line contains Chinese characters and special symbols
  670. 2
  671. 00:00:01,000 --> 00:00:02,000
  672. 3
  673. 00:00:02,000 --> 00:00:03,000
  674. Third
  675. Line
  676. '''
  677. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  678. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  679. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  680. <body>
  681. <div xml:lang="en">
  682. <p begin="0" end="1">The first line</p>
  683. </div>
  684. </body>
  685. </tt>'''
  686. srt_data = '''1
  687. 00:00:00,000 --> 00:00:01,000
  688. The first line
  689. '''
  690. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  691. def test_cli_option(self):
  692. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  693. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  694. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  695. def test_cli_valueless_option(self):
  696. self.assertEqual(cli_valueless_option(
  697. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  698. self.assertEqual(cli_valueless_option(
  699. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  700. self.assertEqual(cli_valueless_option(
  701. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  702. self.assertEqual(cli_valueless_option(
  703. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  704. self.assertEqual(cli_valueless_option(
  705. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  706. self.assertEqual(cli_valueless_option(
  707. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  708. def test_cli_bool_option(self):
  709. self.assertEqual(
  710. cli_bool_option(
  711. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  712. ['--no-check-certificate', 'true'])
  713. self.assertEqual(
  714. cli_bool_option(
  715. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  716. ['--no-check-certificate=true'])
  717. self.assertEqual(
  718. cli_bool_option(
  719. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  720. ['--check-certificate', 'false'])
  721. self.assertEqual(
  722. cli_bool_option(
  723. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  724. ['--check-certificate=false'])
  725. self.assertEqual(
  726. cli_bool_option(
  727. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  728. ['--check-certificate', 'true'])
  729. self.assertEqual(
  730. cli_bool_option(
  731. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  732. ['--check-certificate=true'])
  733. def test_ohdave_rsa_encrypt(self):
  734. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  735. e = 65537
  736. self.assertEqual(
  737. ohdave_rsa_encrypt(b'aa111222', e, N),
  738. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  739. def test_encode_base_n(self):
  740. self.assertEqual(encode_base_n(0, 30), '0')
  741. self.assertEqual(encode_base_n(80, 30), '2k')
  742. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  743. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  744. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  745. self.assertRaises(ValueError, encode_base_n, 0, 70)
  746. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  747. if __name__ == '__main__':
  748. unittest.main()