test_utils.py 95 KB

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