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.

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