test_utils.py 66 KB

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