test_utils.py 98 KB

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