test_utils.py 84 KB

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