test_utils.py 67 KB

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