test_utils.py 77 KB

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