test_utils.py 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import unittest
  6. import warnings
  7. import datetime as dt
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. import contextlib
  10. import io
  11. import itertools
  12. import json
  13. import subprocess
  14. import xml.etree.ElementTree
  15. from yt_dlp.compat import (
  16. compat_etree_fromstring,
  17. compat_HTMLParseError,
  18. compat_os_name,
  19. )
  20. from yt_dlp.utils import (
  21. Config,
  22. DateRange,
  23. ExtractorError,
  24. InAdvancePagedList,
  25. LazyList,
  26. NO_DEFAULT,
  27. OnDemandPagedList,
  28. Popen,
  29. age_restricted,
  30. args_to_str,
  31. base_url,
  32. caesar,
  33. clean_html,
  34. clean_podcast_url,
  35. cli_bool_option,
  36. cli_option,
  37. cli_valueless_option,
  38. date_from_str,
  39. datetime_from_str,
  40. detect_exe_version,
  41. determine_ext,
  42. determine_file_encoding,
  43. dfxp2srt,
  44. encode_base_n,
  45. encode_compat_str,
  46. encodeFilename,
  47. expand_path,
  48. extract_attributes,
  49. extract_basic_auth,
  50. find_xpath_attr,
  51. fix_xml_ampersands,
  52. float_or_none,
  53. format_bytes,
  54. get_compatible_ext,
  55. get_element_by_attribute,
  56. get_element_by_class,
  57. get_element_html_by_attribute,
  58. get_element_html_by_class,
  59. get_element_text_and_html_by_tag,
  60. get_elements_by_attribute,
  61. get_elements_by_class,
  62. get_elements_html_by_attribute,
  63. get_elements_html_by_class,
  64. get_elements_text_and_html_by_attribute,
  65. int_or_none,
  66. intlist_to_bytes,
  67. iri_to_uri,
  68. is_html,
  69. js_to_json,
  70. limit_length,
  71. locked_file,
  72. lowercase_escape,
  73. match_str,
  74. merge_dicts,
  75. mimetype2ext,
  76. month_by_name,
  77. multipart_encode,
  78. ohdave_rsa_encrypt,
  79. orderedSet,
  80. parse_age_limit,
  81. parse_bitrate,
  82. parse_codecs,
  83. parse_count,
  84. parse_dfxp_time_expr,
  85. parse_duration,
  86. parse_filesize,
  87. parse_iso8601,
  88. parse_qs,
  89. parse_resolution,
  90. pkcs1pad,
  91. prepend_extension,
  92. read_batch_urls,
  93. remove_end,
  94. remove_quotes,
  95. remove_start,
  96. render_table,
  97. replace_extension,
  98. rot47,
  99. sanitize_filename,
  100. sanitize_path,
  101. sanitize_url,
  102. shell_quote,
  103. smuggle_url,
  104. str_to_int,
  105. strip_jsonp,
  106. strip_or_none,
  107. subtitles_filename,
  108. timeconvert,
  109. try_call,
  110. unescapeHTML,
  111. unified_strdate,
  112. unified_timestamp,
  113. unsmuggle_url,
  114. update_url_query,
  115. uppercase_escape,
  116. url_basename,
  117. url_or_none,
  118. urlencode_postdata,
  119. urljoin,
  120. urshift,
  121. variadic,
  122. version_tuple,
  123. xpath_attr,
  124. xpath_element,
  125. xpath_text,
  126. xpath_with_ns,
  127. )
  128. from yt_dlp.utils._utils import _UnsafeExtensionError
  129. from yt_dlp.utils.networking import (
  130. HTTPHeaderDict,
  131. escape_rfc3986,
  132. normalize_url,
  133. remove_dot_segments,
  134. )
  135. class TestUtil(unittest.TestCase):
  136. def test_timeconvert(self):
  137. self.assertTrue(timeconvert('') is None)
  138. self.assertTrue(timeconvert('bougrg') is None)
  139. def test_sanitize_filename(self):
  140. self.assertEqual(sanitize_filename(''), '')
  141. self.assertEqual(sanitize_filename('abc'), 'abc')
  142. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  143. self.assertEqual(sanitize_filename('123'), '123')
  144. self.assertEqual('abc⧸de', sanitize_filename('abc/de'))
  145. self.assertFalse('/' in sanitize_filename('abc/de///'))
  146. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', is_id=False))
  147. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', is_id=False))
  148. self.assertEqual('yes no', sanitize_filename('yes? no', is_id=False))
  149. self.assertEqual('this - that', sanitize_filename('this: that', is_id=False))
  150. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  151. aumlaut = 'ä'
  152. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  153. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  154. self.assertEqual(sanitize_filename(tests), tests)
  155. self.assertEqual(
  156. sanitize_filename('New World record at 0:12:34'),
  157. 'New World record at 0_12_34')
  158. self.assertEqual(sanitize_filename('--gasdgf'), '--gasdgf')
  159. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  160. self.assertEqual(sanitize_filename('--gasdgf', is_id=False), '_-gasdgf')
  161. self.assertEqual(sanitize_filename('.gasdgf'), '.gasdgf')
  162. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  163. self.assertEqual(sanitize_filename('.gasdgf', is_id=False), 'gasdgf')
  164. forbidden = '"\0\\/'
  165. for fc in forbidden:
  166. for fbc in forbidden:
  167. self.assertTrue(fbc not in sanitize_filename(fc))
  168. def test_sanitize_filename_restricted(self):
  169. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  170. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  171. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  172. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  173. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  174. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  175. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  176. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  177. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  178. tests = 'aäb\u4e2d\u56fd\u7684c'
  179. self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
  180. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  181. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  182. for fc in forbidden:
  183. for fbc in forbidden:
  184. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  185. # Handle a common case more neatly
  186. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  187. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  188. # .. but make sure the file name is never empty
  189. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  190. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  191. self.assertEqual(sanitize_filename(
  192. 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
  193. 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
  194. def test_sanitize_ids(self):
  195. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  196. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  197. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  198. def test_sanitize_path(self):
  199. if sys.platform != 'win32':
  200. return
  201. self.assertEqual(sanitize_path('abc'), 'abc')
  202. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  203. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  204. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  205. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  206. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  207. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  208. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  209. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  210. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  211. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  212. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  213. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  214. self.assertEqual(
  215. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  216. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  217. self.assertEqual(
  218. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  219. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  220. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  221. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  222. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  223. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  224. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  225. self.assertEqual(sanitize_path('./abc'), 'abc')
  226. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  227. def test_sanitize_url(self):
  228. self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
  229. self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
  230. self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
  231. self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
  232. self.assertEqual(sanitize_url('foo bar'), 'foo bar')
  233. def test_expand_path(self):
  234. def env(var):
  235. return f'%{var}%' if sys.platform == 'win32' else f'${var}'
  236. os.environ['yt_dlp_EXPATH_PATH'] = 'expanded'
  237. self.assertEqual(expand_path(env('yt_dlp_EXPATH_PATH')), 'expanded')
  238. old_home = os.environ.get('HOME')
  239. test_str = R'C:\Documents and Settings\тест\Application Data'
  240. try:
  241. os.environ['HOME'] = test_str
  242. self.assertEqual(expand_path(env('HOME')), os.getenv('HOME'))
  243. self.assertEqual(expand_path('~'), os.getenv('HOME'))
  244. self.assertEqual(
  245. expand_path('~/{}'.format(env('yt_dlp_EXPATH_PATH'))),
  246. '{}/expanded'.format(os.getenv('HOME')))
  247. finally:
  248. os.environ['HOME'] = old_home or ''
  249. _uncommon_extensions = [
  250. ('exe', 'abc.exe.ext'),
  251. ('de', 'abc.de.ext'),
  252. ('../.mp4', None),
  253. ('..\\.mp4', None),
  254. ]
  255. def test_prepend_extension(self):
  256. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  257. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  258. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  259. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  260. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  261. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  262. # Test uncommon extensions
  263. self.assertEqual(prepend_extension('abc.ext', 'bin'), 'abc.bin.ext')
  264. for ext, result in self._uncommon_extensions:
  265. with self.assertRaises(_UnsafeExtensionError):
  266. prepend_extension('abc', ext)
  267. if result:
  268. self.assertEqual(prepend_extension('abc.ext', ext, 'ext'), result)
  269. else:
  270. with self.assertRaises(_UnsafeExtensionError):
  271. prepend_extension('abc.ext', ext, 'ext')
  272. with self.assertRaises(_UnsafeExtensionError):
  273. prepend_extension('abc.unexpected_ext', ext, 'ext')
  274. def test_replace_extension(self):
  275. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  276. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  277. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  278. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  279. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  280. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  281. # Test uncommon extensions
  282. self.assertEqual(replace_extension('abc.ext', 'bin'), 'abc.unknown_video')
  283. for ext, _ in self._uncommon_extensions:
  284. with self.assertRaises(_UnsafeExtensionError):
  285. replace_extension('abc', ext)
  286. with self.assertRaises(_UnsafeExtensionError):
  287. replace_extension('abc.ext', ext, 'ext')
  288. with self.assertRaises(_UnsafeExtensionError):
  289. replace_extension('abc.unexpected_ext', ext, 'ext')
  290. def test_subtitles_filename(self):
  291. self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
  292. self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
  293. self.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
  294. def test_remove_start(self):
  295. self.assertEqual(remove_start(None, 'A - '), None)
  296. self.assertEqual(remove_start('A - B', 'A - '), 'B')
  297. self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
  298. def test_remove_end(self):
  299. self.assertEqual(remove_end(None, ' - B'), None)
  300. self.assertEqual(remove_end('A - B', ' - B'), 'A')
  301. self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
  302. def test_remove_quotes(self):
  303. self.assertEqual(remove_quotes(None), None)
  304. self.assertEqual(remove_quotes('"'), '"')
  305. self.assertEqual(remove_quotes("'"), "'")
  306. self.assertEqual(remove_quotes(';'), ';')
  307. self.assertEqual(remove_quotes('";'), '";')
  308. self.assertEqual(remove_quotes('""'), '')
  309. self.assertEqual(remove_quotes('";"'), ';')
  310. def test_ordered_set(self):
  311. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  312. self.assertEqual(orderedSet([]), [])
  313. self.assertEqual(orderedSet([1]), [1])
  314. # keep the list ordered
  315. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  316. def test_unescape_html(self):
  317. self.assertEqual(unescapeHTML('%20;'), '%20;')
  318. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  319. self.assertEqual(unescapeHTML('&#47;'), '/')
  320. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  321. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  322. self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
  323. # HTML5 entities
  324. self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
  325. def test_date_from_str(self):
  326. self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
  327. self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
  328. self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
  329. self.assertEqual(date_from_str('20200229+365day'), date_from_str('20200229+1year'))
  330. self.assertEqual(date_from_str('20210131+28day'), date_from_str('20210131+1month'))
  331. def test_datetime_from_str(self):
  332. self.assertEqual(datetime_from_str('yesterday', precision='day'), datetime_from_str('now-1day', precision='auto'))
  333. self.assertEqual(datetime_from_str('now+7day', precision='day'), datetime_from_str('now+1week', precision='auto'))
  334. self.assertEqual(datetime_from_str('now+14day', precision='day'), datetime_from_str('now+2week', precision='auto'))
  335. self.assertEqual(datetime_from_str('20200229+365day', precision='day'), datetime_from_str('20200229+1year', precision='auto'))
  336. self.assertEqual(datetime_from_str('20210131+28day', precision='day'), datetime_from_str('20210131+1month', precision='auto'))
  337. self.assertEqual(datetime_from_str('20210131+59day', precision='day'), datetime_from_str('20210131+2month', precision='auto'))
  338. self.assertEqual(datetime_from_str('now+1day', precision='hour'), datetime_from_str('now+24hours', precision='auto'))
  339. self.assertEqual(datetime_from_str('now+23hours', precision='hour'), datetime_from_str('now+23hours', precision='auto'))
  340. def test_daterange(self):
  341. _20century = DateRange('19000101', '20000101')
  342. self.assertFalse('17890714' in _20century)
  343. _ac = DateRange('00010101')
  344. self.assertTrue('19690721' in _ac)
  345. _firstmilenium = DateRange(end='10000101')
  346. self.assertTrue('07110427' in _firstmilenium)
  347. def test_unified_dates(self):
  348. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  349. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  350. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  351. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  352. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  353. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  354. self.assertEqual(unified_strdate('31-07-2022 20:00'), '20220731')
  355. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  356. self.assertEqual(
  357. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  358. '20141126')
  359. self.assertEqual(
  360. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  361. '20150202')
  362. self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
  363. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  364. self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
  365. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  366. self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
  367. self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
  368. self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
  369. self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
  370. self.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
  371. self.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
  372. def test_unified_timestamps(self):
  373. self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
  374. self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
  375. self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
  376. self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
  377. self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
  378. self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
  379. self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
  380. self.assertEqual(
  381. unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
  382. 1417001400)
  383. self.assertEqual(
  384. unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
  385. 1422902860)
  386. self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
  387. self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
  388. self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
  389. self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
  390. self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
  391. self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
  392. self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
  393. self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
  394. self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
  395. self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
  396. self.assertEqual(unified_timestamp('December 31 1969 20:00:01 EDT'), 1)
  397. self.assertEqual(unified_timestamp('Wednesday 31 December 1969 18:01:26 MDT'), 86)
  398. self.assertEqual(unified_timestamp('12/31/1969 20:01:18 EDT', False), 78)
  399. def test_determine_ext(self):
  400. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  401. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  402. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  403. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  404. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  405. self.assertEqual(determine_ext('foobar', None), None)
  406. def test_find_xpath_attr(self):
  407. testxml = '''<root>
  408. <node/>
  409. <node x="a"/>
  410. <node x="a" y="c" />
  411. <node x="b" y="d" />
  412. <node x="" />
  413. </root>'''
  414. doc = compat_etree_fromstring(testxml)
  415. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  416. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  417. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  418. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  419. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  420. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  421. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  422. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  423. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  424. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  425. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  426. def test_xpath_with_ns(self):
  427. testxml = '''<root xmlns:media="http://example.com/">
  428. <media:song>
  429. <media:author>The Author</media:author>
  430. <url>http://server.com/download.mp3</url>
  431. </media:song>
  432. </root>'''
  433. doc = compat_etree_fromstring(testxml)
  434. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  435. self.assertTrue(find('media:song') is not None)
  436. self.assertEqual(find('media:song/media:author').text, 'The Author')
  437. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  438. def test_xpath_element(self):
  439. doc = xml.etree.ElementTree.Element('root')
  440. div = xml.etree.ElementTree.SubElement(doc, 'div')
  441. p = xml.etree.ElementTree.SubElement(div, 'p')
  442. p.text = 'Foo'
  443. self.assertEqual(xpath_element(doc, 'div/p'), p)
  444. self.assertEqual(xpath_element(doc, ['div/p']), p)
  445. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  446. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  447. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  448. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  449. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  450. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  451. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  452. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  453. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  454. def test_xpath_text(self):
  455. testxml = '''<root>
  456. <div>
  457. <p>Foo</p>
  458. </div>
  459. </root>'''
  460. doc = compat_etree_fromstring(testxml)
  461. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  462. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  463. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  464. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  465. def test_xpath_attr(self):
  466. testxml = '''<root>
  467. <div>
  468. <p x="a">Foo</p>
  469. </div>
  470. </root>'''
  471. doc = compat_etree_fromstring(testxml)
  472. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  473. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  474. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  475. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  476. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  477. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  478. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  479. def test_smuggle_url(self):
  480. data = {'ö': 'ö', 'abc': [3]}
  481. url = 'https://foo.bar/baz?x=y#a'
  482. smug_url = smuggle_url(url, data)
  483. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  484. self.assertEqual(url, unsmug_url)
  485. self.assertEqual(data, unsmug_data)
  486. res_url, res_data = unsmuggle_url(url)
  487. self.assertEqual(res_url, url)
  488. self.assertEqual(res_data, None)
  489. smug_url = smuggle_url(url, {'a': 'b'})
  490. smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
  491. res_url, res_data = unsmuggle_url(smug_smug_url)
  492. self.assertEqual(res_url, url)
  493. self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
  494. def test_shell_quote(self):
  495. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  496. self.assertEqual(
  497. shell_quote(args),
  498. """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
  499. def test_float_or_none(self):
  500. self.assertEqual(float_or_none('42.42'), 42.42)
  501. self.assertEqual(float_or_none('42'), 42.0)
  502. self.assertEqual(float_or_none(''), None)
  503. self.assertEqual(float_or_none(None), None)
  504. self.assertEqual(float_or_none([]), None)
  505. self.assertEqual(float_or_none(set()), None)
  506. def test_int_or_none(self):
  507. self.assertEqual(int_or_none('42'), 42)
  508. self.assertEqual(int_or_none(''), None)
  509. self.assertEqual(int_or_none(None), None)
  510. self.assertEqual(int_or_none([]), None)
  511. self.assertEqual(int_or_none(set()), None)
  512. def test_str_to_int(self):
  513. self.assertEqual(str_to_int('123,456'), 123456)
  514. self.assertEqual(str_to_int('123.456'), 123456)
  515. self.assertEqual(str_to_int(523), 523)
  516. self.assertEqual(str_to_int('noninteger'), None)
  517. self.assertEqual(str_to_int([]), None)
  518. def test_url_basename(self):
  519. self.assertEqual(url_basename('http://foo.de/'), '')
  520. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  521. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  522. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  523. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  524. self.assertEqual(
  525. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  526. 'trailer.mp4')
  527. def test_base_url(self):
  528. self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
  529. self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
  530. self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
  531. self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
  532. self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
  533. self.assertEqual(base_url('http://foo.de/bar/baz&x=z&w=y/x/c'), 'http://foo.de/bar/baz&x=z&w=y/x/')
  534. def test_urljoin(self):
  535. self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  536. self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  537. self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  538. self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  539. self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
  540. self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  541. self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  542. self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  543. self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  544. self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  545. self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  546. self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
  547. self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  548. self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
  549. self.assertEqual(urljoin('http://foo.de/', None), None)
  550. self.assertEqual(urljoin('http://foo.de/', ''), None)
  551. self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
  552. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
  553. self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
  554. self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
  555. def test_url_or_none(self):
  556. self.assertEqual(url_or_none(None), None)
  557. self.assertEqual(url_or_none(''), None)
  558. self.assertEqual(url_or_none('foo'), None)
  559. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  560. self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
  561. self.assertEqual(url_or_none('http$://foo.de'), None)
  562. self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
  563. self.assertEqual(url_or_none('//foo.de'), '//foo.de')
  564. self.assertEqual(url_or_none('s3://foo.de'), None)
  565. self.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
  566. self.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
  567. self.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
  568. self.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
  569. def test_parse_age_limit(self):
  570. self.assertEqual(parse_age_limit(None), None)
  571. self.assertEqual(parse_age_limit(False), None)
  572. self.assertEqual(parse_age_limit('invalid'), None)
  573. self.assertEqual(parse_age_limit(0), 0)
  574. self.assertEqual(parse_age_limit(18), 18)
  575. self.assertEqual(parse_age_limit(21), 21)
  576. self.assertEqual(parse_age_limit(22), None)
  577. self.assertEqual(parse_age_limit('18'), 18)
  578. self.assertEqual(parse_age_limit('18+'), 18)
  579. self.assertEqual(parse_age_limit('PG-13'), 13)
  580. self.assertEqual(parse_age_limit('TV-14'), 14)
  581. self.assertEqual(parse_age_limit('TV-MA'), 17)
  582. self.assertEqual(parse_age_limit('TV14'), 14)
  583. self.assertEqual(parse_age_limit('TV_G'), 0)
  584. def test_parse_duration(self):
  585. self.assertEqual(parse_duration(None), None)
  586. self.assertEqual(parse_duration(False), None)
  587. self.assertEqual(parse_duration('invalid'), None)
  588. self.assertEqual(parse_duration('1'), 1)
  589. self.assertEqual(parse_duration('1337:12'), 80232)
  590. self.assertEqual(parse_duration('9:12:43'), 33163)
  591. self.assertEqual(parse_duration('12:00'), 720)
  592. self.assertEqual(parse_duration('00:01:01'), 61)
  593. self.assertEqual(parse_duration('x:y'), None)
  594. self.assertEqual(parse_duration('3h11m53s'), 11513)
  595. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  596. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  597. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  598. self.assertEqual(parse_duration('3 hours, 11 minutes, 53 seconds'), 11513)
  599. self.assertEqual(parse_duration('3 hours, 11 mins, 53 secs'), 11513)
  600. self.assertEqual(parse_duration('62m45s'), 3765)
  601. self.assertEqual(parse_duration('6m59s'), 419)
  602. self.assertEqual(parse_duration('49s'), 49)
  603. self.assertEqual(parse_duration('0h0m0s'), 0)
  604. self.assertEqual(parse_duration('0m0s'), 0)
  605. self.assertEqual(parse_duration('0s'), 0)
  606. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  607. self.assertEqual(parse_duration('T30M38S'), 1838)
  608. self.assertEqual(parse_duration('5 s'), 5)
  609. self.assertEqual(parse_duration('3 min'), 180)
  610. self.assertEqual(parse_duration('2.5 hours'), 9000)
  611. self.assertEqual(parse_duration('02:03:04'), 7384)
  612. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  613. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  614. self.assertEqual(parse_duration('87 Min.'), 5220)
  615. self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
  616. self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
  617. self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
  618. self.assertEqual(parse_duration('01:02:03:050'), 3723.05)
  619. self.assertEqual(parse_duration('103:050'), 103.05)
  620. self.assertEqual(parse_duration('1HR 3MIN'), 3780)
  621. self.assertEqual(parse_duration('2hrs 3mins'), 7380)
  622. def test_fix_xml_ampersands(self):
  623. self.assertEqual(
  624. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  625. self.assertEqual(
  626. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  627. '"&amp;x=y&amp;wrong;&amp;z=a')
  628. self.assertEqual(
  629. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  630. '&amp;&apos;&gt;&lt;&quot;')
  631. self.assertEqual(
  632. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  633. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  634. def test_paged_list(self):
  635. def testPL(size, pagesize, sliceargs, expected):
  636. def get_page(pagenum):
  637. firstid = pagenum * pagesize
  638. upto = min(size, pagenum * pagesize + pagesize)
  639. yield from range(firstid, upto)
  640. pl = OnDemandPagedList(get_page, pagesize)
  641. got = pl.getslice(*sliceargs)
  642. self.assertEqual(got, expected)
  643. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  644. got = iapl.getslice(*sliceargs)
  645. self.assertEqual(got, expected)
  646. testPL(5, 2, (), [0, 1, 2, 3, 4])
  647. testPL(5, 2, (1,), [1, 2, 3, 4])
  648. testPL(5, 2, (2,), [2, 3, 4])
  649. testPL(5, 2, (4,), [4])
  650. testPL(5, 2, (0, 3), [0, 1, 2])
  651. testPL(5, 2, (1, 4), [1, 2, 3])
  652. testPL(5, 2, (2, 99), [2, 3, 4])
  653. testPL(5, 2, (20, 99), [])
  654. def test_read_batch_urls(self):
  655. f = io.StringIO('''\xef\xbb\xbf foo
  656. bar\r
  657. baz
  658. # More after this line\r
  659. ; or after this
  660. bam''')
  661. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  662. def test_urlencode_postdata(self):
  663. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  664. self.assertTrue(isinstance(data, bytes))
  665. def test_update_url_query(self):
  666. self.assertEqual(parse_qs(update_url_query(
  667. 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
  668. parse_qs('http://example.com/path?quality=HD&format=mp4'))
  669. self.assertEqual(parse_qs(update_url_query(
  670. 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
  671. parse_qs('http://example.com/path?system=LINUX&system=WINDOWS'))
  672. self.assertEqual(parse_qs(update_url_query(
  673. 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
  674. parse_qs('http://example.com/path?fields=id,formats,subtitles'))
  675. self.assertEqual(parse_qs(update_url_query(
  676. 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
  677. parse_qs('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
  678. self.assertEqual(parse_qs(update_url_query(
  679. 'http://example.com/path?manifest=f4m', {'manifest': []})),
  680. parse_qs('http://example.com/path'))
  681. self.assertEqual(parse_qs(update_url_query(
  682. 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
  683. parse_qs('http://example.com/path?system=LINUX'))
  684. self.assertEqual(parse_qs(update_url_query(
  685. 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
  686. parse_qs('http://example.com/path?fields=id,formats,subtitles'))
  687. self.assertEqual(parse_qs(update_url_query(
  688. 'http://example.com/path', {'width': 1080, 'height': 720})),
  689. parse_qs('http://example.com/path?width=1080&height=720'))
  690. self.assertEqual(parse_qs(update_url_query(
  691. 'http://example.com/path', {'bitrate': 5020.43})),
  692. parse_qs('http://example.com/path?bitrate=5020.43'))
  693. self.assertEqual(parse_qs(update_url_query(
  694. 'http://example.com/path', {'test': '第二行тест'})),
  695. parse_qs('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
  696. def test_multipart_encode(self):
  697. self.assertEqual(
  698. multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
  699. b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
  700. self.assertEqual(
  701. multipart_encode({'欄位'.encode(): '值'.encode()}, boundary='AAAAAA')[0],
  702. 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')
  703. self.assertRaises(
  704. ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
  705. def test_merge_dicts(self):
  706. self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
  707. self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
  708. self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
  709. self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
  710. self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
  711. self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
  712. self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
  713. self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  714. self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
  715. def test_encode_compat_str(self):
  716. self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
  717. self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
  718. def test_parse_iso8601(self):
  719. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  720. self.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00'), 1395641066)
  721. self.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone=dt.timedelta(hours=-7)), 1395641066)
  722. self.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone=NO_DEFAULT), None)
  723. # default does not override timezone in date_str
  724. self.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00', timezone=dt.timedelta(hours=-10)), 1395641066)
  725. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  726. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  727. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  728. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  729. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  730. def test_strip_jsonp(self):
  731. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  732. d = json.loads(stripped)
  733. self.assertEqual(d, [{'id': '532cb', 'x': 3}])
  734. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  735. d = json.loads(stripped)
  736. self.assertEqual(d, {'STATUS': 'OK'})
  737. stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
  738. d = json.loads(stripped)
  739. self.assertEqual(d, {'status': 'success'})
  740. stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
  741. d = json.loads(stripped)
  742. self.assertEqual(d, {'status': 'success'})
  743. stripped = strip_jsonp('window.cb && cb({"status": "success"});')
  744. d = json.loads(stripped)
  745. self.assertEqual(d, {'status': 'success'})
  746. stripped = strip_jsonp('({"status": "success"});')
  747. d = json.loads(stripped)
  748. self.assertEqual(d, {'status': 'success'})
  749. def test_strip_or_none(self):
  750. self.assertEqual(strip_or_none(' abc'), 'abc')
  751. self.assertEqual(strip_or_none('abc '), 'abc')
  752. self.assertEqual(strip_or_none(' abc '), 'abc')
  753. self.assertEqual(strip_or_none('\tabc\t'), 'abc')
  754. self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
  755. self.assertEqual(strip_or_none('abc'), 'abc')
  756. self.assertEqual(strip_or_none(''), '')
  757. self.assertEqual(strip_or_none(None), None)
  758. self.assertEqual(strip_or_none(42), None)
  759. self.assertEqual(strip_or_none([]), None)
  760. def test_uppercase_escape(self):
  761. self.assertEqual(uppercase_escape('aä'), 'aä')
  762. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  763. def test_lowercase_escape(self):
  764. self.assertEqual(lowercase_escape('aä'), 'aä')
  765. self.assertEqual(lowercase_escape('\\u0026'), '&')
  766. def test_limit_length(self):
  767. self.assertEqual(limit_length(None, 12), None)
  768. self.assertEqual(limit_length('foo', 12), 'foo')
  769. self.assertTrue(
  770. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  771. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  772. def test_mimetype2ext(self):
  773. self.assertEqual(mimetype2ext(None), None)
  774. self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
  775. self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
  776. self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
  777. self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
  778. self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
  779. self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
  780. self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
  781. def test_month_by_name(self):
  782. self.assertEqual(month_by_name(None), None)
  783. self.assertEqual(month_by_name('December', 'en'), 12)
  784. self.assertEqual(month_by_name('décembre', 'fr'), 12)
  785. self.assertEqual(month_by_name('December'), 12)
  786. self.assertEqual(month_by_name('décembre'), None)
  787. self.assertEqual(month_by_name('Unknown', 'unknown'), None)
  788. def test_parse_codecs(self):
  789. self.assertEqual(parse_codecs(''), {})
  790. self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
  791. 'vcodec': 'avc1.77.30',
  792. 'acodec': 'mp4a.40.2',
  793. 'dynamic_range': None,
  794. })
  795. self.assertEqual(parse_codecs('mp4a.40.2'), {
  796. 'vcodec': 'none',
  797. 'acodec': 'mp4a.40.2',
  798. 'dynamic_range': None,
  799. })
  800. self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
  801. 'vcodec': 'avc1.42001e',
  802. 'acodec': 'mp4a.40.5',
  803. 'dynamic_range': None,
  804. })
  805. self.assertEqual(parse_codecs('avc3.640028'), {
  806. 'vcodec': 'avc3.640028',
  807. 'acodec': 'none',
  808. 'dynamic_range': None,
  809. })
  810. self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
  811. 'vcodec': 'h264',
  812. 'acodec': 'aac',
  813. 'dynamic_range': None,
  814. })
  815. self.assertEqual(parse_codecs('av01.0.05M.08'), {
  816. 'vcodec': 'av01.0.05M.08',
  817. 'acodec': 'none',
  818. 'dynamic_range': None,
  819. })
  820. self.assertEqual(parse_codecs('vp9.2'), {
  821. 'vcodec': 'vp9.2',
  822. 'acodec': 'none',
  823. 'dynamic_range': 'HDR10',
  824. })
  825. self.assertEqual(parse_codecs('av01.0.12M.10.0.110.09.16.09.0'), {
  826. 'vcodec': 'av01.0.12M.10.0.110.09.16.09.0',
  827. 'acodec': 'none',
  828. 'dynamic_range': 'HDR10',
  829. })
  830. self.assertEqual(parse_codecs('dvhe'), {
  831. 'vcodec': 'dvhe',
  832. 'acodec': 'none',
  833. 'dynamic_range': 'DV',
  834. })
  835. self.assertEqual(parse_codecs('theora, vorbis'), {
  836. 'vcodec': 'theora',
  837. 'acodec': 'vorbis',
  838. 'dynamic_range': None,
  839. })
  840. self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
  841. 'vcodec': 'unknownvcodec',
  842. 'acodec': 'unknownacodec',
  843. })
  844. self.assertEqual(parse_codecs('unknown'), {})
  845. def test_escape_rfc3986(self):
  846. reserved = "!*'();:@&=+$,/?#[]"
  847. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  848. self.assertEqual(escape_rfc3986(reserved), reserved)
  849. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  850. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  851. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  852. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  853. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  854. def test_normalize_url(self):
  855. self.assertEqual(
  856. normalize_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  857. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4',
  858. )
  859. self.assertEqual(
  860. normalize_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
  861. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290',
  862. )
  863. self.assertEqual(
  864. normalize_url('http://тест.рф/фрагмент'),
  865. 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82',
  866. )
  867. self.assertEqual(
  868. normalize_url('http://тест.рф/абв?абв=абв#абв'),
  869. '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',
  870. )
  871. self.assertEqual(normalize_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  872. self.assertEqual(normalize_url('http://www.example.com/../a/b/../c/./d.html'), 'http://www.example.com/a/c/d.html')
  873. def test_remove_dot_segments(self):
  874. self.assertEqual(remove_dot_segments('/a/b/c/./../../g'), '/a/g')
  875. self.assertEqual(remove_dot_segments('mid/content=5/../6'), 'mid/6')
  876. self.assertEqual(remove_dot_segments('/ad/../cd'), '/cd')
  877. self.assertEqual(remove_dot_segments('/ad/../cd/'), '/cd/')
  878. self.assertEqual(remove_dot_segments('/..'), '/')
  879. self.assertEqual(remove_dot_segments('/./'), '/')
  880. self.assertEqual(remove_dot_segments('/./a'), '/a')
  881. self.assertEqual(remove_dot_segments('/abc/./.././d/././e/.././f/./../../ghi'), '/ghi')
  882. self.assertEqual(remove_dot_segments('/'), '/')
  883. self.assertEqual(remove_dot_segments('/t'), '/t')
  884. self.assertEqual(remove_dot_segments('t'), 't')
  885. self.assertEqual(remove_dot_segments(''), '')
  886. self.assertEqual(remove_dot_segments('/../a/b/c'), '/a/b/c')
  887. self.assertEqual(remove_dot_segments('../a'), 'a')
  888. self.assertEqual(remove_dot_segments('./a'), 'a')
  889. self.assertEqual(remove_dot_segments('.'), '')
  890. self.assertEqual(remove_dot_segments('////'), '////')
  891. def test_js_to_json_vars_strings(self):
  892. self.assertDictEqual(
  893. json.loads(js_to_json(
  894. '''{
  895. 'null': a,
  896. 'nullStr': b,
  897. 'true': c,
  898. 'trueStr': d,
  899. 'false': e,
  900. 'falseStr': f,
  901. 'unresolvedVar': g,
  902. }''',
  903. {
  904. 'a': 'null',
  905. 'b': '"null"',
  906. 'c': 'true',
  907. 'd': '"true"',
  908. 'e': 'false',
  909. 'f': '"false"',
  910. 'g': 'var',
  911. },
  912. )),
  913. {
  914. 'null': None,
  915. 'nullStr': 'null',
  916. 'true': True,
  917. 'trueStr': 'true',
  918. 'false': False,
  919. 'falseStr': 'false',
  920. 'unresolvedVar': 'var',
  921. },
  922. )
  923. self.assertDictEqual(
  924. json.loads(js_to_json(
  925. '''{
  926. 'int': a,
  927. 'intStr': b,
  928. 'float': c,
  929. 'floatStr': d,
  930. }''',
  931. {
  932. 'a': '123',
  933. 'b': '"123"',
  934. 'c': '1.23',
  935. 'd': '"1.23"',
  936. },
  937. )),
  938. {
  939. 'int': 123,
  940. 'intStr': '123',
  941. 'float': 1.23,
  942. 'floatStr': '1.23',
  943. },
  944. )
  945. self.assertDictEqual(
  946. json.loads(js_to_json(
  947. '''{
  948. 'object': a,
  949. 'objectStr': b,
  950. 'array': c,
  951. 'arrayStr': d,
  952. }''',
  953. {
  954. 'a': '{}',
  955. 'b': '"{}"',
  956. 'c': '[]',
  957. 'd': '"[]"',
  958. },
  959. )),
  960. {
  961. 'object': {},
  962. 'objectStr': '{}',
  963. 'array': [],
  964. 'arrayStr': '[]',
  965. },
  966. )
  967. def test_js_to_json_realworld(self):
  968. inp = '''{
  969. 'clip':{'provider':'pseudo'}
  970. }'''
  971. self.assertEqual(js_to_json(inp), '''{
  972. "clip":{"provider":"pseudo"}
  973. }''')
  974. json.loads(js_to_json(inp))
  975. inp = '''{
  976. 'playlist':[{'controls':{'all':null}}]
  977. }'''
  978. self.assertEqual(js_to_json(inp), '''{
  979. "playlist":[{"controls":{"all":null}}]
  980. }''')
  981. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  982. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  983. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  984. json_code = js_to_json(inp)
  985. self.assertEqual(json.loads(json_code), json.loads(inp))
  986. inp = '''{
  987. 0:{src:'skipped', type: 'application/dash+xml'},
  988. 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
  989. }'''
  990. self.assertEqual(js_to_json(inp), '''{
  991. "0":{"src":"skipped", "type": "application/dash+xml"},
  992. "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
  993. }''')
  994. inp = '''{"foo":101}'''
  995. self.assertEqual(js_to_json(inp), '''{"foo":101}''')
  996. inp = '''{"duration": "00:01:07"}'''
  997. self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
  998. inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
  999. self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
  1000. def test_js_to_json_edgecases(self):
  1001. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  1002. self.assertEqual(json.loads(on), {'abc_def': "1'\\2\\'3\"4"})
  1003. on = js_to_json('{"abc": true}')
  1004. self.assertEqual(json.loads(on), {'abc': True})
  1005. # Ignore JavaScript code as well
  1006. on = js_to_json('''{
  1007. "x": 1,
  1008. y: "a",
  1009. z: some.code
  1010. }''')
  1011. d = json.loads(on)
  1012. self.assertEqual(d['x'], 1)
  1013. self.assertEqual(d['y'], 'a')
  1014. # Just drop ! prefix for now though this results in a wrong value
  1015. on = js_to_json('''{
  1016. a: !0,
  1017. b: !1,
  1018. c: !!0,
  1019. d: !!42.42,
  1020. e: !!![],
  1021. f: !"abc",
  1022. g: !"",
  1023. !42: 42
  1024. }''')
  1025. self.assertEqual(json.loads(on), {
  1026. 'a': 0,
  1027. 'b': 1,
  1028. 'c': 0,
  1029. 'd': 42.42,
  1030. 'e': [],
  1031. 'f': 'abc',
  1032. 'g': '',
  1033. '42': 42,
  1034. })
  1035. on = js_to_json('["abc", "def",]')
  1036. self.assertEqual(json.loads(on), ['abc', 'def'])
  1037. on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
  1038. self.assertEqual(json.loads(on), ['abc', 'def'])
  1039. on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
  1040. self.assertEqual(json.loads(on), ['abc', 'def'])
  1041. on = js_to_json('{"abc": "def",}')
  1042. self.assertEqual(json.loads(on), {'abc': 'def'})
  1043. on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
  1044. self.assertEqual(json.loads(on), {'abc': 'def'})
  1045. on = js_to_json('{ 0: /* " \n */ ",]" , }')
  1046. self.assertEqual(json.loads(on), {'0': ',]'})
  1047. on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
  1048. self.assertEqual(json.loads(on), {'0': ',]'})
  1049. on = js_to_json('{ 0: // comment\n1 }')
  1050. self.assertEqual(json.loads(on), {'0': 1})
  1051. on = js_to_json(r'["<p>x<\/p>"]')
  1052. self.assertEqual(json.loads(on), ['<p>x</p>'])
  1053. on = js_to_json(r'["\xaa"]')
  1054. self.assertEqual(json.loads(on), ['\u00aa'])
  1055. on = js_to_json("['a\\\nb']")
  1056. self.assertEqual(json.loads(on), ['ab'])
  1057. on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
  1058. self.assertEqual(json.loads(on), ['ab'])
  1059. on = js_to_json('{0xff:0xff}')
  1060. self.assertEqual(json.loads(on), {'255': 255})
  1061. on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
  1062. self.assertEqual(json.loads(on), {'255': 255})
  1063. on = js_to_json('{077:077}')
  1064. self.assertEqual(json.loads(on), {'63': 63})
  1065. on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
  1066. self.assertEqual(json.loads(on), {'63': 63})
  1067. on = js_to_json('{42:42}')
  1068. self.assertEqual(json.loads(on), {'42': 42})
  1069. on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
  1070. self.assertEqual(json.loads(on), {'42': 42})
  1071. on = js_to_json('{42:4.2e1}')
  1072. self.assertEqual(json.loads(on), {'42': 42.0})
  1073. on = js_to_json('{ "0x40": "0x40" }')
  1074. self.assertEqual(json.loads(on), {'0x40': '0x40'})
  1075. on = js_to_json('{ "040": "040" }')
  1076. self.assertEqual(json.loads(on), {'040': '040'})
  1077. on = js_to_json('[1,//{},\n2]')
  1078. self.assertEqual(json.loads(on), [1, 2])
  1079. on = js_to_json(R'"\^\$\#"')
  1080. self.assertEqual(json.loads(on), R'^$#', msg='Unnecessary escapes should be stripped')
  1081. on = js_to_json('\'"\\""\'')
  1082. self.assertEqual(json.loads(on), '"""', msg='Unnecessary quote escape should be escaped')
  1083. on = js_to_json('[new Date("spam"), \'("eggs")\']')
  1084. self.assertEqual(json.loads(on), ['spam', '("eggs")'], msg='Date regex should match a single string')
  1085. def test_js_to_json_malformed(self):
  1086. self.assertEqual(js_to_json('42a1'), '42"a1"')
  1087. self.assertEqual(js_to_json('42a-1'), '42"a"-1')
  1088. def test_js_to_json_template_literal(self):
  1089. self.assertEqual(js_to_json('`Hello ${name}`', {'name': '"world"'}), '"Hello world"')
  1090. self.assertEqual(js_to_json('`${name}${name}`', {'name': '"X"'}), '"XX"')
  1091. self.assertEqual(js_to_json('`${name}${name}`', {'name': '5'}), '"55"')
  1092. self.assertEqual(js_to_json('`${name}"${name}"`', {'name': '5'}), '"5\\"5\\""')
  1093. self.assertEqual(js_to_json('`${name}`', {}), '"name"')
  1094. def test_js_to_json_common_constructors(self):
  1095. self.assertEqual(json.loads(js_to_json('new Map([["a", 5]])')), {'a': 5})
  1096. self.assertEqual(json.loads(js_to_json('Array(5, 10)')), [5, 10])
  1097. self.assertEqual(json.loads(js_to_json('new Array(15,5)')), [15, 5])
  1098. self.assertEqual(json.loads(js_to_json('new Map([Array(5, 10),new Array(15,5)])')), {'5': 10, '15': 5})
  1099. self.assertEqual(json.loads(js_to_json('new Date("123")')), '123')
  1100. self.assertEqual(json.loads(js_to_json('new Date(\'2023-10-19\')')), '2023-10-19')
  1101. def test_extract_attributes(self):
  1102. self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
  1103. self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
  1104. self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
  1105. self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
  1106. self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
  1107. self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
  1108. self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
  1109. self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
  1110. self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
  1111. self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
  1112. self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
  1113. self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
  1114. self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
  1115. self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
  1116. self.assertEqual(extract_attributes('<e x >'), {'x': None})
  1117. self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
  1118. self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
  1119. self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
  1120. self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
  1121. self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
  1122. self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
  1123. self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
  1124. self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
  1125. self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
  1126. self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
  1127. self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
  1128. self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
  1129. self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
  1130. # "Narrow" Python builds don't support unicode code points outside BMP.
  1131. try:
  1132. chr(0x10000)
  1133. supports_outside_bmp = True
  1134. except ValueError:
  1135. supports_outside_bmp = False
  1136. if supports_outside_bmp:
  1137. self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
  1138. # Malformed HTML should not break attributes extraction on older Python
  1139. self.assertEqual(extract_attributes('<mal"formed/>'), {})
  1140. def test_clean_html(self):
  1141. self.assertEqual(clean_html('a:\nb'), 'a: b')
  1142. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  1143. self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
  1144. def test_intlist_to_bytes(self):
  1145. self.assertEqual(
  1146. intlist_to_bytes([0, 1, 127, 128, 255]),
  1147. b'\x00\x01\x7f\x80\xff')
  1148. def test_args_to_str(self):
  1149. self.assertEqual(
  1150. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  1151. 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""',
  1152. )
  1153. def test_parse_filesize(self):
  1154. self.assertEqual(parse_filesize(None), None)
  1155. self.assertEqual(parse_filesize(''), None)
  1156. self.assertEqual(parse_filesize('91 B'), 91)
  1157. self.assertEqual(parse_filesize('foobar'), None)
  1158. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  1159. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  1160. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  1161. self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
  1162. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  1163. self.assertEqual(parse_filesize('1,24 kb'), 1240)
  1164. self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
  1165. def test_parse_count(self):
  1166. self.assertEqual(parse_count(None), None)
  1167. self.assertEqual(parse_count(''), None)
  1168. self.assertEqual(parse_count('0'), 0)
  1169. self.assertEqual(parse_count('1000'), 1000)
  1170. self.assertEqual(parse_count('1.000'), 1000)
  1171. self.assertEqual(parse_count('1.1k'), 1100)
  1172. self.assertEqual(parse_count('1.1 k'), 1100)
  1173. self.assertEqual(parse_count('1,1 k'), 1100)
  1174. self.assertEqual(parse_count('1.1kk'), 1100000)
  1175. self.assertEqual(parse_count('1.1kk '), 1100000)
  1176. self.assertEqual(parse_count('1,1kk'), 1100000)
  1177. self.assertEqual(parse_count('100 views'), 100)
  1178. self.assertEqual(parse_count('1,100 views'), 1100)
  1179. self.assertEqual(parse_count('1.1kk views'), 1100000)
  1180. self.assertEqual(parse_count('10M views'), 10000000)
  1181. self.assertEqual(parse_count('has 10M views'), 10000000)
  1182. def test_parse_resolution(self):
  1183. self.assertEqual(parse_resolution(None), {})
  1184. self.assertEqual(parse_resolution(''), {})
  1185. self.assertEqual(parse_resolution(' 1920x1080'), {'width': 1920, 'height': 1080})
  1186. self.assertEqual(parse_resolution('1920×1080 '), {'width': 1920, 'height': 1080})
  1187. self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
  1188. self.assertEqual(parse_resolution('720p'), {'height': 720})
  1189. self.assertEqual(parse_resolution('4k'), {'height': 2160})
  1190. self.assertEqual(parse_resolution('8K'), {'height': 4320})
  1191. self.assertEqual(parse_resolution('pre_1920x1080_post'), {'width': 1920, 'height': 1080})
  1192. self.assertEqual(parse_resolution('ep1x2'), {})
  1193. self.assertEqual(parse_resolution('1920, 1080'), {'width': 1920, 'height': 1080})
  1194. def test_parse_bitrate(self):
  1195. self.assertEqual(parse_bitrate(None), None)
  1196. self.assertEqual(parse_bitrate(''), None)
  1197. self.assertEqual(parse_bitrate('300kbps'), 300)
  1198. self.assertEqual(parse_bitrate('1500kbps'), 1500)
  1199. self.assertEqual(parse_bitrate('300 kbps'), 300)
  1200. def test_version_tuple(self):
  1201. self.assertEqual(version_tuple('1'), (1,))
  1202. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  1203. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  1204. def test_detect_exe_version(self):
  1205. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  1206. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  1207. configuration: --prefix=/usr --extra-'''), '1.2.1')
  1208. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  1209. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  1210. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  1211. Trying to open render node...
  1212. Success at /dev/dri/renderD128.
  1213. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  1214. def test_age_restricted(self):
  1215. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  1216. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  1217. self.assertFalse(age_restricted(8, 10))
  1218. self.assertTrue(age_restricted(18, 14))
  1219. self.assertFalse(age_restricted(18, 18))
  1220. def test_is_html(self):
  1221. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  1222. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  1223. self.assertTrue(is_html( # UTF-8 with BOM
  1224. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  1225. self.assertTrue(is_html( # UTF-16-LE
  1226. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00',
  1227. ))
  1228. self.assertTrue(is_html( # UTF-16-BE
  1229. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4',
  1230. ))
  1231. self.assertTrue(is_html( # UTF-32-BE
  1232. 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'))
  1233. self.assertTrue(is_html( # UTF-32-LE
  1234. 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'))
  1235. def test_render_table(self):
  1236. self.assertEqual(
  1237. render_table(
  1238. ['a', 'empty', 'bcd'],
  1239. [[123, '', 4], [9999, '', 51]]),
  1240. 'a empty bcd\n'
  1241. '123 4\n'
  1242. '9999 51')
  1243. self.assertEqual(
  1244. render_table(
  1245. ['a', 'empty', 'bcd'],
  1246. [[123, '', 4], [9999, '', 51]],
  1247. hide_empty=True),
  1248. 'a bcd\n'
  1249. '123 4\n'
  1250. '9999 51')
  1251. self.assertEqual(
  1252. render_table(
  1253. ['\ta', 'bcd'],
  1254. [['1\t23', 4], ['\t9999', 51]]),
  1255. ' a bcd\n'
  1256. '1 23 4\n'
  1257. '9999 51')
  1258. self.assertEqual(
  1259. render_table(
  1260. ['a', 'bcd'],
  1261. [[123, 4], [9999, 51]],
  1262. delim='-'),
  1263. 'a bcd\n'
  1264. '--------\n'
  1265. '123 4\n'
  1266. '9999 51')
  1267. self.assertEqual(
  1268. render_table(
  1269. ['a', 'bcd'],
  1270. [[123, 4], [9999, 51]],
  1271. delim='-', extra_gap=2),
  1272. 'a bcd\n'
  1273. '----------\n'
  1274. '123 4\n'
  1275. '9999 51')
  1276. def test_match_str(self):
  1277. # Unary
  1278. self.assertFalse(match_str('xy', {'x': 1200}))
  1279. self.assertTrue(match_str('!xy', {'x': 1200}))
  1280. self.assertTrue(match_str('x', {'x': 1200}))
  1281. self.assertFalse(match_str('!x', {'x': 1200}))
  1282. self.assertTrue(match_str('x', {'x': 0}))
  1283. self.assertTrue(match_str('is_live', {'is_live': True}))
  1284. self.assertFalse(match_str('is_live', {'is_live': False}))
  1285. self.assertFalse(match_str('is_live', {'is_live': None}))
  1286. self.assertFalse(match_str('is_live', {}))
  1287. self.assertFalse(match_str('!is_live', {'is_live': True}))
  1288. self.assertTrue(match_str('!is_live', {'is_live': False}))
  1289. self.assertTrue(match_str('!is_live', {'is_live': None}))
  1290. self.assertTrue(match_str('!is_live', {}))
  1291. self.assertTrue(match_str('title', {'title': 'abc'}))
  1292. self.assertTrue(match_str('title', {'title': ''}))
  1293. self.assertFalse(match_str('!title', {'title': 'abc'}))
  1294. self.assertFalse(match_str('!title', {'title': ''}))
  1295. # Numeric
  1296. self.assertFalse(match_str('x>0', {'x': 0}))
  1297. self.assertFalse(match_str('x>0', {}))
  1298. self.assertTrue(match_str('x>?0', {}))
  1299. self.assertTrue(match_str('x>1K', {'x': 1200}))
  1300. self.assertFalse(match_str('x>2K', {'x': 1200}))
  1301. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  1302. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  1303. self.assertTrue(match_str('x > 1:0:0', {'x': 3700}))
  1304. # String
  1305. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  1306. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  1307. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  1308. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  1309. self.assertTrue(match_str('y^=foo', {'y': 'foobar42'}))
  1310. self.assertFalse(match_str('y!^=foo', {'y': 'foobar42'}))
  1311. self.assertFalse(match_str('y^=bar', {'y': 'foobar42'}))
  1312. self.assertTrue(match_str('y!^=bar', {'y': 'foobar42'}))
  1313. self.assertRaises(ValueError, match_str, 'x^=42', {'x': 42})
  1314. self.assertTrue(match_str('y*=bar', {'y': 'foobar42'}))
  1315. self.assertFalse(match_str('y!*=bar', {'y': 'foobar42'}))
  1316. self.assertFalse(match_str('y*=baz', {'y': 'foobar42'}))
  1317. self.assertTrue(match_str('y!*=baz', {'y': 'foobar42'}))
  1318. self.assertTrue(match_str('y$=42', {'y': 'foobar42'}))
  1319. self.assertFalse(match_str('y$=43', {'y': 'foobar42'}))
  1320. # And
  1321. self.assertFalse(match_str(
  1322. 'like_count > 100 & dislike_count <? 50 & description',
  1323. {'like_count': 90, 'description': 'foo'}))
  1324. self.assertTrue(match_str(
  1325. 'like_count > 100 & dislike_count <? 50 & description',
  1326. {'like_count': 190, 'description': 'foo'}))
  1327. self.assertFalse(match_str(
  1328. 'like_count > 100 & dislike_count <? 50 & description',
  1329. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  1330. self.assertFalse(match_str(
  1331. 'like_count > 100 & dislike_count <? 50 & description',
  1332. {'like_count': 190, 'dislike_count': 10}))
  1333. # Regex
  1334. self.assertTrue(match_str(r'x~=\bbar', {'x': 'foo bar'}))
  1335. self.assertFalse(match_str(r'x~=\bbar.+', {'x': 'foo bar'}))
  1336. self.assertFalse(match_str(r'x~=^FOO', {'x': 'foo bar'}))
  1337. self.assertTrue(match_str(r'x~=(?i)^FOO', {'x': 'foo bar'}))
  1338. # Quotes
  1339. self.assertTrue(match_str(r'x^="foo"', {'x': 'foo "bar"'}))
  1340. self.assertFalse(match_str(r'x^="foo "', {'x': 'foo "bar"'}))
  1341. self.assertFalse(match_str(r'x$="bar"', {'x': 'foo "bar"'}))
  1342. self.assertTrue(match_str(r'x$=" \"bar\""', {'x': 'foo "bar"'}))
  1343. # Escaping &
  1344. self.assertFalse(match_str(r'x=foo & bar', {'x': 'foo & bar'}))
  1345. self.assertTrue(match_str(r'x=foo \& bar', {'x': 'foo & bar'}))
  1346. self.assertTrue(match_str(r'x=foo \& bar & x^=foo', {'x': 'foo & bar'}))
  1347. self.assertTrue(match_str(r'x="foo \& bar" & x^=foo', {'x': 'foo & bar'}))
  1348. # Example from docs
  1349. self.assertTrue(match_str(
  1350. r"!is_live & like_count>?100 & description~='(?i)\bcats \& dogs\b'",
  1351. {'description': 'Raining Cats & Dogs'}))
  1352. # Incomplete
  1353. self.assertFalse(match_str('id!=foo', {'id': 'foo'}, True))
  1354. self.assertTrue(match_str('x', {'id': 'foo'}, True))
  1355. self.assertTrue(match_str('!x', {'id': 'foo'}, True))
  1356. self.assertFalse(match_str('x', {'id': 'foo'}, False))
  1357. def test_parse_dfxp_time_expr(self):
  1358. self.assertEqual(parse_dfxp_time_expr(None), None)
  1359. self.assertEqual(parse_dfxp_time_expr(''), None)
  1360. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  1361. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  1362. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  1363. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  1364. self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
  1365. def test_dfxp2srt(self):
  1366. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  1367. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1368. <body>
  1369. <div xml:lang="en">
  1370. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  1371. <p begin="1" end="2">第二行<br/>♪♪</p>
  1372. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  1373. <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
  1374. <p begin="-1" end="-1">Ignore, two</p>
  1375. <p begin="3" dur="-1">Ignored, three</p>
  1376. </div>
  1377. </body>
  1378. </tt>'''.encode()
  1379. srt_data = '''1
  1380. 00:00:00,000 --> 00:00:01,000
  1381. The following line contains Chinese characters and special symbols
  1382. 2
  1383. 00:00:01,000 --> 00:00:02,000
  1384. 第二行
  1385. ♪♪
  1386. 3
  1387. 00:00:02,000 --> 00:00:03,000
  1388. Third
  1389. Line
  1390. '''
  1391. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  1392. dfxp_data_no_default_namespace = b'''<?xml version="1.0" encoding="UTF-8"?>
  1393. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1394. <body>
  1395. <div xml:lang="en">
  1396. <p begin="0" end="1">The first line</p>
  1397. </div>
  1398. </body>
  1399. </tt>'''
  1400. srt_data = '''1
  1401. 00:00:00,000 --> 00:00:01,000
  1402. The first line
  1403. '''
  1404. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  1405. dfxp_data_with_style = b'''<?xml version="1.0" encoding="utf-8"?>
  1406. <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">
  1407. <head>
  1408. <styling>
  1409. <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
  1410. <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
  1411. <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
  1412. <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
  1413. </styling>
  1414. </head>
  1415. <body tts:textAlign="center" style="s0">
  1416. <div>
  1417. <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
  1418. <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>
  1419. <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
  1420. <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>
  1421. </div>
  1422. </body>
  1423. </tt>'''
  1424. srt_data = '''1
  1425. 00:00:02,080 --> 00:00:05,840
  1426. <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
  1427. 2
  1428. 00:00:02,080 --> 00:00:05,840
  1429. <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
  1430. </font>part 2</font></b>
  1431. 3
  1432. 00:00:05,840 --> 00:00:09,560
  1433. <u><font color="lime">line 3
  1434. part 3</font></u>
  1435. 4
  1436. 00:00:09,560 --> 00:00:12,360
  1437. <i><u><font color="yellow"><font color="lime">inner
  1438. </font>style</font></u></i>
  1439. '''
  1440. self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
  1441. dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
  1442. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  1443. <body>
  1444. <div xml:lang="en">
  1445. <p begin="0" end="1">Line 1</p>
  1446. <p begin="1" end="2">第二行</p>
  1447. </div>
  1448. </body>
  1449. </tt>'''.encode('utf-16')
  1450. srt_data = '''1
  1451. 00:00:00,000 --> 00:00:01,000
  1452. Line 1
  1453. 2
  1454. 00:00:01,000 --> 00:00:02,000
  1455. 第二行
  1456. '''
  1457. self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
  1458. def test_cli_option(self):
  1459. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  1460. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  1461. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  1462. self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
  1463. def test_cli_valueless_option(self):
  1464. self.assertEqual(cli_valueless_option(
  1465. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  1466. self.assertEqual(cli_valueless_option(
  1467. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  1468. self.assertEqual(cli_valueless_option(
  1469. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  1470. self.assertEqual(cli_valueless_option(
  1471. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  1472. self.assertEqual(cli_valueless_option(
  1473. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  1474. self.assertEqual(cli_valueless_option(
  1475. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  1476. def test_cli_bool_option(self):
  1477. self.assertEqual(
  1478. cli_bool_option(
  1479. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  1480. ['--no-check-certificate', 'true'])
  1481. self.assertEqual(
  1482. cli_bool_option(
  1483. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  1484. ['--no-check-certificate=true'])
  1485. self.assertEqual(
  1486. cli_bool_option(
  1487. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1488. ['--check-certificate', 'false'])
  1489. self.assertEqual(
  1490. cli_bool_option(
  1491. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1492. ['--check-certificate=false'])
  1493. self.assertEqual(
  1494. cli_bool_option(
  1495. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  1496. ['--check-certificate', 'true'])
  1497. self.assertEqual(
  1498. cli_bool_option(
  1499. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1500. ['--check-certificate=true'])
  1501. self.assertEqual(
  1502. cli_bool_option(
  1503. {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  1504. [])
  1505. def test_ohdave_rsa_encrypt(self):
  1506. N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
  1507. e = 65537
  1508. self.assertEqual(
  1509. ohdave_rsa_encrypt(b'aa111222', e, N),
  1510. '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
  1511. def test_pkcs1pad(self):
  1512. data = [1, 2, 3]
  1513. padded_data = pkcs1pad(data, 32)
  1514. self.assertEqual(padded_data[:2], [0, 2])
  1515. self.assertEqual(padded_data[28:], [0, 1, 2, 3])
  1516. self.assertRaises(ValueError, pkcs1pad, data, 8)
  1517. def test_encode_base_n(self):
  1518. self.assertEqual(encode_base_n(0, 30), '0')
  1519. self.assertEqual(encode_base_n(80, 30), '2k')
  1520. custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
  1521. self.assertEqual(encode_base_n(0, 30, custom_table), '9')
  1522. self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
  1523. self.assertRaises(ValueError, encode_base_n, 0, 70)
  1524. self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
  1525. def test_caesar(self):
  1526. self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
  1527. self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
  1528. self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
  1529. self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
  1530. self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
  1531. self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
  1532. self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
  1533. self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
  1534. def test_rot47(self):
  1535. self.assertEqual(rot47('yt-dlp'), r'JE\5=A')
  1536. self.assertEqual(rot47('YT-DLP'), r'*%\s{!')
  1537. def test_urshift(self):
  1538. self.assertEqual(urshift(3, 1), 1)
  1539. self.assertEqual(urshift(-3, 1), 2147483646)
  1540. GET_ELEMENT_BY_CLASS_TEST_STRING = '''
  1541. <span class="foo bar">nice</span>
  1542. '''
  1543. def test_get_element_by_class(self):
  1544. html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
  1545. self.assertEqual(get_element_by_class('foo', html), 'nice')
  1546. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1547. def test_get_element_html_by_class(self):
  1548. html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
  1549. self.assertEqual(get_element_html_by_class('foo', html), html.strip())
  1550. self.assertEqual(get_element_by_class('no-such-class', html), None)
  1551. GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING = '''
  1552. <div itemprop="author" itemscope>foo</div>
  1553. '''
  1554. def test_get_element_by_attribute(self):
  1555. html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
  1556. self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
  1557. self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
  1558. self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
  1559. html = self.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
  1560. self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
  1561. def test_get_element_html_by_attribute(self):
  1562. html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
  1563. self.assertEqual(get_element_html_by_attribute('class', 'foo bar', html), html.strip())
  1564. self.assertEqual(get_element_html_by_attribute('class', 'foo', html), None)
  1565. self.assertEqual(get_element_html_by_attribute('class', 'no-such-foo', html), None)
  1566. html = self.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
  1567. self.assertEqual(get_element_html_by_attribute('itemprop', 'author', html), html.strip())
  1568. GET_ELEMENTS_BY_CLASS_TEST_STRING = '''
  1569. <span class="foo bar">nice</span><span class="foo bar">also nice</span>
  1570. '''
  1571. GET_ELEMENTS_BY_CLASS_RES = ['<span class="foo bar">nice</span>', '<span class="foo bar">also nice</span>']
  1572. def test_get_elements_by_class(self):
  1573. html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
  1574. self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
  1575. self.assertEqual(get_elements_by_class('no-such-class', html), [])
  1576. def test_get_elements_html_by_class(self):
  1577. html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
  1578. self.assertEqual(get_elements_html_by_class('foo', html), self.GET_ELEMENTS_BY_CLASS_RES)
  1579. self.assertEqual(get_elements_html_by_class('no-such-class', html), [])
  1580. def test_get_elements_by_attribute(self):
  1581. html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
  1582. self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
  1583. self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
  1584. self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
  1585. def test_get_elements_html_by_attribute(self):
  1586. html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
  1587. self.assertEqual(get_elements_html_by_attribute('class', 'foo bar', html), self.GET_ELEMENTS_BY_CLASS_RES)
  1588. self.assertEqual(get_elements_html_by_attribute('class', 'foo', html), [])
  1589. self.assertEqual(get_elements_html_by_attribute('class', 'no-such-foo', html), [])
  1590. def test_get_elements_text_and_html_by_attribute(self):
  1591. html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
  1592. self.assertEqual(
  1593. list(get_elements_text_and_html_by_attribute('class', 'foo bar', html)),
  1594. list(zip(['nice', 'also nice'], self.GET_ELEMENTS_BY_CLASS_RES)))
  1595. self.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'foo', html)), [])
  1596. self.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'no-such-foo', html)), [])
  1597. self.assertEqual(list(get_elements_text_and_html_by_attribute(
  1598. 'class', 'foo', '<a class="foo">nice</a><span class="foo">nice</span>', tag='a')), [('nice', '<a class="foo">nice</a>')])
  1599. GET_ELEMENT_BY_TAG_TEST_STRING = '''
  1600. random text lorem ipsum</p>
  1601. <div>
  1602. this should be returned
  1603. <span>this should also be returned</span>
  1604. <div>
  1605. this should also be returned
  1606. </div>
  1607. closing tag above should not trick, so this should also be returned
  1608. </div>
  1609. but this text should not be returned
  1610. '''
  1611. GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML = GET_ELEMENT_BY_TAG_TEST_STRING.strip()[32:276]
  1612. GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT = GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML[5:-6]
  1613. GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML = GET_ELEMENT_BY_TAG_TEST_STRING.strip()[78:119]
  1614. GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT = GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML[6:-7]
  1615. def test_get_element_text_and_html_by_tag(self):
  1616. html = self.GET_ELEMENT_BY_TAG_TEST_STRING
  1617. self.assertEqual(
  1618. get_element_text_and_html_by_tag('div', html),
  1619. (self.GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT, self.GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML))
  1620. self.assertEqual(
  1621. get_element_text_and_html_by_tag('span', html),
  1622. (self.GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT, self.GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML))
  1623. self.assertRaises(compat_HTMLParseError, get_element_text_and_html_by_tag, 'article', html)
  1624. def test_iri_to_uri(self):
  1625. self.assertEqual(
  1626. iri_to_uri('https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b'),
  1627. 'https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b') # Same
  1628. self.assertEqual(
  1629. iri_to_uri('https://www.google.com/search?q=Käsesoßenrührlöffel'), # German for cheese sauce stirring spoon
  1630. 'https://www.google.com/search?q=K%C3%A4seso%C3%9Fenr%C3%BChrl%C3%B6ffel')
  1631. self.assertEqual(
  1632. iri_to_uri('https://www.google.com/search?q=lt<+gt>+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#'),
  1633. 'https://www.google.com/search?q=lt%3C+gt%3E+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#')
  1634. self.assertEqual(
  1635. iri_to_uri('http://правозащита38.рф/category/news/'),
  1636. 'http://xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
  1637. self.assertEqual(
  1638. iri_to_uri('http://www.правозащита38.рф/category/news/'),
  1639. 'http://www.xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
  1640. self.assertEqual(
  1641. iri_to_uri('https://i❤.ws/emojidomain/👍👏🤝💪'),
  1642. 'https://xn--i-7iq.ws/emojidomain/%F0%9F%91%8D%F0%9F%91%8F%F0%9F%A4%9D%F0%9F%92%AA')
  1643. self.assertEqual(
  1644. iri_to_uri('http://日本語.jp/'),
  1645. 'http://xn--wgv71a119e.jp/')
  1646. self.assertEqual(
  1647. iri_to_uri('http://导航.中国/'),
  1648. 'http://xn--fet810g.xn--fiqs8s/')
  1649. def test_clean_podcast_url(self):
  1650. 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')
  1651. 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')
  1652. self.assertEqual(clean_podcast_url('https://pdst.fm/e/2.gum.fm/chtbl.com/track/chrt.fm/track/34D33/pscrb.fm/rss/p/traffic.megaphone.fm/ITLLC7765286967.mp3?updated=1687282661'), 'https://traffic.megaphone.fm/ITLLC7765286967.mp3?updated=1687282661')
  1653. self.assertEqual(clean_podcast_url('https://pdst.fm/e/https://mgln.ai/e/441/www.buzzsprout.com/1121972/13019085-ep-252-the-deep-life-stack.mp3'), 'https://www.buzzsprout.com/1121972/13019085-ep-252-the-deep-life-stack.mp3')
  1654. def test_LazyList(self):
  1655. it = list(range(10))
  1656. self.assertEqual(list(LazyList(it)), it)
  1657. self.assertEqual(LazyList(it).exhaust(), it)
  1658. self.assertEqual(LazyList(it)[5], it[5])
  1659. self.assertEqual(LazyList(it)[5:], it[5:])
  1660. self.assertEqual(LazyList(it)[:5], it[:5])
  1661. self.assertEqual(LazyList(it)[::2], it[::2])
  1662. self.assertEqual(LazyList(it)[1::2], it[1::2])
  1663. self.assertEqual(LazyList(it)[5::-1], it[5::-1])
  1664. self.assertEqual(LazyList(it)[6:2:-2], it[6:2:-2])
  1665. self.assertEqual(LazyList(it)[::-1], it[::-1])
  1666. self.assertTrue(LazyList(it))
  1667. self.assertFalse(LazyList(range(0)))
  1668. self.assertEqual(len(LazyList(it)), len(it))
  1669. self.assertEqual(repr(LazyList(it)), repr(it))
  1670. self.assertEqual(str(LazyList(it)), str(it))
  1671. self.assertEqual(list(LazyList(it, reverse=True)), it[::-1])
  1672. self.assertEqual(list(reversed(LazyList(it))[::-1]), it)
  1673. self.assertEqual(list(reversed(LazyList(it))[1:3:7]), it[::-1][1:3:7])
  1674. def test_LazyList_laziness(self):
  1675. def test(ll, idx, val, cache):
  1676. self.assertEqual(ll[idx], val)
  1677. self.assertEqual(ll._cache, list(cache))
  1678. ll = LazyList(range(10))
  1679. test(ll, 0, 0, range(1))
  1680. test(ll, 5, 5, range(6))
  1681. test(ll, -3, 7, range(10))
  1682. ll = LazyList(range(10), reverse=True)
  1683. test(ll, -1, 0, range(1))
  1684. test(ll, 3, 6, range(10))
  1685. ll = LazyList(itertools.count())
  1686. test(ll, 10, 10, range(11))
  1687. ll = reversed(ll)
  1688. test(ll, -15, 14, range(15))
  1689. def test_format_bytes(self):
  1690. self.assertEqual(format_bytes(0), '0.00B')
  1691. self.assertEqual(format_bytes(1000), '1000.00B')
  1692. self.assertEqual(format_bytes(1024), '1.00KiB')
  1693. self.assertEqual(format_bytes(1024**2), '1.00MiB')
  1694. self.assertEqual(format_bytes(1024**3), '1.00GiB')
  1695. self.assertEqual(format_bytes(1024**4), '1.00TiB')
  1696. self.assertEqual(format_bytes(1024**5), '1.00PiB')
  1697. self.assertEqual(format_bytes(1024**6), '1.00EiB')
  1698. self.assertEqual(format_bytes(1024**7), '1.00ZiB')
  1699. self.assertEqual(format_bytes(1024**8), '1.00YiB')
  1700. self.assertEqual(format_bytes(1024**9), '1024.00YiB')
  1701. def test_hide_login_info(self):
  1702. self.assertEqual(Config.hide_login_info(['-u', 'foo', '-p', 'bar']),
  1703. ['-u', 'PRIVATE', '-p', 'PRIVATE'])
  1704. self.assertEqual(Config.hide_login_info(['-u']), ['-u'])
  1705. self.assertEqual(Config.hide_login_info(['-u', 'foo', '-u', 'bar']),
  1706. ['-u', 'PRIVATE', '-u', 'PRIVATE'])
  1707. self.assertEqual(Config.hide_login_info(['--username=foo']),
  1708. ['--username=PRIVATE'])
  1709. def test_locked_file(self):
  1710. TEXT = 'test_locked_file\n'
  1711. FILE = 'test_locked_file.ytdl'
  1712. MODES = 'war' # Order is important
  1713. try:
  1714. for lock_mode in MODES:
  1715. with locked_file(FILE, lock_mode, False) as f:
  1716. if lock_mode == 'r':
  1717. self.assertEqual(f.read(), TEXT * 2, 'Wrong file content')
  1718. else:
  1719. f.write(TEXT)
  1720. for test_mode in MODES:
  1721. testing_write = test_mode != 'r'
  1722. try:
  1723. with locked_file(FILE, test_mode, False):
  1724. pass
  1725. except (BlockingIOError, PermissionError):
  1726. if not testing_write: # FIXME: blocked read access
  1727. print(f'Known issue: Exclusive lock ({lock_mode}) blocks read access ({test_mode})')
  1728. continue
  1729. self.assertTrue(testing_write, f'{test_mode} is blocked by {lock_mode}')
  1730. else:
  1731. self.assertFalse(testing_write, f'{test_mode} is not blocked by {lock_mode}')
  1732. finally:
  1733. with contextlib.suppress(OSError):
  1734. os.remove(FILE)
  1735. def test_determine_file_encoding(self):
  1736. self.assertEqual(determine_file_encoding(b''), (None, 0))
  1737. self.assertEqual(determine_file_encoding(b'--verbose -x --audio-format mkv\n'), (None, 0))
  1738. self.assertEqual(determine_file_encoding(b'\xef\xbb\xbf'), ('utf-8', 3))
  1739. self.assertEqual(determine_file_encoding(b'\x00\x00\xfe\xff'), ('utf-32-be', 4))
  1740. self.assertEqual(determine_file_encoding(b'\xff\xfe'), ('utf-16-le', 2))
  1741. self.assertEqual(determine_file_encoding(b'\xff\xfe# coding: utf-8\n--verbose'), ('utf-16-le', 2))
  1742. self.assertEqual(determine_file_encoding(b'# coding: utf-8\n--verbose'), ('utf-8', 0))
  1743. self.assertEqual(determine_file_encoding(b'# coding: someencodinghere-12345\n--verbose'), ('someencodinghere-12345', 0))
  1744. self.assertEqual(determine_file_encoding(b'#coding:utf-8\n--verbose'), ('utf-8', 0))
  1745. self.assertEqual(determine_file_encoding(b'# coding: utf-8 \r\n--verbose'), ('utf-8', 0))
  1746. self.assertEqual(determine_file_encoding('# coding: utf-32-be'.encode('utf-32-be')), ('utf-32-be', 0))
  1747. self.assertEqual(determine_file_encoding('# coding: utf-16-le'.encode('utf-16-le')), ('utf-16-le', 0))
  1748. def test_get_compatible_ext(self):
  1749. self.assertEqual(get_compatible_ext(
  1750. vcodecs=[None], acodecs=[None, None], vexts=['mp4'], aexts=['m4a', 'm4a']), 'mkv')
  1751. self.assertEqual(get_compatible_ext(
  1752. vcodecs=[None], acodecs=[None], vexts=['flv'], aexts=['flv']), 'flv')
  1753. self.assertEqual(get_compatible_ext(
  1754. vcodecs=[None], acodecs=[None], vexts=['mp4'], aexts=['m4a']), 'mp4')
  1755. self.assertEqual(get_compatible_ext(
  1756. vcodecs=[None], acodecs=[None], vexts=['mp4'], aexts=['webm']), 'mkv')
  1757. self.assertEqual(get_compatible_ext(
  1758. vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['m4a']), 'mkv')
  1759. self.assertEqual(get_compatible_ext(
  1760. vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['webm']), 'webm')
  1761. self.assertEqual(get_compatible_ext(
  1762. vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['weba']), 'webm')
  1763. self.assertEqual(get_compatible_ext(
  1764. vcodecs=['h264'], acodecs=['mp4a'], vexts=['mov'], aexts=['m4a']), 'mp4')
  1765. self.assertEqual(get_compatible_ext(
  1766. vcodecs=['av01.0.12M.08'], acodecs=['opus'], vexts=['mp4'], aexts=['webm']), 'webm')
  1767. self.assertEqual(get_compatible_ext(
  1768. vcodecs=['vp9'], acodecs=['opus'], vexts=['webm'], aexts=['webm'], preferences=['flv', 'mp4']), 'mp4')
  1769. self.assertEqual(get_compatible_ext(
  1770. vcodecs=['av1'], acodecs=['mp4a'], vexts=['webm'], aexts=['m4a'], preferences=('webm', 'mkv')), 'mkv')
  1771. def test_try_call(self):
  1772. def total(*x, **kwargs):
  1773. return sum(x) + sum(kwargs.values())
  1774. self.assertEqual(try_call(None), None,
  1775. msg='not a fn should give None')
  1776. self.assertEqual(try_call(lambda: 1), 1,
  1777. msg='int fn with no expected_type should give int')
  1778. self.assertEqual(try_call(lambda: 1, expected_type=int), 1,
  1779. msg='int fn with expected_type int should give int')
  1780. self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
  1781. msg='int fn with wrong expected_type should give None')
  1782. self.assertEqual(try_call(total, args=(0, 1, 0), expected_type=int), 1,
  1783. msg='fn should accept arglist')
  1784. self.assertEqual(try_call(total, kwargs={'a': 0, 'b': 1, 'c': 0}, expected_type=int), 1,
  1785. msg='fn should accept kwargs')
  1786. self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
  1787. msg='int fn with no expected_type should give None')
  1788. self.assertEqual(try_call(lambda x: {}, total, args=(42, ), expected_type=int), 42,
  1789. msg='expect first int result with expected_type int')
  1790. def test_variadic(self):
  1791. self.assertEqual(variadic(None), (None, ))
  1792. self.assertEqual(variadic('spam'), ('spam', ))
  1793. self.assertEqual(variadic('spam', allowed_types=dict), 'spam')
  1794. with warnings.catch_warnings():
  1795. warnings.simplefilter('ignore')
  1796. self.assertEqual(variadic('spam', allowed_types=[dict]), 'spam')
  1797. def test_http_header_dict(self):
  1798. headers = HTTPHeaderDict()
  1799. headers['ytdl-test'] = b'0'
  1800. self.assertEqual(list(headers.items()), [('Ytdl-Test', '0')])
  1801. headers['ytdl-test'] = 1
  1802. self.assertEqual(list(headers.items()), [('Ytdl-Test', '1')])
  1803. headers['Ytdl-test'] = '2'
  1804. self.assertEqual(list(headers.items()), [('Ytdl-Test', '2')])
  1805. self.assertTrue('ytDl-Test' in headers)
  1806. self.assertEqual(str(headers), str(dict(headers)))
  1807. self.assertEqual(repr(headers), str(dict(headers)))
  1808. headers.update({'X-dlp': 'data'})
  1809. self.assertEqual(set(headers.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data')})
  1810. self.assertEqual(dict(headers), {'Ytdl-Test': '2', 'X-Dlp': 'data'})
  1811. self.assertEqual(len(headers), 2)
  1812. self.assertEqual(headers.copy(), headers)
  1813. headers2 = HTTPHeaderDict({'X-dlp': 'data3'}, **headers, **{'X-dlp': 'data2'})
  1814. self.assertEqual(set(headers2.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data2')})
  1815. self.assertEqual(len(headers2), 2)
  1816. headers2.clear()
  1817. self.assertEqual(len(headers2), 0)
  1818. # ensure we prefer latter headers
  1819. headers3 = HTTPHeaderDict({'Ytdl-TeSt': 1}, {'Ytdl-test': 2})
  1820. self.assertEqual(set(headers3.items()), {('Ytdl-Test', '2')})
  1821. del headers3['ytdl-tesT']
  1822. self.assertEqual(dict(headers3), {})
  1823. headers4 = HTTPHeaderDict({'ytdl-test': 'data;'})
  1824. self.assertEqual(set(headers4.items()), {('Ytdl-Test', 'data;')})
  1825. # common mistake: strip whitespace from values
  1826. # https://github.com/yt-dlp/yt-dlp/issues/8729
  1827. headers5 = HTTPHeaderDict({'ytdl-test': ' data; '})
  1828. self.assertEqual(set(headers5.items()), {('Ytdl-Test', 'data;')})
  1829. def test_extract_basic_auth(self):
  1830. assert extract_basic_auth('http://:foo.bar') == ('http://:foo.bar', None)
  1831. assert extract_basic_auth('http://foo.bar') == ('http://foo.bar', None)
  1832. assert extract_basic_auth('http://@foo.bar') == ('http://foo.bar', 'Basic Og==')
  1833. assert extract_basic_auth('http://:pass@foo.bar') == ('http://foo.bar', 'Basic OnBhc3M=')
  1834. assert extract_basic_auth('http://user:@foo.bar') == ('http://foo.bar', 'Basic dXNlcjo=')
  1835. assert extract_basic_auth('http://user:pass@foo.bar') == ('http://foo.bar', 'Basic dXNlcjpwYXNz')
  1836. @unittest.skipUnless(compat_os_name == 'nt', 'Only relevant on Windows')
  1837. def test_windows_escaping(self):
  1838. tests = [
  1839. 'test"&',
  1840. '%CMDCMDLINE:~-1%&',
  1841. 'a\nb',
  1842. '"',
  1843. '\\',
  1844. '!',
  1845. '^!',
  1846. 'a \\ b',
  1847. 'a \\" b',
  1848. 'a \\ b\\',
  1849. # We replace \r with \n
  1850. ('a\r\ra', 'a\n\na'),
  1851. ]
  1852. def run_shell(args):
  1853. stdout, stderr, error = Popen.run(
  1854. args, text=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1855. assert not stderr
  1856. assert not error
  1857. return stdout
  1858. for argument in tests:
  1859. if isinstance(argument, str):
  1860. expected = argument
  1861. else:
  1862. argument, expected = argument
  1863. args = [sys.executable, '-c', 'import sys; print(end=sys.argv[1])', argument, 'end']
  1864. assert run_shell(args) == expected
  1865. assert run_shell(shell_quote(args, shell=True)) == expected
  1866. if __name__ == '__main__':
  1867. unittest.main()