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.

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