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.

1410 lines
64 KiB

10 years ago
10 years ago
10 years ago
9 years ago
9 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. date_from_str,
  19. DateRange,
  20. detect_exe_version,
  21. determine_ext,
  22. dict_get,
  23. encode_compat_str,
  24. encodeFilename,
  25. escape_rfc3986,
  26. escape_url,
  27. extract_attributes,
  28. ExtractorError,
  29. find_xpath_attr,
  30. fix_xml_ampersands,
  31. float_or_none,
  32. get_element_by_class,
  33. get_element_by_attribute,
  34. get_elements_by_class,
  35. get_elements_by_attribute,
  36. InAdvancePagedList,
  37. int_or_none,
  38. intlist_to_bytes,
  39. is_html,
  40. js_to_json,
  41. limit_length,
  42. merge_dicts,
  43. mimetype2ext,
  44. month_by_name,
  45. multipart_encode,
  46. ohdave_rsa_encrypt,
  47. OnDemandPagedList,
  48. orderedSet,
  49. parse_age_limit,
  50. parse_duration,
  51. parse_filesize,
  52. parse_count,
  53. parse_iso8601,
  54. parse_resolution,
  55. parse_bitrate,
  56. pkcs1pad,
  57. read_batch_urls,
  58. sanitize_filename,
  59. sanitize_path,
  60. sanitize_url,
  61. expand_path,
  62. prepend_extension,
  63. replace_extension,
  64. remove_start,
  65. remove_end,
  66. remove_quotes,
  67. shell_quote,
  68. smuggle_url,
  69. str_to_int,
  70. strip_jsonp,
  71. strip_or_none,
  72. timeconvert,
  73. unescapeHTML,
  74. unified_strdate,
  75. unified_timestamp,
  76. unsmuggle_url,
  77. uppercase_escape,
  78. lowercase_escape,
  79. url_basename,
  80. url_or_none,
  81. base_url,
  82. urljoin,
  83. urlencode_postdata,
  84. urshift,
  85. update_url_query,
  86. version_tuple,
  87. xpath_with_ns,
  88. xpath_element,
  89. xpath_text,
  90. xpath_attr,
  91. render_table,
  92. match_str,
  93. parse_dfxp_time_expr,
  94. dfxp2srt,
  95. cli_option,
  96. cli_valueless_option,
  97. cli_bool_option,
  98. parse_codecs,
  99. )
  100. from youtube_dl.compat import (
  101. compat_chr,
  102. compat_etree_fromstring,
  103. compat_getenv,
  104. compat_os_name,
  105. compat_setenv,
  106. compat_urlparse,
  107. compat_parse_qs,
  108. )
  109. class TestUtil(unittest.TestCase):
  110. def test_timeconvert(self):
  111. self.assertTrue(timeconvert('') is None)
  112. self.assertTrue(timeconvert('bougrg') is None)
  113. def test_sanitize_filename(self):
  114. self.assertEqual(sanitize_filename('abc'), 'abc')
  115. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  116. self.assertEqual(sanitize_filename('123'), '123')
  117. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  118. self.assertFalse('/' in sanitize_filename('abc/de///'))
  119. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  120. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  121. self.assertEqual('yes no', sanitize_filename('yes? no'))
  122. self.assertEqual('this - that', sanitize_filename('this: that'))
  123. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  124. aumlaut = 'ä'
  125. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  126. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  127. self.assertEqual(sanitize_filename(tests), tests)
  128. self.assertEqual(
  129. sanitize_filename('New World record at 0:12:34'),
  130. 'New World record at 0_12_34')
  131. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  132. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  133. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  134. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  135. forbidden = '"\0\\/'
  136. for fc in forbidden:
  137. for fbc in forbidden:
  138. self.assertTrue(fbc not in sanitize_filename(fc))
  139. def test_sanitize_filename_restricted(self):
  140. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  141. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  142. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  143. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  144. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  145. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  146. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  147. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  148. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  149. tests = 'aäb\u4e2d\u56fd\u7684c'
  150. self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
  151. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  152. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  153. for fc in forbidden:
  154. for fbc in forbidden:
  155. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  156. # Handle a common case more neatly
  157. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  158. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  159. # .. but make sure the file name is never empty
  160. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  161. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  162. self.assertEqual(sanitize_filename(
  163. 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
  164. 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
  165. def test_sanitize_ids(self):
  166. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  167. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  168. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  169. def test_sanitize_path(self):
  170. if sys.platform != 'win32':
  171. return
  172. self.assertEqual(sanitize_path('abc'), 'abc')
  173. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  174. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  175. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  176. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  177. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  178. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  179. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  180. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  181. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  182. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  183. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  184. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  185. self.assertEqual(
  186. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  187. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  188. self.assertEqual(
  189. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  190. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  191. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  192. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  193. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  194. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  195. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  196. self.assertEqual(sanitize_path('./abc'), 'abc')
  197. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  198. def test_sanitize_url(self):
  199. self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
  200. self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
  201. self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
  202. self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
  203. def test_expand_path(self):
  204. def env(var):
  205. return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
  206. compat_setenv('YOUTUBE_DL_EXPATH_PATH', 'expanded')
  207. self.assertEqual(expand_path(env('YOUTUBE_DL_EXPATH_PATH')), 'expanded')
  208. self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
  209. self.assertEqual(expand_path('~'), compat_getenv('HOME'))
  210. self.assertEqual(
  211. expand_path('~/%s' % env('YOUTUBE_DL_EXPATH_PATH')),
  212. '%s/expanded' % compat_getenv('HOME'))
  213. def test_prepend_extension(self):
  214. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  215. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  216. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  217. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  218. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  219. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  220. def test_replace_extension(self):
  221. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  222. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  223. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  224. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  225. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  226. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  227. def test_remove_start(self):
  228. self.assertEqual(remove_start(None, 'A - '), None)
  229. self.assertEqual(remove_start('A - B', 'A - '), 'B')
  230. self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
  231. def test_remove_end(self):
  232. self.assertEqual(remove_end(None, ' - B'), None)
  233. self.assertEqual(remove_end('A - B', ' - B'), 'A')
  234. self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
  235. def test_remove_quotes(self):
  236. self.assertEqual(remove_quotes(None), None)
  237. self.assertEqual(remove_quotes('"'), '"')
  238. self.assertEqual(remove_quotes("'"), "'")
  239. self.assertEqual(remove_quotes(';'), ';')
  240. self.assertEqual(remove_quotes('";'), '";')
  241. self.assertEqual(remove_quotes('""'), '')
  242. self.assertEqual(remove_quotes('";"'), ';')
  243. def test_ordered_set(self):
  244. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  245. self.assertEqual(orderedSet([]), [])
  246. self.assertEqual(orderedSet([1]), [1])
  247. # keep the list ordered
  248. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  249. def test_unescape_html(self):
  250. self.assertEqual(unescapeHTML('%20;'), '%20;')
  251. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  252. self.assertEqual(unescapeHTML('&#47;'), '/')
  253. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  254. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  255. self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
  256. # HTML5 entities
  257. self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
  258. def test_date_from_str(self):
  259. self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
  260. self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
  261. self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
  262. self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
  263. self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
  264. def test_daterange(self):
  265. _20century = DateRange("19000101", "20000101")
  266. self.assertFalse("17890714" in _20century)
  267. _ac = DateRange("00010101")
  268. self.assertTrue("19690721" in _ac)
  269. _firstmilenium = DateRange(end="10000101")
  270. self.assertTrue("07110427" in _firstmilenium)
  271. def test_unified_dates(self):
  272. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  273. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  274. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  275. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  276. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  277. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  278. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  279. self.assertEqual(
  280. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  281. '20141126')
  282. self.assertEqual(
  283. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  284. '20150202')
  285. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  286. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  287. self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
  288. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  289. self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
  290. self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
  291. self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
  292. self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
  293. def test_unified_timestamps(self):
  294. self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
  295. self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
  296. self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
  297. self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
  298. self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
  299. self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
  300. self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
  301. self.assertEqual(
  302. unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
  303. 1417001400)
  304. self.assertEqual(
  305. unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
  306. 1422902860)
  307. self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
  308. self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
  309. self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
  310. self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
  311. self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
  312. self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
  313. self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
  314. self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
  315. self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
  316. self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
  317. def test_determine_ext(self):
  318. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  319. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  320. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  321. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  322. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  323. self.assertEqual(determine_ext('foobar', None), None)
  324. def test_find_xpath_attr(self):
  325. testxml = '''<root>
  326. <node/>
  327. <node x="a"/>
  328. <node x="a" y="c" />
  329. <node x="b" y="d" />
  330. <node x="" />
  331. </root>'''
  332. doc = compat_etree_fromstring(testxml)
  333. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  334. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  335. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  336. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  337. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  338. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  339. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  340. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  341. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  342. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  343. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  344. def test_xpath_with_ns(self):
  345. testxml = '''<root xmlns:media="http://example.com/">
  346. <media:song>
  347. <media:author>The Author</media:author>
  348. <url>http://server.com/download.mp3</url>
  349. </media:song>
  350. </root>'''
  351. doc = compat_etree_fromstring(testxml)
  352. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  353. self.assertTrue(find('media:song') is not None)
  354. self.assertEqual(find('media:song/media:author').text, 'The Author')
  355. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  356. def test_xpath_element(self):
  357. doc = xml.etree.ElementTree.Element('root')
  358. div = xml.etree.ElementTree.SubElement(doc, 'div')
  359. p = xml.etree.ElementTree.SubElement(div, 'p')
  360. p.text = 'Foo'
  361. self.assertEqual(xpath_element(doc, 'div/p'), p)
  362. self.assertEqual(xpath_element(doc, ['div/p']), p)
  363. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  364. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  365. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  366. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  367. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  368. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  369. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  370. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  371. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  372. def test_xpath_text(self):
  373. testxml = '''<root>
  374. <div>
  375. <p>Foo</p>
  376. </div>
  377. </root>'''
  378. doc = compat_etree_fromstring(testxml)
  379. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  380. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  381. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  382. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  383. def test_xpath_attr(self):
  384. testxml = '''<root>
  385. <div>
  386. <p x="a">Foo</p>
  387. </div>
  388. </root>'''
  389. doc = compat_etree_fromstring(testxml)
  390. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  391. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  392. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  393. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  394. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  395. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  396. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  397. def test_smuggle_url(self):
  398. data = {"ö": "ö", "abc": [3]}
  399. url = 'https://foo.bar/baz?x=y#a'
  400. smug_url = smuggle_url(url, data)
  401. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  402. self.assertEqual(url, unsmug_url)
  403. self.assertEqual(data, unsmug_data)
  404. res_url, res_data = unsmuggle_url(url)
  405. self.assertEqual(res_url, url)
  406. self.assertEqual(res_data, None)
  407. smug_url = smuggle_url(url, {'a': 'b'})
  408. smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
  409. res_url, res_data = unsmuggle_url(smug_smug_url)
  410. self.assertEqual(res_url, url)
  411. self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
  412. def test_shell_quote(self):
  413. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  414. self.assertEqual(
  415. shell_quote(args),
  416. """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
  417. def test_float_or_none(self):
  418. self.assertEqual(float_or_none('42.42'), 42.42)
  419. self.assertEqual(float_or_none('42'), 42.0)
  420. self.assertEqual(float_or_none(''), None)
  421. self.assertEqual(float_or_none(None), None)
  422. self.assertEqual(float_or_none([]), None)
  423. self.assertEqual(float_or_none(set()), None)
  424. def test_int_or_none(self):
  425. self.assertEqual(int_or_none('42'), 42)
  426. self.assertEqual(int_or_none(''), None)
  427. self.assertEqual(int_or_none(None), None)
  428. self.assertEqual(int_or_none([]), None)
  429. self.assertEqual(int_or_none(set()), None)
  430. def test_str_to_int(self):
  431. self.assertEqual(str_to_int('123,456'), 123456)
  432. self.assertEqual(str_to_int('123.456'), 123456)
  433. def test_url_basename(self):
  434. self.assertEqual(url_basename('http://foo.de/'), '')
  435. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  436. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  437. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  438. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  439. self.assertEqual(
  440. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  441. 'trailer.mp4')
  442. def test_base_url(self):
  443. self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
  444. self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
  445. self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
  446. self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
  447. self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
  448. def test_urljoin(self):
  449. self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  450. self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  451. self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  452. self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  453. self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
  454. self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  455. self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  456. self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  457. self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  458. self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  459. self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  460. self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  461. self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  462. self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  463. self.assertEqual(urljoin('http://foo.de/', None), None)
  464. self.assertEqual(urljoin('http://foo.de/', ''), None)
  465. self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
  466. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
  467. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
  468. self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
  469. def test_url_or_none(self):
  470. self.assertEqual(url_or_none(None), None)
  471. self.assertEqual(url_or_none(''), None)
  472. self.assertEqual(url_or_none('foo'), None)
  473. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  474. self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
  475. self.assertEqual(url_or_none('http$://foo.de'), None)
  476. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  477. self.assertEqual(url_or_none('//foo.de'), '//foo.de')
  478. def test_parse_age_limit(self):
  479. self.assertEqual(parse_age_limit(None), None)
  480. self.assertEqual(parse_age_limit(False), None)
  481. self.assertEqual(parse_age_limit('invalid'), None)
  482. self.assertEqual(parse_age_limit(0), 0)
  483. self.assertEqual(parse_age_limit(18), 18)
  484. self.assertEqual(parse_age_limit(21), 21)
  485. self.assertEqual(parse_age_limit(22), None)
  486. self.assertEqual(parse_age_limit('18'), 18)
  487. self.assertEqual(parse_age_limit('18+'), 18)
  488. self.assertEqual(parse_age_limit('PG-13'), 13)
  489. self.assertEqual(parse_age_limit('TV-14'), 14)
  490. self.assertEqual(parse_age_limit('TV-MA'), 17)
  491. self.assertEqual(parse_age_limit('TV14'), 14)
  492. self.assertEqual(parse_age_limit('TV_G'), 0)
  493. def test_parse_duration(self):
  494. self.assertEqual(parse_duration(None), None)
  495. self.assertEqual(parse_duration(False), None)
  496. self.assertEqual(parse_duration('invalid'), None)
  497. self.assertEqual(parse_duration('1'), 1)
  498. self.assertEqual(parse_duration('1337:12'), 80232)
  499. self.assertEqual(parse_duration('9:12:43'), 33163)
  500. self.assertEqual(parse_duration('12:00'), 720)
  501. self.assertEqual(parse_duration('00:01:01'), 61)
  502. self.assertEqual(parse_duration('x:y'), None)
  503. self.assertEqual(parse_duration('3h11m53s'), 11513)
  504. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  505. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  506. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  507. self.assertEqual(parse_duration('62m45s'), 3765)
  508. self.assertEqual(parse_duration('6m59s'), 419)
  509. self.assertEqual(parse_duration('49s'), 49)
  510. self.assertEqual(parse_duration('0h0m0s'), 0)
  511. self.assertEqual(parse_duration('0m0s'), 0)
  512. self.assertEqual(parse_duration('0s'), 0)
  513. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  514. self.assertEqual(parse_duration('T30M38S'), 1838)
  515. self.assertEqual(parse_duration('5 s'), 5)
  516. self.assertEqual(parse_duration('3 min'), 180)
  517. self.assertEqual(parse_duration('2.5 hours'), 9000)
  518. self.assertEqual(parse_duration('02:03:04'), 7384)
  519. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  520. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  521. self.assertEqual(parse_duration('87 Min.'), 5220)
  522. self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
  523. self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
  524. self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
  525. def test_fix_xml_ampersands(self):
  526. self.assertEqual(
  527. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  528. self.assertEqual(
  529. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  530. '"&amp;x=y&amp;wrong;&amp;z=a')
  531. self.assertEqual(
  532. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  533. '&amp;&apos;&gt;&lt;&quot;')
  534. self.assertEqual(
  535. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  536. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  537. def test_paged_list(self):
  538. def testPL(size, pagesize, sliceargs, expected):
  539. def get_page(pagenum):
  540. firstid = pagenum * pagesize
  541. upto = min(size, pagenum * pagesize + pagesize)
  542. for i in range(firstid, upto):
  543. yield i
  544. pl = OnDemandPagedList(get_page, pagesize)
  545. got = pl.getslice(*sliceargs)
  546. self.assertEqual(got, expected)
  547. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  548. got = iapl.getslice(*sliceargs)
  549. self.assertEqual(got, expected)
  550. testPL(5, 2, (), [0, 1, 2, 3, 4])
  551. testPL(5, 2, (1,), [1, 2, 3, 4])
  552. testPL(5, 2, (2,), [2, 3, 4])
  553. testPL(5, 2, (4,), [4])
  554. testPL(5, 2, (0, 3), [0, 1, 2])
  555. testPL(5, 2, (1, 4), [1, 2, 3])
  556. testPL(5, 2, (2, 99), [2, 3, 4])
  557. testPL(5, 2, (20, 99), [])
  558. def test_read_batch_urls(self):
  559. f = io.StringIO('''\xef\xbb\xbf foo
  560. bar\r
  561. baz
  562. # More after this line\r
  563. ; or after this
  564. bam''')
  565. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  566. def test_urlencode_postdata(self):
  567. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  568. self.assertTrue(isinstance(data, bytes))
  569. def test_update_url_query(self):
  570. def query_dict(url):
  571. return compat_parse_qs(compat_urlparse.urlparse(url).query)
  572. self.assertEqual(query_dict(update_url_query(
  573. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  574. query_dict('http://example.com/path?quality=HD&format=mp4'))
  575. self.assertEqual(query_dict(update_url_query(
  576. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  577. query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
  578. self.assertEqual(query_dict(update_url_query(
  579. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  580. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  581. self.assertEqual(query_dict(update_url_query(
  582. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  583. query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  584. self.assertEqual(query_dict(update_url_query(
  585. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  586. query_dict('http://example.com/path'))
  587. self.assertEqual(query_dict(update_url_query(
  588. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  589. query_dict('http://example.com/path?system=LINUX'))
  590. self.assertEqual(query_dict(update_url_query(
  591. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  592. query_dict('http://example.com/path?fields=id,formats,subtitles'))
  593. self.assertEqual(query_dict(update_url_query(
  594. 'http://example.com/path', {'width': 1080, 'height': 720})),
  595. query_dict('http://example.com/path?width=1080&height=720'))
  596. self.assertEqual(query_dict(update_url_query(
  597. 'http://example.com/path', {'bitrate': 5020.43})),
  598. query_dict('http://example.com/path?bitrate=5020.43'))
  599. self.assertEqual(query_dict(update_url_query(
  600. 'http://example.com/path', {'test': '第二行тест'})),
  601. query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  602. def test_multipart_encode(self):
  603. self.assertEqual(
  604. multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
  605. b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
  606. self.assertEqual(
  607. multipart_encode({'欄位'.encode('utf-8'): ''.encode('utf-8')}, boundary='AAAAAA')[0],
  608. b'--AAAAAA\r\nContent-Disposition: form-data; name="\xe6\xac\x84\xe4\xbd\x8d"\r\n\r\n\xe5\x80\xbc\r\n--AAAAAA--\r\n')
  609. self.assertRaises(
  610. ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
  611. def test_dict_get(self):
  612. FALSE_VALUES = {
  613. 'none': None,
  614. 'false': False,
  615. 'zero': 0,
  616. 'empty_string': '',
  617. 'empty_list': [],
  618. }
  619. d = FALSE_VALUES.copy()
  620. d['a'] = 42
  621. self.assertEqual(dict_get(d, 'a'), 42)
  622. self.assertEqual(dict_get(d, 'b'), None)
  623. self.assertEqual(dict_get(d, 'b', 42), 42)
  624. self.assertEqual(dict_get(d, ('a', )), 42)
  625. self.assertEqual(dict_get(d, ('b', 'a', )), 42)
  626. self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
  627. self.assertEqual(dict_get(d, ('b', 'c', )), None)
  628. self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
  629. for key, false_value in FALSE_VALUES.items():
  630. self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
  631. self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
  632. def test_merge_dicts(self):
  633. self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
  634. self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
  635. self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
  636. self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
  637. self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
  638. self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
  639. self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
  640. self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  641. self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  642. def test_encode_compat_str(self):
  643. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  644. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  645. def test_parse_iso8601(self):
  646. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  647. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  648. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  649. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  650. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  651. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  652. def test_strip_jsonp(self):
  653. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  654. d = json.loads(stripped)
  655. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  656. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  657. d = json.loads(stripped)
  658. self.assertEqual(d, {'STATUS': 'OK'})
  659. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  660. d = json.loads(stripped)
  661. self.assertEqual(d, {'status': 'success'})
  662. stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
  663. d = json.loads(stripped)
  664. self.assertEqual(d, {'status': 'success'})
  665. stripped = strip_jsonp('window.cb && cb({"status": "success"});')
  666. d = json.loads(stripped)
  667. self.assertEqual(d, {'status': 'success'})
  668. stripped = strip_jsonp('({"status": "success"});')
  669. d = json.loads(stripped)
  670. self.assertEqual(d, {'status': 'success'})
  671. def test_strip_or_none(self):
  672. self.assertEqual(strip_or_none(' abc'), 'abc')
  673. self.assertEqual(strip_or_none('abc '), 'abc')
  674. self.assertEqual(strip_or_none(' abc '), 'abc')
  675. self.assertEqual(strip_or_none('\tabc\t'), 'abc')
  676. self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
  677. self.assertEqual(strip_or_none('abc'), 'abc')
  678. self.assertEqual(strip_or_none(''), '')
  679. self.assertEqual(strip_or_none(None), None)
  680. self.assertEqual(strip_or_none(42), None)
  681. self.assertEqual(strip_or_none([]), None)
  682. def test_uppercase_escape(self):
  683. self.assertEqual(uppercase_escape(''), '')
  684. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  685. def test_lowercase_escape(self):
  686. self.assertEqual(lowercase_escape(''), '')
  687. self.assertEqual(lowercase_escape('\\u0026'), '&')
  688. def test_limit_length(self):
  689. self.assertEqual(limit_length(None, 12), None)
  690. self.assertEqual(limit_length('foo', 12), 'foo')
  691. self.assertTrue(
  692. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  693. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  694. def test_mimetype2ext(self):
  695. self.assertEqual(mimetype2ext(None), None)
  696. self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
  697. self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
  698. self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
  699. self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
  700. self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
  701. def test_month_by_name(self):
  702. self.assertEqual(month_by_name(None), None)
  703. self.assertEqual(month_by_name('December', 'en'), 12)
  704. self.assertEqual(month_by_name('décembre', 'fr'), 12)
  705. self.assertEqual(month_by_name('December'), 12)
  706. self.assertEqual(month_by_name('décembre'), None)
  707. self.assertEqual(month_by_name('Unknown', 'unknown'), None)
  708. def test_parse_codecs(self):
  709. self.assertEqual(parse_codecs(''), {})
  710. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  711. 'vcodec': 'avc1.77.30',
  712. 'acodec': 'mp4a.40.2',
  713. })
  714. self.assertEqual(parse_codecs('mp4a.40.2'), {
  715. 'vcodec': 'none',
  716. 'acodec': 'mp4a.40.2',
  717. })
  718. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  719. 'vcodec': 'avc1.42001e',
  720. 'acodec': 'mp4a.40.5',
  721. })
  722. self.assertEqual(parse_codecs('avc3.640028'), {
  723. 'vcodec': 'avc3.640028',
  724. 'acodec': 'none',
  725. })
  726. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  727. 'vcodec': 'h264',
  728. 'acodec': 'aac',
  729. })
  730. self.assertEqual(parse_codecs('av01.0.05M.08'), {
  731. 'vcodec': 'av01.0.05M.08',
  732. 'acodec': 'none',
  733. })
  734. self.assertEqual(parse_codecs('theora, vorbis'), {
  735. 'vcodec': 'theora',
  736. 'acodec': 'vorbis',
  737. })
  738. self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
  739. 'vcodec': 'unknownvcodec',
  740. 'acodec': 'unknownacodec',
  741. })
  742. self.assertEqual(parse_codecs('unknown'), {})
  743. def test_escape_rfc3986(self):
  744. reserved = "!*'();:@&=+$,/?#[]"
  745. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  746. self.assertEqual(escape_rfc3986(reserved), reserved)
  747. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  748. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  749. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  750. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  751. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  752. def test_escape_url(self):
  753. self.assertEqual(
  754. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  755. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  756. )
  757. self.assertEqual(
  758. 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'),
  759. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  760. )
  761. self.assertEqual(
  762. escape_url('http://тест.рф/фрагмент'),
  763. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  764. )
  765. self.assertEqual(
  766. escape_url('http://тест.рф/абв?абв=абв#абв'),
  767. 'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  768. )
  769. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  770. def test_js_to_json_realworld(self):
  771. inp = '''{
  772. 'clip':{'provider':'pseudo'}
  773. }'''
  774. self.assertEqual(js_to_json(inp), '''{
  775. "clip":{"provider":"pseudo"}
  776. }''')
  777. json.loads(js_to_json(inp))
  778. inp = '''{
  779. 'playlist':[{'controls':{'all':null}}]
  780. }'''
  781. self.assertEqual(js_to_json(inp), '''{
  782. "playlist":[{"controls":{"all":null}}]
  783. }''')
  784. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  785. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  786. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  787. json_code = js_to_json(inp)
  788. self.assertEqual(json.loads(json_code), json.loads(inp))
  789. inp = '''{
  790. 0:{src:'skipped', type: 'application/dash+xml'},
  791. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  792. }'''
  793. self.assertEqual(js_to_json(inp), '''{
  794. "0":{"src":"skipped", "type": "application/dash+xml"},
  795. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  796. }''')
  797. inp = '''{"foo":101}'''
  798. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  799. inp = '''{"duration": "00:01:07"}'''
  800. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  801. inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
  802. self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
  803. def test_js_to_json_edgecases(self):
  804. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  805. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  806. on = js_to_json('{"abc": true}')
  807. self.assertEqual(json.loads(on), {'abc': True})
  808. # Ignore JavaScript code as well
  809. on = js_to_json('''{
  810. "x": 1,
  811. y: "a",
  812. z: some.code
  813. }''')
  814. d = json.loads(on)
  815. self.assertEqual(d['x'], 1)
  816. self.assertEqual(d['y'], 'a')
  817. on = js_to_json('["abc", "def",]')
  818. self.assertEqual(json.loads(on), ['abc', 'def'])
  819. on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
  820. self.assertEqual(json.loads(on), ['abc', 'def'])
  821. on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
  822. self.assertEqual(json.loads(on), ['abc', 'def'])
  823. on = js_to_json('{"abc": "def",}')
  824. self.assertEqual(json.loads(on), {'abc': 'def'})
  825. on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
  826. self.assertEqual(json.loads(on), {'abc': 'def'})
  827. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  828. self.assertEqual(json.loads(on), {'0': ',]'})
  829. on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
  830. self.assertEqual(json.loads(on), {'0': ',]'})
  831. on = js_to_json('{ 0: // comment\n1 }')
  832. self.assertEqual(json.loads(on), {'0': 1})
  833. on = js_to_json(r'["<p>x<\/p>"]')
  834. self.assertEqual(json.loads(on), ['<p>x</p>'])
  835. on = js_to_json(r'["\xaa"]')
  836. self.assertEqual(json.loads(on), ['\u00aa'])
  837. on = js_to_json("['a\\\nb']")
  838. self.assertEqual(json.loads(on), ['ab'])
  839. on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
  840. self.assertEqual(json.loads(on), ['ab'])
  841. on = js_to_json('{0xff:0xff}')
  842. self.assertEqual(json.loads(on), {'255': 255})
  843. on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
  844. self.assertEqual(json.loads(on), {'255': 255})
  845. on = js_to_json('{077:077}')
  846. self.assertEqual(json.loads(on), {'63': 63})
  847. on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
  848. self.assertEqual(json.loads(on), {'63': 63})
  849. on = js_to_json('{42:42}')
  850. self.assertEqual(json.loads(on), {'42': 42})
  851. on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
  852. self.assertEqual(json.loads(on), {'42': 42})
  853. on = js_to_json('{42:4.2e1}')
  854. self.assertEqual(json.loads(on), {'42': 42.0})
  855. def test_js_to_json_malformed(self):
  856. self.assertEqual(js_to_json('42a1'), '42"a1"')
  857. self.assertEqual(js_to_json('42a-1'), '42"a"-1')
  858. def test_extract_attributes(self):
  859. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  860. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  861. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  862. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  863. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  864. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  865. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  866. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  867. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  868. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  869. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  870. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  871. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  872. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  873. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  874. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  875. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  876. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  877. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  878. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  879. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  880. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  881. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  882. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  883. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  884. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  885. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  886. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  887. # "Narrow" Python builds don't support unicode code points outside BMP.
  888. try:
  889. compat_chr(0x10000)
  890. supports_outside_bmp = True
  891. except ValueError:
  892. supports_outside_bmp = False
  893. if supports_outside_bmp:
  894. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  895. # Malformed HTML should not break attributes extraction on older Python
  896. self.assertEqual(extract_attributes('<mal"formed/>'), {})
  897. def test_clean_html(self):
  898. self.assertEqual(clean_html('a:\nb'), 'a: b')
  899. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  900. self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
  901. def test_intlist_to_bytes(self):
  902. self.assertEqual(
  903. intlist_to_bytes([0, 1, 127, 128, 255]),
  904. b'\x00\x01\x7f\x80\xff')
  905. def test_args_to_str(self):
  906. self.assertEqual(
  907. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  908. 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
  909. )
  910. def test_parse_filesize(self):
  911. self.assertEqual(parse_filesize(None), None)
  912. self.assertEqual(parse_filesize(''), None)
  913. self.assertEqual(parse_filesize('91 B'), 91)
  914. self.assertEqual(parse_filesize('foobar'), None)
  915. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  916. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  917. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  918. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  919. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  920. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  921. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  922. def test_parse_count(self):
  923. self.assertEqual(parse_count(None), None)
  924. self.assertEqual(parse_count(''), None)
  925. self.assertEqual(parse_count('0'), 0)
  926. self.assertEqual(parse_count('1000'), 1000)
  927. self.assertEqual(parse_count('1.000'), 1000)
  928. self.assertEqual(parse_count('1.1k'), 1100)
  929. self.assertEqual(parse_count('1.1kk'), 1100000)
  930. self.assertEqual(parse_count('1.1kk '), 1100000)
  931. self.assertEqual(parse_count('1.1kk views'), 1100000)
  932. def test_parse_resolution(self):
  933. self.assertEqual(parse_resolution(None), {})
  934. self.assertEqual(parse_resolution(''), {})
  935. self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
  936. self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
  937. self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
  938. self.assertEqual(parse_resolution('720p'), {'height': 720})
  939. self.assertEqual(parse_resolution('4k'), {'height': 2160})
  940. self.assertEqual(parse_resolution('8K'), {'height': 4320})
  941. def test_parse_bitrate(self):
  942. self.assertEqual(parse_bitrate(None), None)
  943. self.assertEqual(parse_bitrate(''), None)
  944. self.assertEqual(parse_bitrate('300kbps'), 300)
  945. self.assertEqual(parse_bitrate('1500kbps'), 1500)
  946. self.assertEqual(parse_bitrate('300 kbps'), 300)
  947. def test_version_tuple(self):
  948. self.assertEqual(version_tuple('1'), (1,))
  949. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  950. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  951. def test_detect_exe_version(self):
  952. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  953. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  954. configuration: --prefix=/usr --extra-'''), '1.2.1')
  955. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  956. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  957. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  958. Trying to open render node...
  959. Success at /dev/dri/renderD128.
  960. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  961. def test_age_restricted(self):
  962. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  963. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  964. self.assertFalse(age_restricted(8, 10))
  965. self.assertTrue(age_restricted(18, 14))
  966. self.assertFalse(age_restricted(18, 18))
  967. def test_is_html(self):
  968. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  969. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  970. self.assertTrue(is_html( # UTF-8 with BOM
  971. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  972. self.assertTrue(is_html( # UTF-16-LE
  973. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  974. ))
  975. self.assertTrue(is_html( # UTF-16-BE
  976. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  977. ))
  978. self.assertTrue(is_html( # UTF-32-BE
  979. 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'))
  980. self.assertTrue(is_html( # UTF-32-LE
  981. 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'))
  982. def test_render_table(self):
  983. self.assertEqual(
  984. render_table(
  985. ['a', 'bcd'],
  986. [[123, 4], [9999, 51]]),
  987. 'a bcd\n'
  988. '123 4\n'
  989. '9999 51')
  990. def test_match_str(self):
  991. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  992. self.assertFalse(match_str('xy', {'x': 1200}))
  993. self.assertTrue(match_str('!xy', {'x': 1200}))
  994. self.assertTrue(match_str('x', {'x': 1200}))
  995. self.assertFalse(match_str('!x', {'x': 1200}))
  996. self.assertTrue(match_str('x', {'x': 0}))
  997. self.assertFalse(match_str('x>0', {'x': 0}))
  998. self.assertFalse(match_str('x>0', {}))
  999. self.assertTrue(match_str('x>?0', {}))
  1000. self.assertTrue(match_str('x>1K', {'x': 1200}))
  1001. self.assertFalse(match_str('x>2K', {'x': 1200}))
  1002. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  1003. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  1004. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  1005. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  1006. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  1007. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  1008. self.assertFalse(match_str(
  1009. 'like_count > 100 & dislike_count <? 50 & description',
  1010. {'like_count': 90, 'description': 'foo'}))
  1011. self.assertTrue(match_str(
  1012. 'like_count > 100 & dislike_count <? 50 & description',
  1013. {'like_count': 190, 'description': 'foo'}))
  1014. self.assertFalse(match_str(
  1015. 'like_count > 100 & dislike_count <? 50 & description',
  1016. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  1017. self.assertFalse(match_str(
  1018. 'like_count > 100 & dislike_count <? 50 & description',
  1019. {'like_count': 190, 'dislike_count': 10}))
  1020. self.assertTrue(match_str('is_live', {'is_live': True}))
  1021. self.assertFalse(match_str('is_live', {'is_live': False}))
  1022. self.assertFalse(match_str('is_live', {'is_live': None}))
  1023. self.assertFalse(match_str('is_live', {}))
  1024. self.assertFalse(match_str('!is_live', {'is_live': True}))
  1025. self.assertTrue(match_str('!is_live', {'is_live': False}))
  1026. self.assertTrue(match_str('!is_live', {'is_live': None}))
  1027. self.assertTrue(match_str('!is_live', {}))
  1028. self.assertTrue(match_str('title', {'title': 'abc'}))
  1029. self.assertTrue(match_str('title', {'title': ''}))
  1030. self.assertFalse(match_str('!title', {'title': 'abc'}))
  1031. self.assertFalse(match_str('!title', {'title': ''}))
  1032. def test_parse_dfxp_time_expr(self):
  1033. self.assertEqual(parse_dfxp_time_expr(None), None)
  1034. self.assertEqual(parse_dfxp_time_expr(''), None)
  1035. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  1036. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  1037. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  1038. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  1039. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  1040. def test_dfxp2srt(self):
  1041. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  1042. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1043. <body>
  1044. <div xml:lang="en">
  1045. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  1046. <p begin="1" end="2"><br/></p>
  1047. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  1048. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  1049. <p begin="-1" end="-1">Ignore, two</p>
  1050. <p begin="3" dur="-1">Ignored, three</p>
  1051. </div>
  1052. </body>
  1053. </tt>'''.encode('utf-8')
  1054. srt_data = '''1
  1055. 00:00:00,000 --> 00:00:01,000
  1056. The following line contains Chinese characters and special symbols
  1057. 2
  1058. 00:00:01,000 --> 00:00:02,000
  1059. 3
  1060. 00:00:02,000 --> 00:00:03,000
  1061. Third
  1062. Line
  1063. '''
  1064. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  1065. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  1066. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1067. <body>
  1068. <div xml:lang="en">
  1069. <p begin="0" end="1">The first line</p>
  1070. </div>
  1071. </body>
  1072. </tt>'''.encode('utf-8')
  1073. srt_data = '''1
  1074. 00:00:00,000 --> 00:00:01,000
  1075. The first line
  1076. '''
  1077. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  1078. dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
  1079. <tt xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:ttp="http://www.w3.org/2006/10/ttaf1#parameter" ttp:timeBase="media" xmlns:tts="http://www.w3.org/2006/10/ttaf1#style" xml:lang="en" xmlns:ttm="http://www.w3.org/2006/10/ttaf1#metadata">
  1080. <head>
  1081. <styling>
  1082. <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
  1083. <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
  1084. <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
  1085. <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
  1086. </styling>
  1087. </head>
  1088. <body tts:textAlign="center" style="s0">
  1089. <div>
  1090. <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
  1091. <p style="s2" begin="00:00:02.08" id="p0" end="00:00:05.84"><span tts:color="lime">part 1<br /></span><span tts:color="cyan">part 2</span></p>
  1092. <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
  1093. <p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
  1094. </div>
  1095. </body>
  1096. </tt>'''.encode('utf-8')
  1097. srt_data = '''1
  1098. 00:00:02,080 --> 00:00:05,839
  1099. <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
  1100. 2
  1101. 00:00:02,080 --> 00:00:05,839
  1102. <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
  1103. </font>part 2</font></b>
  1104. 3
  1105. 00:00:05,839 --> 00:00:09,560
  1106. <u><font color="lime">line 3
  1107. part 3</font></u>
  1108. 4
  1109. 00:00:09,560 --> 00:00:12,359
  1110. <i><u><font color="yellow"><font color="lime">inner
  1111. </font>style</font></u></i>
  1112. '''
  1113. self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
  1114. dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
  1115. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1116. <body>
  1117. <div xml:lang="en">
  1118. <p begin="0" end="1">Line 1</p>
  1119. <p begin="1" end="2"></p>
  1120. </div>
  1121. </body>
  1122. </tt>'''.encode('utf-16')
  1123. srt_data = '''1
  1124. 00:00:00,000 --> 00:00:01,000
  1125. Line 1
  1126. 2
  1127. 00:00:01,000 --> 00:00:02,000
  1128. '''
  1129. self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
  1130. def test_cli_option(self):
  1131. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  1132. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  1133. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  1134. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  1135. def test_cli_valueless_option(self):
  1136. self.assertEqual(cli_valueless_option(
  1137. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  1138. self.assertEqual(cli_valueless_option(
  1139. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  1140. self.assertEqual(cli_valueless_option(
  1141. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  1142. self.assertEqual(cli_valueless_option(
  1143. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  1144. self.assertEqual(cli_valueless_option(
  1145. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  1146. self.assertEqual(cli_valueless_option(
  1147. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  1148. def test_cli_bool_option(self):
  1149. self.assertEqual(
  1150. cli_bool_option(
  1151. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  1152. ['--no-check-certificate', 'true'])
  1153. self.assertEqual(
  1154. cli_bool_option(
  1155. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  1156. ['--no-check-certificate=true'])
  1157. self.assertEqual(
  1158. cli_bool_option(
  1159. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1160. ['--check-certificate', 'false'])
  1161. self.assertEqual(
  1162. cli_bool_option(
  1163. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1164. ['--check-certificate=false'])
  1165. self.assertEqual(
  1166. cli_bool_option(
  1167. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1168. ['--check-certificate', 'true'])
  1169. self.assertEqual(
  1170. cli_bool_option(
  1171. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1172. ['--check-certificate=true'])
  1173. self.assertEqual(
  1174. cli_bool_option(
  1175. {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1176. [])
  1177. def test_ohdave_rsa_encrypt(self):
  1178. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  1179. e = 65537
  1180. self.assertEqual(
  1181. ohdave_rsa_encrypt(b'aa111222', e, N),
  1182. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  1183. def test_pkcs1pad(self):
  1184. data = [1, 2, 3]
  1185. padded_data = pkcs1pad(data, 32)
  1186. self.assertEqual(padded_data[:2], [0, 2])
  1187. self.assertEqual(padded_data[28:], [0, 1, 2, 3])
  1188. self.assertRaises(ValueError, pkcs1pad, data, 8)
  1189. def test_encode_base_n(self):
  1190. self.assertEqual(encode_base_n(0, 30), '0')
  1191. self.assertEqual(encode_base_n(80, 30), '2k')
  1192. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  1193. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  1194. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  1195. self.assertRaises(ValueError, encode_base_n, 0, 70)
  1196. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  1197. def test_urshift(self):
  1198. self.assertEqual(urshift(3, 1), 1)
  1199. self.assertEqual(urshift(-3, 1), 2147483646)
  1200. def test_get_element_by_class(self):
  1201. html = '''
  1202. <span class="foo bar">nice</span>
  1203. '''
  1204. self.assertEqual(get_element_by_class('foo', html), 'nice')
  1205. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1206. def test_get_element_by_attribute(self):
  1207. html = '''
  1208. <span class="foo bar">nice</span>
  1209. '''
  1210. self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
  1211. self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
  1212. self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
  1213. html = '''
  1214. <div itemprop="author" itemscope>foo</div>
  1215. '''
  1216. self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
  1217. def test_get_elements_by_class(self):
  1218. html = '''
  1219. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1220. '''
  1221. self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
  1222. self.assertEqual(get_elements_by_class('no-such-class', html), [])
  1223. def test_get_elements_by_attribute(self):
  1224. html = '''
  1225. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1226. '''
  1227. self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
  1228. self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
  1229. self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
  1230. if __name__ == '__main__':
  1231. unittest.main()