test_utils.py 99 KB

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