test_utils.py 99 KB

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