This is a backup of https://github.com/ytdl-org/youtube-dl since it was taken down by the RIAA.
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.

test_utils.py 66KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448
  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. self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
  717. self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
  718. def test_month_by_name(self):
  719. self.assertEqual(month_by_name(None), None)
  720. self.assertEqual(month_by_name('December', 'en'), 12)
  721. self.assertEqual(month_by_name('décembre', 'fr'), 12)
  722. self.assertEqual(month_by_name('December'), 12)
  723. self.assertEqual(month_by_name('décembre'), None)
  724. self.assertEqual(month_by_name('Unknown', 'unknown'), None)
  725. def test_parse_codecs(self):
  726. self.assertEqual(parse_codecs(''), {})
  727. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  728. 'vcodec': 'avc1.77.30',
  729. 'acodec': 'mp4a.40.2',
  730. })
  731. self.assertEqual(parse_codecs('mp4a.40.2'), {
  732. 'vcodec': 'none',
  733. 'acodec': 'mp4a.40.2',
  734. })
  735. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  736. 'vcodec': 'avc1.42001e',
  737. 'acodec': 'mp4a.40.5',
  738. })
  739. self.assertEqual(parse_codecs('avc3.640028'), {
  740. 'vcodec': 'avc3.640028',
  741. 'acodec': 'none',
  742. })
  743. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  744. 'vcodec': 'h264',
  745. 'acodec': 'aac',
  746. })
  747. self.assertEqual(parse_codecs('av01.0.05M.08'), {
  748. 'vcodec': 'av01.0.05M.08',
  749. 'acodec': 'none',
  750. })
  751. self.assertEqual(parse_codecs('theora, vorbis'), {
  752. 'vcodec': 'theora',
  753. 'acodec': 'vorbis',
  754. })
  755. self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
  756. 'vcodec': 'unknownvcodec',
  757. 'acodec': 'unknownacodec',
  758. })
  759. self.assertEqual(parse_codecs('unknown'), {})
  760. def test_escape_rfc3986(self):
  761. reserved = "!*'();:@&=+$,/?#[]"
  762. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  763. self.assertEqual(escape_rfc3986(reserved), reserved)
  764. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  765. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  766. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  767. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  768. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  769. def test_escape_url(self):
  770. self.assertEqual(
  771. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  772. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  773. )
  774. self.assertEqual(
  775. 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'),
  776. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  777. )
  778. self.assertEqual(
  779. escape_url('http://тест.рф/фрагмент'),
  780. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  781. )
  782. self.assertEqual(
  783. escape_url('http://тест.рф/абв?абв=абв#абв'),
  784. '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'
  785. )
  786. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  787. def test_js_to_json_realworld(self):
  788. inp = '''{
  789. 'clip':{'provider':'pseudo'}
  790. }'''
  791. self.assertEqual(js_to_json(inp), '''{
  792. "clip":{"provider":"pseudo"}
  793. }''')
  794. json.loads(js_to_json(inp))
  795. inp = '''{
  796. 'playlist':[{'controls':{'all':null}}]
  797. }'''
  798. self.assertEqual(js_to_json(inp), '''{
  799. "playlist":[{"controls":{"all":null}}]
  800. }''')
  801. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  802. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  803. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  804. json_code = js_to_json(inp)
  805. self.assertEqual(json.loads(json_code), json.loads(inp))
  806. inp = '''{
  807. 0:{src:'skipped', type: 'application/dash+xml'},
  808. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  809. }'''
  810. self.assertEqual(js_to_json(inp), '''{
  811. "0":{"src":"skipped", "type": "application/dash+xml"},
  812. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  813. }''')
  814. inp = '''{"foo":101}'''
  815. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  816. inp = '''{"duration": "00:01:07"}'''
  817. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  818. inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
  819. self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
  820. def test_js_to_json_edgecases(self):
  821. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  822. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  823. on = js_to_json('{"abc": true}')
  824. self.assertEqual(json.loads(on), {'abc': True})
  825. # Ignore JavaScript code as well
  826. on = js_to_json('''{
  827. "x": 1,
  828. y: "a",
  829. z: some.code
  830. }''')
  831. d = json.loads(on)
  832. self.assertEqual(d['x'], 1)
  833. self.assertEqual(d['y'], 'a')
  834. on = js_to_json('["abc", "def",]')
  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('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
  839. self.assertEqual(json.loads(on), ['abc', 'def'])
  840. on = js_to_json('{"abc": "def",}')
  841. self.assertEqual(json.loads(on), {'abc': 'def'})
  842. on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
  843. self.assertEqual(json.loads(on), {'abc': 'def'})
  844. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  845. self.assertEqual(json.loads(on), {'0': ',]'})
  846. on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
  847. self.assertEqual(json.loads(on), {'0': ',]'})
  848. on = js_to_json('{ 0: // comment\n1 }')
  849. self.assertEqual(json.loads(on), {'0': 1})
  850. on = js_to_json(r'["<p>x<\/p>"]')
  851. self.assertEqual(json.loads(on), ['<p>x</p>'])
  852. on = js_to_json(r'["\xaa"]')
  853. self.assertEqual(json.loads(on), ['\u00aa'])
  854. on = js_to_json("['a\\\nb']")
  855. self.assertEqual(json.loads(on), ['ab'])
  856. on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
  857. self.assertEqual(json.loads(on), ['ab'])
  858. on = js_to_json('{0xff:0xff}')
  859. self.assertEqual(json.loads(on), {'255': 255})
  860. on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
  861. self.assertEqual(json.loads(on), {'255': 255})
  862. on = js_to_json('{077:077}')
  863. self.assertEqual(json.loads(on), {'63': 63})
  864. on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
  865. self.assertEqual(json.loads(on), {'63': 63})
  866. on = js_to_json('{42:42}')
  867. self.assertEqual(json.loads(on), {'42': 42})
  868. on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
  869. self.assertEqual(json.loads(on), {'42': 42})
  870. on = js_to_json('{42:4.2e1}')
  871. self.assertEqual(json.loads(on), {'42': 42.0})
  872. on = js_to_json('{ "0x40": "0x40" }')
  873. self.assertEqual(json.loads(on), {'0x40': '0x40'})
  874. on = js_to_json('{ "040": "040" }')
  875. self.assertEqual(json.loads(on), {'040': '040'})
  876. def test_js_to_json_malformed(self):
  877. self.assertEqual(js_to_json('42a1'), '42"a1"')
  878. self.assertEqual(js_to_json('42a-1'), '42"a"-1')
  879. def test_extract_attributes(self):
  880. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  881. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  882. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  883. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  884. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  885. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  886. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  887. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  888. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  889. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  890. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  891. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  892. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  893. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  894. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  895. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  896. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  897. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  898. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  899. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  900. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  901. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  902. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  903. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  904. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  905. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  906. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  907. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  908. # "Narrow" Python builds don't support unicode code points outside BMP.
  909. try:
  910. compat_chr(0x10000)
  911. supports_outside_bmp = True
  912. except ValueError:
  913. supports_outside_bmp = False
  914. if supports_outside_bmp:
  915. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  916. # Malformed HTML should not break attributes extraction on older Python
  917. self.assertEqual(extract_attributes('<mal"formed/>'), {})
  918. def test_clean_html(self):
  919. self.assertEqual(clean_html('a:\nb'), 'a: b')
  920. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  921. self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
  922. def test_intlist_to_bytes(self):
  923. self.assertEqual(
  924. intlist_to_bytes([0, 1, 127, 128, 255]),
  925. b'\x00\x01\x7f\x80\xff')
  926. def test_args_to_str(self):
  927. self.assertEqual(
  928. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  929. 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
  930. )
  931. def test_parse_filesize(self):
  932. self.assertEqual(parse_filesize(None), None)
  933. self.assertEqual(parse_filesize(''), None)
  934. self.assertEqual(parse_filesize('91 B'), 91)
  935. self.assertEqual(parse_filesize('foobar'), None)
  936. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  937. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  938. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  939. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  940. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  941. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  942. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  943. def test_parse_count(self):
  944. self.assertEqual(parse_count(None), None)
  945. self.assertEqual(parse_count(''), None)
  946. self.assertEqual(parse_count('0'), 0)
  947. self.assertEqual(parse_count('1000'), 1000)
  948. self.assertEqual(parse_count('1.000'), 1000)
  949. self.assertEqual(parse_count('1.1k'), 1100)
  950. self.assertEqual(parse_count('1.1kk'), 1100000)
  951. self.assertEqual(parse_count('1.1kk '), 1100000)
  952. self.assertEqual(parse_count('1.1kk views'), 1100000)
  953. def test_parse_resolution(self):
  954. self.assertEqual(parse_resolution(None), {})
  955. self.assertEqual(parse_resolution(''), {})
  956. self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
  957. self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
  958. self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
  959. self.assertEqual(parse_resolution('720p'), {'height': 720})
  960. self.assertEqual(parse_resolution('4k'), {'height': 2160})
  961. self.assertEqual(parse_resolution('8K'), {'height': 4320})
  962. def test_parse_bitrate(self):
  963. self.assertEqual(parse_bitrate(None), None)
  964. self.assertEqual(parse_bitrate(''), None)
  965. self.assertEqual(parse_bitrate('300kbps'), 300)
  966. self.assertEqual(parse_bitrate('1500kbps'), 1500)
  967. self.assertEqual(parse_bitrate('300 kbps'), 300)
  968. def test_version_tuple(self):
  969. self.assertEqual(version_tuple('1'), (1,))
  970. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  971. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  972. def test_detect_exe_version(self):
  973. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  974. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  975. configuration: --prefix=/usr --extra-'''), '1.2.1')
  976. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  977. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  978. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  979. Trying to open render node...
  980. Success at /dev/dri/renderD128.
  981. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  982. def test_age_restricted(self):
  983. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  984. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  985. self.assertFalse(age_restricted(8, 10))
  986. self.assertTrue(age_restricted(18, 14))
  987. self.assertFalse(age_restricted(18, 18))
  988. def test_is_html(self):
  989. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  990. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  991. self.assertTrue(is_html( # UTF-8 with BOM
  992. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  993. self.assertTrue(is_html( # UTF-16-LE
  994. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  995. ))
  996. self.assertTrue(is_html( # UTF-16-BE
  997. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  998. ))
  999. self.assertTrue(is_html( # UTF-32-BE
  1000. 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'))
  1001. self.assertTrue(is_html( # UTF-32-LE
  1002. 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'))
  1003. def test_render_table(self):
  1004. self.assertEqual(
  1005. render_table(
  1006. ['a', 'bcd'],
  1007. [[123, 4], [9999, 51]]),
  1008. 'a bcd\n'
  1009. '123 4\n'
  1010. '9999 51')
  1011. def test_match_str(self):
  1012. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  1013. self.assertFalse(match_str('xy', {'x': 1200}))
  1014. self.assertTrue(match_str('!xy', {'x': 1200}))
  1015. self.assertTrue(match_str('x', {'x': 1200}))
  1016. self.assertFalse(match_str('!x', {'x': 1200}))
  1017. self.assertTrue(match_str('x', {'x': 0}))
  1018. self.assertFalse(match_str('x>0', {'x': 0}))
  1019. self.assertFalse(match_str('x>0', {}))
  1020. self.assertTrue(match_str('x>?0', {}))
  1021. self.assertTrue(match_str('x>1K', {'x': 1200}))
  1022. self.assertFalse(match_str('x>2K', {'x': 1200}))
  1023. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  1024. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  1025. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  1026. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  1027. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  1028. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  1029. self.assertFalse(match_str(
  1030. 'like_count > 100 & dislike_count <? 50 & description',
  1031. {'like_count': 90, 'description': 'foo'}))
  1032. self.assertTrue(match_str(
  1033. 'like_count > 100 & dislike_count <? 50 & description',
  1034. {'like_count': 190, 'description': 'foo'}))
  1035. self.assertFalse(match_str(
  1036. 'like_count > 100 & dislike_count <? 50 & description',
  1037. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  1038. self.assertFalse(match_str(
  1039. 'like_count > 100 & dislike_count <? 50 & description',
  1040. {'like_count': 190, 'dislike_count': 10}))
  1041. self.assertTrue(match_str('is_live', {'is_live': True}))
  1042. self.assertFalse(match_str('is_live', {'is_live': False}))
  1043. self.assertFalse(match_str('is_live', {'is_live': None}))
  1044. self.assertFalse(match_str('is_live', {}))
  1045. self.assertFalse(match_str('!is_live', {'is_live': True}))
  1046. self.assertTrue(match_str('!is_live', {'is_live': False}))
  1047. self.assertTrue(match_str('!is_live', {'is_live': None}))
  1048. self.assertTrue(match_str('!is_live', {}))
  1049. self.assertTrue(match_str('title', {'title': 'abc'}))
  1050. self.assertTrue(match_str('title', {'title': ''}))
  1051. self.assertFalse(match_str('!title', {'title': 'abc'}))
  1052. self.assertFalse(match_str('!title', {'title': ''}))
  1053. def test_parse_dfxp_time_expr(self):
  1054. self.assertEqual(parse_dfxp_time_expr(None), None)
  1055. self.assertEqual(parse_dfxp_time_expr(''), None)
  1056. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  1057. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  1058. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  1059. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  1060. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  1061. def test_dfxp2srt(self):
  1062. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  1063. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1064. <body>
  1065. <div xml:lang="en">
  1066. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  1067. <p begin="1" end="2">第二行<br/>♪♪</p>
  1068. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  1069. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  1070. <p begin="-1" end="-1">Ignore, two</p>
  1071. <p begin="3" dur="-1">Ignored, three</p>
  1072. </div>
  1073. </body>
  1074. </tt>'''.encode('utf-8')
  1075. srt_data = '''1
  1076. 00:00:00,000 --> 00:00:01,000
  1077. The following line contains Chinese characters and special symbols
  1078. 2
  1079. 00:00:01,000 --> 00:00:02,000
  1080. 第二行
  1081. ♪♪
  1082. 3
  1083. 00:00:02,000 --> 00:00:03,000
  1084. Third
  1085. Line
  1086. '''
  1087. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  1088. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  1089. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1090. <body>
  1091. <div xml:lang="en">
  1092. <p begin="0" end="1">The first line</p>
  1093. </div>
  1094. </body>
  1095. </tt>'''.encode('utf-8')
  1096. srt_data = '''1
  1097. 00:00:00,000 --> 00:00:01,000
  1098. The first line
  1099. '''
  1100. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  1101. dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
  1102. <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">
  1103. <head>
  1104. <styling>
  1105. <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
  1106. <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
  1107. <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
  1108. <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
  1109. </styling>
  1110. </head>
  1111. <body tts:textAlign="center" style="s0">
  1112. <div>
  1113. <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
  1114. <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>
  1115. <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
  1116. <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>
  1117. </div>
  1118. </body>
  1119. </tt>'''.encode('utf-8')
  1120. srt_data = '''1
  1121. 00:00:02,080 --> 00:00:05,839
  1122. <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
  1123. 2
  1124. 00:00:02,080 --> 00:00:05,839
  1125. <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
  1126. </font>part 2</font></b>
  1127. 3
  1128. 00:00:05,839 --> 00:00:09,560
  1129. <u><font color="lime">line 3
  1130. part 3</font></u>
  1131. 4
  1132. 00:00:09,560 --> 00:00:12,359
  1133. <i><u><font color="yellow"><font color="lime">inner
  1134. </font>style</font></u></i>
  1135. '''
  1136. self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
  1137. dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
  1138. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1139. <body>
  1140. <div xml:lang="en">
  1141. <p begin="0" end="1">Line 1</p>
  1142. <p begin="1" end="2">第二行</p>
  1143. </div>
  1144. </body>
  1145. </tt>'''.encode('utf-16')
  1146. srt_data = '''1
  1147. 00:00:00,000 --> 00:00:01,000
  1148. Line 1
  1149. 2
  1150. 00:00:01,000 --> 00:00:02,000
  1151. 第二行
  1152. '''
  1153. self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
  1154. def test_cli_option(self):
  1155. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  1156. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  1157. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  1158. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  1159. def test_cli_valueless_option(self):
  1160. self.assertEqual(cli_valueless_option(
  1161. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  1162. self.assertEqual(cli_valueless_option(
  1163. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  1164. self.assertEqual(cli_valueless_option(
  1165. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  1166. self.assertEqual(cli_valueless_option(
  1167. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  1168. self.assertEqual(cli_valueless_option(
  1169. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  1170. self.assertEqual(cli_valueless_option(
  1171. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  1172. def test_cli_bool_option(self):
  1173. self.assertEqual(
  1174. cli_bool_option(
  1175. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  1176. ['--no-check-certificate', 'true'])
  1177. self.assertEqual(
  1178. cli_bool_option(
  1179. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  1180. ['--no-check-certificate=true'])
  1181. self.assertEqual(
  1182. cli_bool_option(
  1183. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1184. ['--check-certificate', 'false'])
  1185. self.assertEqual(
  1186. cli_bool_option(
  1187. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1188. ['--check-certificate=false'])
  1189. self.assertEqual(
  1190. cli_bool_option(
  1191. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1192. ['--check-certificate', 'true'])
  1193. self.assertEqual(
  1194. cli_bool_option(
  1195. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1196. ['--check-certificate=true'])
  1197. self.assertEqual(
  1198. cli_bool_option(
  1199. {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1200. [])
  1201. def test_ohdave_rsa_encrypt(self):
  1202. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  1203. e = 65537
  1204. self.assertEqual(
  1205. ohdave_rsa_encrypt(b'aa111222', e, N),
  1206. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  1207. def test_pkcs1pad(self):
  1208. data = [1, 2, 3]
  1209. padded_data = pkcs1pad(data, 32)
  1210. self.assertEqual(padded_data[:2], [0, 2])
  1211. self.assertEqual(padded_data[28:], [0, 1, 2, 3])
  1212. self.assertRaises(ValueError, pkcs1pad, data, 8)
  1213. def test_encode_base_n(self):
  1214. self.assertEqual(encode_base_n(0, 30), '0')
  1215. self.assertEqual(encode_base_n(80, 30), '2k')
  1216. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  1217. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  1218. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  1219. self.assertRaises(ValueError, encode_base_n, 0, 70)
  1220. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  1221. def test_caesar(self):
  1222. self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
  1223. self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
  1224. self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
  1225. self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
  1226. self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
  1227. self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
  1228. self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
  1229. self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
  1230. def test_rot47(self):
  1231. self.assertEqual(rot47('youtube-dl'), r'J@FEF36\5=')
  1232. self.assertEqual(rot47('YOUTUBE-DL'), r'*~&%&qt\s{')
  1233. def test_urshift(self):
  1234. self.assertEqual(urshift(3, 1), 1)
  1235. self.assertEqual(urshift(-3, 1), 2147483646)
  1236. def test_get_element_by_class(self):
  1237. html = '''
  1238. <span class="foo bar">nice</span>
  1239. '''
  1240. self.assertEqual(get_element_by_class('foo', html), 'nice')
  1241. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1242. def test_get_element_by_attribute(self):
  1243. html = '''
  1244. <span class="foo bar">nice</span>
  1245. '''
  1246. self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
  1247. self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
  1248. self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
  1249. html = '''
  1250. <div itemprop="author" itemscope>foo</div>
  1251. '''
  1252. self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
  1253. def test_get_elements_by_class(self):
  1254. html = '''
  1255. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1256. '''
  1257. self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
  1258. self.assertEqual(get_elements_by_class('no-such-class', html), [])
  1259. def test_get_elements_by_attribute(self):
  1260. html = '''
  1261. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1262. '''
  1263. self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
  1264. self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
  1265. self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
  1266. if __name__ == '__main__':
  1267. unittest.main()