test_YoutubeDL.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import unittest
  6. from unittest.mock import patch
  7. from yt_dlp.globals import all_plugins_loaded
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. import contextlib
  10. import copy
  11. import json
  12. from test.helper import FakeYDL, assertRegexpMatches, try_rm
  13. from yt_dlp import YoutubeDL
  14. from yt_dlp.extractor import YoutubeIE
  15. from yt_dlp.extractor.common import InfoExtractor
  16. from yt_dlp.postprocessor.common import PostProcessor
  17. from yt_dlp.utils import (
  18. ExtractorError,
  19. LazyList,
  20. OnDemandPagedList,
  21. int_or_none,
  22. match_filter_func,
  23. )
  24. from yt_dlp.utils.traversal import traverse_obj
  25. TEST_URL = 'http://localhost/sample.mp4'
  26. class YDL(FakeYDL):
  27. def __init__(self, *args, **kwargs):
  28. super().__init__(*args, **kwargs)
  29. self.downloaded_info_dicts = []
  30. self.msgs = []
  31. def process_info(self, info_dict):
  32. self.downloaded_info_dicts.append(info_dict.copy())
  33. def to_screen(self, msg, *args, **kwargs):
  34. self.msgs.append(msg)
  35. def dl(self, *args, **kwargs):
  36. assert False, 'Downloader must not be invoked for test_YoutubeDL'
  37. def _make_result(formats, **kwargs):
  38. res = {
  39. 'formats': formats,
  40. 'id': 'testid',
  41. 'title': 'testttitle',
  42. 'extractor': 'testex',
  43. 'extractor_key': 'TestEx',
  44. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  45. }
  46. res.update(**kwargs)
  47. return res
  48. class TestFormatSelection(unittest.TestCase):
  49. def test_prefer_free_formats(self):
  50. # Same resolution => download webm
  51. ydl = YDL()
  52. ydl.params['prefer_free_formats'] = True
  53. formats = [
  54. {'ext': 'webm', 'height': 460, 'url': TEST_URL},
  55. {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
  56. ]
  57. info_dict = _make_result(formats)
  58. ydl.sort_formats(info_dict)
  59. ydl.process_ie_result(info_dict)
  60. downloaded = ydl.downloaded_info_dicts[0]
  61. self.assertEqual(downloaded['ext'], 'webm')
  62. # Different resolution => download best quality (mp4)
  63. ydl = YDL()
  64. ydl.params['prefer_free_formats'] = True
  65. formats = [
  66. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  67. {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
  68. ]
  69. info_dict['formats'] = formats
  70. ydl.sort_formats(info_dict)
  71. ydl.process_ie_result(info_dict)
  72. downloaded = ydl.downloaded_info_dicts[0]
  73. self.assertEqual(downloaded['ext'], 'mp4')
  74. # No prefer_free_formats => prefer mp4 and webm
  75. ydl = YDL()
  76. ydl.params['prefer_free_formats'] = False
  77. formats = [
  78. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  79. {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
  80. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  81. ]
  82. info_dict['formats'] = formats
  83. ydl.sort_formats(info_dict)
  84. ydl.process_ie_result(info_dict)
  85. downloaded = ydl.downloaded_info_dicts[0]
  86. self.assertEqual(downloaded['ext'], 'mp4')
  87. ydl = YDL()
  88. ydl.params['prefer_free_formats'] = False
  89. formats = [
  90. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  91. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  92. ]
  93. info_dict['formats'] = formats
  94. ydl.sort_formats(info_dict)
  95. ydl.process_ie_result(info_dict)
  96. downloaded = ydl.downloaded_info_dicts[0]
  97. self.assertEqual(downloaded['ext'], 'webm')
  98. def test_format_selection(self):
  99. formats = [
  100. {'format_id': '35', 'ext': 'mp4', 'preference': 0, 'url': TEST_URL},
  101. {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
  102. {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
  103. {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
  104. {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
  105. ]
  106. info_dict = _make_result(formats)
  107. def test(inp, *expected, multi=False):
  108. ydl = YDL({
  109. 'format': inp,
  110. 'allow_multiple_video_streams': multi,
  111. 'allow_multiple_audio_streams': multi,
  112. })
  113. ydl.process_ie_result(info_dict.copy())
  114. downloaded = [x['format_id'] for x in ydl.downloaded_info_dicts]
  115. self.assertEqual(downloaded, list(expected))
  116. test('20/47', '47')
  117. test('20/71/worst', '35')
  118. test(None, '2')
  119. test('webm/mp4', '47')
  120. test('3gp/40/mp4', '35')
  121. test('example-with-dashes', 'example-with-dashes')
  122. test('all', '2', '47', '45', 'example-with-dashes', '35')
  123. test('mergeall', '2+47+45+example-with-dashes+35', multi=True)
  124. # See: https://github.com/yt-dlp/yt-dlp/pulls/8797
  125. test('7_a/worst', '35')
  126. def test_format_selection_audio(self):
  127. formats = [
  128. {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  129. {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  130. {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
  131. {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
  132. ]
  133. info_dict = _make_result(formats)
  134. ydl = YDL({'format': 'bestaudio'})
  135. ydl.process_ie_result(info_dict.copy())
  136. downloaded = ydl.downloaded_info_dicts[0]
  137. self.assertEqual(downloaded['format_id'], 'audio-high')
  138. ydl = YDL({'format': 'worstaudio'})
  139. ydl.process_ie_result(info_dict.copy())
  140. downloaded = ydl.downloaded_info_dicts[0]
  141. self.assertEqual(downloaded['format_id'], 'audio-low')
  142. formats = [
  143. {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  144. {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
  145. ]
  146. info_dict = _make_result(formats)
  147. ydl = YDL({'format': 'bestaudio/worstaudio/best'})
  148. ydl.process_ie_result(info_dict.copy())
  149. downloaded = ydl.downloaded_info_dicts[0]
  150. self.assertEqual(downloaded['format_id'], 'vid-high')
  151. def test_format_selection_audio_exts(self):
  152. formats = [
  153. {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  154. {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  155. {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  156. {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  157. {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  158. ]
  159. info_dict = _make_result(formats)
  160. ydl = YDL({'format': 'best', 'format_sort': ['abr', 'ext']})
  161. ydl.sort_formats(info_dict)
  162. ydl.process_ie_result(copy.deepcopy(info_dict))
  163. downloaded = ydl.downloaded_info_dicts[0]
  164. self.assertEqual(downloaded['format_id'], 'aac-64')
  165. ydl = YDL({'format': 'mp3'})
  166. ydl.sort_formats(info_dict)
  167. ydl.process_ie_result(copy.deepcopy(info_dict))
  168. downloaded = ydl.downloaded_info_dicts[0]
  169. self.assertEqual(downloaded['format_id'], 'mp3-64')
  170. ydl = YDL({'prefer_free_formats': True, 'format_sort': ['abr', 'ext']})
  171. ydl.sort_formats(info_dict)
  172. ydl.process_ie_result(copy.deepcopy(info_dict))
  173. downloaded = ydl.downloaded_info_dicts[0]
  174. self.assertEqual(downloaded['format_id'], 'ogg-64')
  175. def test_format_selection_video(self):
  176. formats = [
  177. {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
  178. {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
  179. {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
  180. ]
  181. info_dict = _make_result(formats)
  182. ydl = YDL({'format': 'bestvideo'})
  183. ydl.process_ie_result(info_dict.copy())
  184. downloaded = ydl.downloaded_info_dicts[0]
  185. self.assertEqual(downloaded['format_id'], 'dash-video-high')
  186. ydl = YDL({'format': 'worstvideo'})
  187. ydl.process_ie_result(info_dict.copy())
  188. downloaded = ydl.downloaded_info_dicts[0]
  189. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  190. ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
  191. ydl.process_ie_result(info_dict.copy())
  192. downloaded = ydl.downloaded_info_dicts[0]
  193. self.assertEqual(downloaded['format_id'], 'dash-video-low')
  194. formats = [
  195. {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
  196. ]
  197. info_dict = _make_result(formats)
  198. ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
  199. ydl.process_ie_result(info_dict.copy())
  200. downloaded = ydl.downloaded_info_dicts[0]
  201. self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
  202. def test_format_selection_by_vcodec_sort(self):
  203. formats = [
  204. {'format_id': 'av1-format', 'ext': 'mp4', 'vcodec': 'av1', 'acodec': 'none', 'url': TEST_URL},
  205. {'format_id': 'vp9-hdr-format', 'ext': 'mp4', 'vcodec': 'vp09.02.50.10.01.09.18.09.00', 'acodec': 'none', 'url': TEST_URL},
  206. {'format_id': 'vp9-sdr-format', 'ext': 'mp4', 'vcodec': 'vp09.00.50.08', 'acodec': 'none', 'url': TEST_URL},
  207. {'format_id': 'h265-format', 'ext': 'mp4', 'vcodec': 'h265', 'acodec': 'none', 'url': TEST_URL},
  208. ]
  209. info_dict = _make_result(formats)
  210. ydl = YDL({'format': 'bestvideo', 'format_sort': ['vcodec:vp9.2']})
  211. ydl.process_ie_result(info_dict.copy())
  212. downloaded = ydl.downloaded_info_dicts[0]
  213. self.assertEqual(downloaded['format_id'], 'vp9-hdr-format')
  214. ydl = YDL({'format': 'bestvideo', 'format_sort': ['vcodec:vp9']})
  215. ydl.process_ie_result(info_dict.copy())
  216. downloaded = ydl.downloaded_info_dicts[0]
  217. self.assertEqual(downloaded['format_id'], 'vp9-sdr-format')
  218. ydl = YDL({'format': 'bestvideo', 'format_sort': ['+vcodec:vp9.2']})
  219. ydl.process_ie_result(info_dict.copy())
  220. downloaded = ydl.downloaded_info_dicts[0]
  221. self.assertEqual(downloaded['format_id'], 'vp9-hdr-format')
  222. ydl = YDL({'format': 'bestvideo', 'format_sort': ['+vcodec:vp9']})
  223. ydl.process_ie_result(info_dict.copy())
  224. downloaded = ydl.downloaded_info_dicts[0]
  225. self.assertEqual(downloaded['format_id'], 'vp9-sdr-format')
  226. def test_format_selection_string_ops(self):
  227. formats = [
  228. {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
  229. {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
  230. ]
  231. info_dict = _make_result(formats)
  232. # equals (=)
  233. ydl = YDL({'format': '[format_id=abc-cba]'})
  234. ydl.process_ie_result(info_dict.copy())
  235. downloaded = ydl.downloaded_info_dicts[0]
  236. self.assertEqual(downloaded['format_id'], 'abc-cba')
  237. # does not equal (!=)
  238. ydl = YDL({'format': '[format_id!=abc-cba]'})
  239. ydl.process_ie_result(info_dict.copy())
  240. downloaded = ydl.downloaded_info_dicts[0]
  241. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  242. ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
  243. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  244. # starts with (^=)
  245. ydl = YDL({'format': '[format_id^=abc]'})
  246. ydl.process_ie_result(info_dict.copy())
  247. downloaded = ydl.downloaded_info_dicts[0]
  248. self.assertEqual(downloaded['format_id'], 'abc-cba')
  249. # does not start with (!^=)
  250. ydl = YDL({'format': '[format_id!^=abc]'})
  251. ydl.process_ie_result(info_dict.copy())
  252. downloaded = ydl.downloaded_info_dicts[0]
  253. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  254. ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
  255. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  256. # ends with ($=)
  257. ydl = YDL({'format': '[format_id$=cba]'})
  258. ydl.process_ie_result(info_dict.copy())
  259. downloaded = ydl.downloaded_info_dicts[0]
  260. self.assertEqual(downloaded['format_id'], 'abc-cba')
  261. # does not end with (!$=)
  262. ydl = YDL({'format': '[format_id!$=cba]'})
  263. ydl.process_ie_result(info_dict.copy())
  264. downloaded = ydl.downloaded_info_dicts[0]
  265. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  266. ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
  267. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  268. # contains (*=)
  269. ydl = YDL({'format': '[format_id*=bc-cb]'})
  270. ydl.process_ie_result(info_dict.copy())
  271. downloaded = ydl.downloaded_info_dicts[0]
  272. self.assertEqual(downloaded['format_id'], 'abc-cba')
  273. # does not contain (!*=)
  274. ydl = YDL({'format': '[format_id!*=bc-cb]'})
  275. ydl.process_ie_result(info_dict.copy())
  276. downloaded = ydl.downloaded_info_dicts[0]
  277. self.assertEqual(downloaded['format_id'], 'zxc-cxz')
  278. ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
  279. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  280. ydl = YDL({'format': '[format_id!*=-]'})
  281. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  282. def test_youtube_format_selection(self):
  283. # FIXME: Rewrite in accordance with the new format sorting options
  284. return
  285. order = [
  286. '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
  287. # Apple HTTP Live Streaming
  288. '96', '95', '94', '93', '92', '132', '151',
  289. # 3D
  290. '85', '84', '102', '83', '101', '82', '100',
  291. # Dash video
  292. '137', '248', '136', '247', '135', '246',
  293. '245', '244', '134', '243', '133', '242', '160',
  294. # Dash audio
  295. '141', '172', '140', '171', '139',
  296. ]
  297. def format_info(f_id):
  298. info = YoutubeIE._formats[f_id].copy()
  299. # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
  300. # and 'vcodec', while in tests such information is incomplete since
  301. # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
  302. # test_YoutubeDL.test_youtube_format_selection is broken without
  303. # this fix
  304. if 'acodec' in info and 'vcodec' not in info:
  305. info['vcodec'] = 'none'
  306. elif 'vcodec' in info and 'acodec' not in info:
  307. info['acodec'] = 'none'
  308. info['format_id'] = f_id
  309. info['url'] = 'url:' + f_id
  310. return info
  311. formats_order = [format_info(f_id) for f_id in order]
  312. info_dict = _make_result(list(formats_order), extractor='youtube')
  313. ydl = YDL({'format': 'bestvideo+bestaudio'})
  314. ydl.sort_formats(info_dict)
  315. ydl.process_ie_result(info_dict)
  316. downloaded = ydl.downloaded_info_dicts[0]
  317. self.assertEqual(downloaded['format_id'], '248+172')
  318. self.assertEqual(downloaded['ext'], 'mp4')
  319. info_dict = _make_result(list(formats_order), extractor='youtube')
  320. ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
  321. ydl.sort_formats(info_dict)
  322. ydl.process_ie_result(info_dict)
  323. downloaded = ydl.downloaded_info_dicts[0]
  324. self.assertEqual(downloaded['format_id'], '38')
  325. info_dict = _make_result(list(formats_order), extractor='youtube')
  326. ydl = YDL({'format': 'bestvideo/best,bestaudio'})
  327. ydl.sort_formats(info_dict)
  328. ydl.process_ie_result(info_dict)
  329. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  330. self.assertEqual(downloaded_ids, ['137', '141'])
  331. info_dict = _make_result(list(formats_order), extractor='youtube')
  332. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
  333. ydl.sort_formats(info_dict)
  334. ydl.process_ie_result(info_dict)
  335. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  336. self.assertEqual(downloaded_ids, ['137+141', '248+141'])
  337. info_dict = _make_result(list(formats_order), extractor='youtube')
  338. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
  339. ydl.sort_formats(info_dict)
  340. ydl.process_ie_result(info_dict)
  341. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  342. self.assertEqual(downloaded_ids, ['136+141', '247+141'])
  343. info_dict = _make_result(list(formats_order), extractor='youtube')
  344. ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
  345. ydl.sort_formats(info_dict)
  346. ydl.process_ie_result(info_dict)
  347. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  348. self.assertEqual(downloaded_ids, ['248+141'])
  349. for f1, f2 in zip(formats_order, formats_order[1:]):
  350. info_dict = _make_result([f1, f2], extractor='youtube')
  351. ydl = YDL({'format': 'best/bestvideo'})
  352. ydl.sort_formats(info_dict)
  353. ydl.process_ie_result(info_dict)
  354. downloaded = ydl.downloaded_info_dicts[0]
  355. self.assertEqual(downloaded['format_id'], f1['format_id'])
  356. info_dict = _make_result([f2, f1], extractor='youtube')
  357. ydl = YDL({'format': 'best/bestvideo'})
  358. ydl.sort_formats(info_dict)
  359. ydl.process_ie_result(info_dict)
  360. downloaded = ydl.downloaded_info_dicts[0]
  361. self.assertEqual(downloaded['format_id'], f1['format_id'])
  362. def test_audio_only_extractor_format_selection(self):
  363. # For extractors with incomplete formats (all formats are audio-only or
  364. # video-only) best and worst should fallback to corresponding best/worst
  365. # video-only or audio-only formats (as per
  366. # https://github.com/ytdl-org/youtube-dl/pull/5556)
  367. formats = [
  368. {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  369. {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  370. ]
  371. info_dict = _make_result(formats)
  372. ydl = YDL({'format': 'best'})
  373. ydl.process_ie_result(info_dict.copy())
  374. downloaded = ydl.downloaded_info_dicts[0]
  375. self.assertEqual(downloaded['format_id'], 'high')
  376. ydl = YDL({'format': 'worst'})
  377. ydl.process_ie_result(info_dict.copy())
  378. downloaded = ydl.downloaded_info_dicts[0]
  379. self.assertEqual(downloaded['format_id'], 'low')
  380. def test_format_not_available(self):
  381. formats = [
  382. {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
  383. {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  384. ]
  385. info_dict = _make_result(formats)
  386. # This must fail since complete video-audio format does not match filter
  387. # and extractor does not provide incomplete only formats (i.e. only
  388. # video-only or audio-only).
  389. ydl = YDL({'format': 'best[height>360]'})
  390. self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
  391. def test_format_selection_issue_10083(self):
  392. # See https://github.com/ytdl-org/youtube-dl/issues/10083
  393. formats = [
  394. {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
  395. {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
  396. {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
  397. ]
  398. info_dict = _make_result(formats)
  399. ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
  400. ydl.process_ie_result(info_dict.copy())
  401. self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
  402. def test_invalid_format_specs(self):
  403. def assert_syntax_error(format_spec):
  404. self.assertRaises(SyntaxError, YDL, {'format': format_spec})
  405. assert_syntax_error('bestvideo,,best')
  406. assert_syntax_error('+bestaudio')
  407. assert_syntax_error('bestvideo+')
  408. assert_syntax_error('/')
  409. assert_syntax_error('[720<height]')
  410. def test_format_filtering(self):
  411. formats = [
  412. {'format_id': 'A', 'filesize': 500, 'width': 1000, 'aspect_ratio': 1.0},
  413. {'format_id': 'B', 'filesize': 1000, 'width': 500, 'aspect_ratio': 1.33},
  414. {'format_id': 'C', 'filesize': 1000, 'width': 400, 'aspect_ratio': 1.5},
  415. {'format_id': 'D', 'filesize': 2000, 'width': 600, 'aspect_ratio': 1.78},
  416. {'format_id': 'E', 'filesize': 3000, 'aspect_ratio': 0.56},
  417. {'format_id': 'F'},
  418. {'format_id': 'G', 'filesize': 1000000},
  419. ]
  420. for f in formats:
  421. f['url'] = 'http://_/'
  422. f['ext'] = 'unknown'
  423. info_dict = _make_result(formats, _format_sort_fields=('id', ))
  424. ydl = YDL({'format': 'best[filesize<3000]'})
  425. ydl.process_ie_result(info_dict)
  426. downloaded = ydl.downloaded_info_dicts[0]
  427. self.assertEqual(downloaded['format_id'], 'D')
  428. ydl = YDL({'format': 'best[filesize<=3000]'})
  429. ydl.process_ie_result(info_dict)
  430. downloaded = ydl.downloaded_info_dicts[0]
  431. self.assertEqual(downloaded['format_id'], 'E')
  432. ydl = YDL({'format': 'best[filesize <= ? 3000]'})
  433. ydl.process_ie_result(info_dict)
  434. downloaded = ydl.downloaded_info_dicts[0]
  435. self.assertEqual(downloaded['format_id'], 'F')
  436. ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
  437. ydl.process_ie_result(info_dict)
  438. downloaded = ydl.downloaded_info_dicts[0]
  439. self.assertEqual(downloaded['format_id'], 'B')
  440. ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
  441. ydl.process_ie_result(info_dict)
  442. downloaded = ydl.downloaded_info_dicts[0]
  443. self.assertEqual(downloaded['format_id'], 'C')
  444. ydl = YDL({'format': '[filesize>?1]'})
  445. ydl.process_ie_result(info_dict)
  446. downloaded = ydl.downloaded_info_dicts[0]
  447. self.assertEqual(downloaded['format_id'], 'G')
  448. ydl = YDL({'format': '[filesize<1M]'})
  449. ydl.process_ie_result(info_dict)
  450. downloaded = ydl.downloaded_info_dicts[0]
  451. self.assertEqual(downloaded['format_id'], 'E')
  452. ydl = YDL({'format': '[filesize<1MiB]'})
  453. ydl.process_ie_result(info_dict)
  454. downloaded = ydl.downloaded_info_dicts[0]
  455. self.assertEqual(downloaded['format_id'], 'G')
  456. ydl = YDL({'format': 'all[width>=400][width<=600]'})
  457. ydl.process_ie_result(info_dict)
  458. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  459. self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
  460. ydl = YDL({'format': 'best[height<40]'})
  461. with contextlib.suppress(ExtractorError):
  462. ydl.process_ie_result(info_dict)
  463. self.assertEqual(ydl.downloaded_info_dicts, [])
  464. ydl = YDL({'format': 'best[aspect_ratio=1]'})
  465. ydl.process_ie_result(info_dict)
  466. downloaded = ydl.downloaded_info_dicts[0]
  467. self.assertEqual(downloaded['format_id'], 'A')
  468. ydl = YDL({'format': 'all[aspect_ratio > 1.00]'})
  469. ydl.process_ie_result(info_dict)
  470. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  471. self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
  472. ydl = YDL({'format': 'all[aspect_ratio < 1.00]'})
  473. ydl.process_ie_result(info_dict)
  474. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  475. self.assertEqual(downloaded_ids, ['E'])
  476. ydl = YDL({'format': 'best[aspect_ratio=1.5]'})
  477. ydl.process_ie_result(info_dict)
  478. downloaded = ydl.downloaded_info_dicts[0]
  479. self.assertEqual(downloaded['format_id'], 'C')
  480. ydl = YDL({'format': 'all[aspect_ratio!=1]'})
  481. ydl.process_ie_result(info_dict)
  482. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  483. self.assertEqual(downloaded_ids, ['E', 'D', 'C', 'B'])
  484. @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.available', False)
  485. def test_default_format_spec_without_ffmpeg(self):
  486. ydl = YDL({})
  487. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  488. ydl = YDL({'simulate': True})
  489. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  490. ydl = YDL({})
  491. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  492. ydl = YDL({'simulate': True})
  493. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  494. ydl = YDL({'outtmpl': '-'})
  495. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  496. ydl = YDL({})
  497. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  498. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  499. @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.available', True)
  500. @patch('yt_dlp.postprocessor.ffmpeg.FFmpegMergerPP.can_merge', lambda _: True)
  501. def test_default_format_spec_with_ffmpeg(self):
  502. ydl = YDL({})
  503. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  504. ydl = YDL({'simulate': True})
  505. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  506. ydl = YDL({})
  507. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  508. ydl = YDL({'simulate': True})
  509. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  510. ydl = YDL({'outtmpl': '-'})
  511. self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
  512. ydl = YDL({})
  513. self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
  514. self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
  515. class TestYoutubeDL(unittest.TestCase):
  516. def test_subtitles(self):
  517. def s_formats(lang, autocaption=False):
  518. return [{
  519. 'ext': ext,
  520. 'url': f'http://localhost/video.{lang}.{ext}',
  521. '_auto': autocaption,
  522. } for ext in ['vtt', 'srt', 'ass']]
  523. subtitles = {l: s_formats(l) for l in ['en', 'fr', 'es']}
  524. auto_captions = {l: s_formats(l, True) for l in ['it', 'pt', 'es']}
  525. info_dict = {
  526. 'id': 'test',
  527. 'title': 'Test',
  528. 'url': 'http://localhost/video.mp4',
  529. 'subtitles': subtitles,
  530. 'automatic_captions': auto_captions,
  531. 'extractor': 'TEST',
  532. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  533. }
  534. def get_info(params={}):
  535. params.setdefault('simulate', True)
  536. ydl = YDL(params)
  537. ydl.report_warning = lambda *args, **kargs: None
  538. return ydl.process_video_result(info_dict, download=False)
  539. result = get_info()
  540. self.assertFalse(result.get('requested_subtitles'))
  541. self.assertEqual(result['subtitles'], subtitles)
  542. self.assertEqual(result['automatic_captions'], auto_captions)
  543. result = get_info({'writesubtitles': True})
  544. subs = result['requested_subtitles']
  545. self.assertTrue(subs)
  546. self.assertEqual(set(subs.keys()), {'en'})
  547. self.assertTrue(subs['en'].get('data') is None)
  548. self.assertEqual(subs['en']['ext'], 'ass')
  549. result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
  550. subs = result['requested_subtitles']
  551. self.assertEqual(subs['en']['ext'], 'srt')
  552. result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
  553. subs = result['requested_subtitles']
  554. self.assertTrue(subs)
  555. self.assertEqual(set(subs.keys()), {'es', 'fr'})
  556. result = get_info({'writesubtitles': True, 'subtitleslangs': ['all', '-en']})
  557. subs = result['requested_subtitles']
  558. self.assertTrue(subs)
  559. self.assertEqual(set(subs.keys()), {'es', 'fr'})
  560. result = get_info({'writesubtitles': True, 'subtitleslangs': ['en', 'fr', '-en']})
  561. subs = result['requested_subtitles']
  562. self.assertTrue(subs)
  563. self.assertEqual(set(subs.keys()), {'fr'})
  564. result = get_info({'writesubtitles': True, 'subtitleslangs': ['-en', 'en']})
  565. subs = result['requested_subtitles']
  566. self.assertTrue(subs)
  567. self.assertEqual(set(subs.keys()), {'en'})
  568. result = get_info({'writesubtitles': True, 'subtitleslangs': ['e.+']})
  569. subs = result['requested_subtitles']
  570. self.assertTrue(subs)
  571. self.assertEqual(set(subs.keys()), {'es', 'en'})
  572. result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  573. subs = result['requested_subtitles']
  574. self.assertTrue(subs)
  575. self.assertEqual(set(subs.keys()), {'es', 'pt'})
  576. self.assertFalse(subs['es']['_auto'])
  577. self.assertTrue(subs['pt']['_auto'])
  578. result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  579. subs = result['requested_subtitles']
  580. self.assertTrue(subs)
  581. self.assertEqual(set(subs.keys()), {'es', 'pt'})
  582. self.assertTrue(subs['es']['_auto'])
  583. self.assertTrue(subs['pt']['_auto'])
  584. def test_add_extra_info(self):
  585. test_dict = {
  586. 'extractor': 'Foo',
  587. }
  588. extra_info = {
  589. 'extractor': 'Bar',
  590. 'playlist': 'funny videos',
  591. }
  592. YDL.add_extra_info(test_dict, extra_info)
  593. self.assertEqual(test_dict['extractor'], 'Foo')
  594. self.assertEqual(test_dict['playlist'], 'funny videos')
  595. outtmpl_info = {
  596. 'id': '1234',
  597. 'ext': 'mp4',
  598. 'width': None,
  599. 'height': 1080,
  600. 'filesize': 1024,
  601. 'title1': '$PATH',
  602. 'title2': '%PATH%',
  603. 'title3': 'foo/bar\\test',
  604. 'title4': 'foo "bar" test',
  605. 'title5': 'áéí 𝐀',
  606. 'timestamp': 1618488000,
  607. 'duration': 100000,
  608. 'playlist_index': 1,
  609. 'playlist_autonumber': 2,
  610. '__last_playlist_index': 100,
  611. 'n_entries': 10,
  612. 'formats': [
  613. {'id': 'id 1', 'height': 1080, 'width': 1920},
  614. {'id': 'id 2', 'height': 720},
  615. {'id': 'id 3'},
  616. ],
  617. }
  618. def test_prepare_outtmpl_and_filename(self):
  619. def test(tmpl, expected, *, info=None, **params):
  620. params['outtmpl'] = tmpl
  621. ydl = FakeYDL(params)
  622. ydl._num_downloads = 1
  623. self.assertEqual(ydl.validate_outtmpl(tmpl), None)
  624. out = ydl.evaluate_outtmpl(tmpl, info or self.outtmpl_info)
  625. fname = ydl.prepare_filename(info or self.outtmpl_info)
  626. if not isinstance(expected, (list, tuple)):
  627. expected = (expected, expected)
  628. for (name, got), expect in zip((('outtmpl', out), ('filename', fname)), expected):
  629. if callable(expect):
  630. self.assertTrue(expect(got), f'Wrong {name} from {tmpl}')
  631. elif expect is not None:
  632. self.assertEqual(got, expect, f'Wrong {name} from {tmpl}')
  633. # Side-effects
  634. original_infodict = dict(self.outtmpl_info)
  635. test('foo.bar', 'foo.bar')
  636. original_infodict['epoch'] = self.outtmpl_info.get('epoch')
  637. self.assertTrue(isinstance(original_infodict['epoch'], int))
  638. test('%(epoch)d', int_or_none)
  639. self.assertEqual(original_infodict, self.outtmpl_info)
  640. # Auto-generated fields
  641. test('%(id)s.%(ext)s', '1234.mp4')
  642. test('%(duration_string)s', ('27:46:40', '27-46-40'))
  643. test('%(resolution)s', '1080p')
  644. test('%(playlist_index|)s', '001')
  645. test('%(playlist_index&{}!)s', '1!')
  646. test('%(playlist_autonumber)s', '02')
  647. test('%(autonumber)s', '00001')
  648. test('%(autonumber+2)03d', '005', autonumber_start=3)
  649. test('%(autonumber)s', '001', autonumber_size=3)
  650. # Escaping %
  651. test('%', '%')
  652. test('%%', '%')
  653. test('%%%%', '%%')
  654. test('%s', '%s')
  655. test('%%%s', '%%s')
  656. test('%d', '%d')
  657. test('%abc%', '%abc%')
  658. test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
  659. test('%%%(height)s', '%1080')
  660. test('%(width)06d.%(ext)s', 'NA.mp4')
  661. test('%(width)06d.%%(ext)s', 'NA.%(ext)s')
  662. test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
  663. # Sanitization options
  664. test('%(title3)s', (None, 'foo⧸bar⧹test'))
  665. test('%(title5)s', (None, 'aei_A'), restrictfilenames=True)
  666. test('%(title3)s', (None, 'foo_bar_test'), windowsfilenames=False, restrictfilenames=True)
  667. if sys.platform != 'win32':
  668. test('%(title3)s', (None, 'foo⧸bar\\test'), windowsfilenames=False)
  669. # ID sanitization
  670. test('%(id)s', '_abcd', info={'id': '_abcd'})
  671. test('%(some_id)s', '_abcd', info={'some_id': '_abcd'})
  672. test('%(formats.0.id)s', '_abcd', info={'formats': [{'id': '_abcd'}]})
  673. test('%(id)s', '-abcd', info={'id': '-abcd'})
  674. test('%(id)s', '.abcd', info={'id': '.abcd'})
  675. test('%(id)s', 'ab__cd', info={'id': 'ab__cd'})
  676. test('%(id)s', ('ab:cd', 'ab:cd'), info={'id': 'ab:cd'})
  677. test('%(id.0)s', '-', info={'id': '--'})
  678. # Invalid templates
  679. self.assertTrue(isinstance(YoutubeDL.validate_outtmpl('%(title)'), ValueError))
  680. test('%(invalid@tmpl|def)s', 'none', outtmpl_na_placeholder='none')
  681. test('%(..)s', 'NA')
  682. test('%(formats.{id)s', 'NA')
  683. # Entire info_dict
  684. def expect_same_infodict(out):
  685. got_dict = json.loads(out)
  686. for info_field, expected in self.outtmpl_info.items():
  687. self.assertEqual(got_dict.get(info_field), expected, info_field)
  688. return True
  689. test('%()j', (expect_same_infodict, None))
  690. # NA placeholder
  691. NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(x|def)s-%(id)s.%(ext)s'
  692. test(NA_TEST_OUTTMPL, 'NA-NA-def-1234.mp4')
  693. test(NA_TEST_OUTTMPL, 'none-none-def-1234.mp4', outtmpl_na_placeholder='none')
  694. test(NA_TEST_OUTTMPL, '--def-1234.mp4', outtmpl_na_placeholder='')
  695. test('%(non_existent.0)s', 'NA')
  696. # String formatting
  697. FMT_TEST_OUTTMPL = '%%(height)%s.%%(ext)s'
  698. test(FMT_TEST_OUTTMPL % 's', '1080.mp4')
  699. test(FMT_TEST_OUTTMPL % 'd', '1080.mp4')
  700. test(FMT_TEST_OUTTMPL % '6d', ' 1080.mp4')
  701. test(FMT_TEST_OUTTMPL % '-6d', '1080 .mp4')
  702. test(FMT_TEST_OUTTMPL % '06d', '001080.mp4')
  703. test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
  704. test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
  705. test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
  706. test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
  707. test(FMT_TEST_OUTTMPL % ' 0 6d', ' 01080.mp4')
  708. # Type casting
  709. test('%(id)d', '1234')
  710. test('%(height)c', '1')
  711. test('%(ext)c', 'm')
  712. test('%(id)d %(id)r', "1234 '1234'")
  713. test('%(id)r %(height)r', "'1234' 1080")
  714. test('%(title5)a %(height)a', (R"'\xe1\xe9\xed \U0001d400' 1080", None))
  715. test('%(ext)s-%(ext|def)d', 'mp4-def')
  716. test('%(width|0)04d', '0')
  717. test('a%(width|b)d', 'ab', outtmpl_na_placeholder='none')
  718. FORMATS = self.outtmpl_info['formats']
  719. # Custom type casting
  720. test('%(formats.:.id)l', 'id 1, id 2, id 3')
  721. test('%(formats.:.id)#l', ('id 1\nid 2\nid 3', 'id 1 id 2 id 3'))
  722. test('%(ext)l', 'mp4')
  723. test('%(formats.:.id) 18l', ' id 1, id 2, id 3')
  724. test('%(formats)j', (json.dumps(FORMATS), None))
  725. test('%(formats)#j', (
  726. json.dumps(FORMATS, indent=4),
  727. json.dumps(FORMATS, indent=4).replace(':', ':').replace('"', '"').replace('\n', ' '),
  728. ))
  729. test('%(title5).3B', 'á')
  730. test('%(title5)U', 'áéí 𝐀')
  731. test('%(title5)#U', 'a\u0301e\u0301i\u0301 𝐀')
  732. test('%(title5)+U', 'áéí A')
  733. test('%(title5)+#U', 'a\u0301e\u0301i\u0301 A')
  734. test('%(height)D', '1k')
  735. test('%(filesize)#D', '1Ki')
  736. test('%(height)5.2D', ' 1.08k')
  737. test('%(title4)#S', 'foo_bar_test')
  738. test('%(title4).10S', ('foo "bar" ', 'foo "bar"' + ('#' if os.name == 'nt' else ' ')))
  739. if os.name == 'nt':
  740. test('%(title4)q', ('"foo ""bar"" test"', None))
  741. test('%(formats.:.id)#q', ('"id 1" "id 2" "id 3"', None))
  742. test('%(formats.0.id)#q', ('"id 1"', None))
  743. else:
  744. test('%(title4)q', ('\'foo "bar" test\'', '\'foo "bar" test\''))
  745. test('%(formats.:.id)#q', "'id 1' 'id 2' 'id 3'")
  746. test('%(formats.0.id)#q', "'id 1'")
  747. # Internal formatting
  748. test('%(timestamp-1000>%H-%M-%S)s', '11-43-20')
  749. test('%(title|%)s %(title|%%)s', '% %%')
  750. test('%(id+1-height+3)05d', '00158')
  751. test('%(width+100)05d', 'NA')
  752. test('%(filesize*8)d', '8192')
  753. test('%(formats.0) 15s', ('% 15s' % FORMATS[0], None))
  754. test('%(formats.0)r', (repr(FORMATS[0]), None))
  755. test('%(height.0)03d', '001')
  756. test('%(-height.0)04d', '-001')
  757. test('%(formats.-1.id)s', FORMATS[-1]['id'])
  758. test('%(formats.0.id.-1)d', FORMATS[0]['id'][-1])
  759. test('%(formats.3)s', 'NA')
  760. test('%(formats.:2:-1)r', repr(FORMATS[:2:-1]))
  761. test('%(formats.0.id.-1+id)f', '1235.000000')
  762. test('%(formats.0.id.-1+formats.1.id.-1)d', '3')
  763. out = json.dumps([{'id': f['id'], 'height.:2': str(f['height'])[:2]}
  764. if 'height' in f else {'id': f['id']}
  765. for f in FORMATS])
  766. test('%(formats.:.{id,height.:2})j', (out, None))
  767. test('%(formats.:.{id,height}.id)l', ', '.join(f['id'] for f in FORMATS))
  768. test('%(.{id,title})j', ('{"id": "1234"}', '{"id": "1234"}'))
  769. # Alternates
  770. test('%(title,id)s', '1234')
  771. test('%(width-100,height+20|def)d', '1100')
  772. test('%(width-100,height+width|def)s', 'def')
  773. test('%(timestamp-x>%H\\,%M\\,%S,timestamp>%H\\,%M\\,%S)s', '12,00,00')
  774. # Replacement
  775. test('%(id&foo)s.bar', 'foo.bar')
  776. test('%(title&foo)s.bar', 'NA.bar')
  777. test('%(title&foo|baz)s.bar', 'baz.bar')
  778. test('%(x,id&foo|baz)s.bar', 'foo.bar')
  779. test('%(x,title&foo|baz)s.bar', 'baz.bar')
  780. test('%(id&a\nb|)s', ('a\nb', 'a b'))
  781. test('%(id&hi {:>10} {}|)s', 'hi 1234 1234')
  782. test(R'%(id&{0} {}|)s', 'NA')
  783. test(R'%(id&{0.1}|)s', 'NA')
  784. test('%(height&{:,d})S', '1,080')
  785. # Laziness
  786. def gen():
  787. yield from range(5)
  788. raise self.assertTrue(False, 'LazyList should not be evaluated till here')
  789. test('%(key.4)s', '4', info={'key': LazyList(gen())})
  790. # Empty filename
  791. test('%(foo|)s-%(bar|)s.%(ext)s', '-.mp4')
  792. # test('%(foo|)s.%(ext)s', ('.mp4', '_.mp4')) # FIXME: ?
  793. # test('%(foo|)s', ('', '_')) # FIXME: ?
  794. # Environment variable expansion for prepare_filename
  795. os.environ['__yt_dlp_var'] = 'expanded'
  796. envvar = '%__yt_dlp_var%' if os.name == 'nt' else '$__yt_dlp_var'
  797. test(envvar, (envvar, 'expanded'))
  798. if os.name == 'nt':
  799. test('%s%', ('%s%', '%s%'))
  800. os.environ['s'] = 'expanded'
  801. test('%s%', ('%s%', 'expanded')) # %s% should be expanded before escaping %s
  802. os.environ['(test)s'] = 'expanded'
  803. test('%(test)s%', ('NA%', 'expanded')) # Environment should take priority over template
  804. # Path expansion and escaping
  805. test('Hello %(title1)s', 'Hello $PATH')
  806. test('Hello %(title2)s', 'Hello %PATH%')
  807. test('%(title3)s', ('foo/bar\\test', 'foo⧸bar⧹test'))
  808. test('folder/%(title3)s', ('folder/foo/bar\\test', f'folder{os.path.sep}foo⧸bar⧹test'))
  809. def test_format_note(self):
  810. ydl = YoutubeDL()
  811. self.assertEqual(ydl._format_note({}), '')
  812. assertRegexpMatches(self, ydl._format_note({
  813. 'vbr': 10,
  814. }), r'^\s*10k$')
  815. assertRegexpMatches(self, ydl._format_note({
  816. 'fps': 30,
  817. }), r'^30fps$')
  818. def test_postprocessors(self):
  819. filename = 'post-processor-testfile.mp4'
  820. audiofile = filename + '.mp3'
  821. class SimplePP(PostProcessor):
  822. def run(self, info):
  823. with open(audiofile, 'w') as f:
  824. f.write('EXAMPLE')
  825. return [info['filepath']], info
  826. def run_pp(params, pp):
  827. with open(filename, 'w') as f:
  828. f.write('EXAMPLE')
  829. ydl = YoutubeDL(params)
  830. ydl.add_post_processor(pp())
  831. ydl.post_process(filename, {'filepath': filename})
  832. run_pp({'keepvideo': True}, SimplePP)
  833. self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
  834. self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
  835. os.unlink(filename)
  836. os.unlink(audiofile)
  837. run_pp({'keepvideo': False}, SimplePP)
  838. self.assertFalse(os.path.exists(filename), f'{filename} exists')
  839. self.assertTrue(os.path.exists(audiofile), f'{audiofile} doesn\'t exist')
  840. os.unlink(audiofile)
  841. class ModifierPP(PostProcessor):
  842. def run(self, info):
  843. with open(info['filepath'], 'w') as f:
  844. f.write('MODIFIED')
  845. return [], info
  846. run_pp({'keepvideo': False}, ModifierPP)
  847. self.assertTrue(os.path.exists(filename), f'{filename} doesn\'t exist')
  848. os.unlink(filename)
  849. def test_match_filter(self):
  850. first = {
  851. 'id': '1',
  852. 'url': TEST_URL,
  853. 'title': 'one',
  854. 'extractor': 'TEST',
  855. 'duration': 30,
  856. 'filesize': 10 * 1024,
  857. 'playlist_id': '42',
  858. 'uploader': '變態妍字幕版 太妍 тест',
  859. 'creator': "тест ' 123 ' тест--",
  860. 'webpage_url': 'http://example.com/watch?v=shenanigans',
  861. }
  862. second = {
  863. 'id': '2',
  864. 'url': TEST_URL,
  865. 'title': 'two',
  866. 'extractor': 'TEST',
  867. 'duration': 10,
  868. 'description': 'foo',
  869. 'filesize': 5 * 1024,
  870. 'playlist_id': '43',
  871. 'uploader': 'тест 123',
  872. 'webpage_url': 'http://example.com/watch?v=SHENANIGANS',
  873. }
  874. videos = [first, second]
  875. def get_videos(filter_=None):
  876. ydl = YDL({'match_filter': filter_, 'simulate': True})
  877. for v in videos:
  878. ydl.process_ie_result(v.copy(), download=True)
  879. return [v['id'] for v in ydl.downloaded_info_dicts]
  880. res = get_videos()
  881. self.assertEqual(res, ['1', '2'])
  882. def f(v, incomplete):
  883. if v['id'] == '1':
  884. return None
  885. else:
  886. return 'Video id is not 1'
  887. res = get_videos(f)
  888. self.assertEqual(res, ['1'])
  889. f = match_filter_func('duration < 30')
  890. res = get_videos(f)
  891. self.assertEqual(res, ['2'])
  892. f = match_filter_func('description = foo')
  893. res = get_videos(f)
  894. self.assertEqual(res, ['2'])
  895. f = match_filter_func('description =? foo')
  896. res = get_videos(f)
  897. self.assertEqual(res, ['1', '2'])
  898. f = match_filter_func('filesize > 5KiB')
  899. res = get_videos(f)
  900. self.assertEqual(res, ['1'])
  901. f = match_filter_func('playlist_id = 42')
  902. res = get_videos(f)
  903. self.assertEqual(res, ['1'])
  904. f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
  905. res = get_videos(f)
  906. self.assertEqual(res, ['1'])
  907. f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
  908. res = get_videos(f)
  909. self.assertEqual(res, ['2'])
  910. f = match_filter_func('creator = "тест \' 123 \' тест--"')
  911. res = get_videos(f)
  912. self.assertEqual(res, ['1'])
  913. f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
  914. res = get_videos(f)
  915. self.assertEqual(res, ['1'])
  916. f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
  917. res = get_videos(f)
  918. self.assertEqual(res, [])
  919. def test_playlist_items_selection(self):
  920. INDICES, PAGE_SIZE = list(range(1, 11)), 3
  921. def entry(i, evaluated):
  922. evaluated.append(i)
  923. return {
  924. 'id': str(i),
  925. 'title': str(i),
  926. 'url': TEST_URL,
  927. }
  928. def pagedlist_entries(evaluated):
  929. def page_func(n):
  930. start = PAGE_SIZE * n
  931. for i in INDICES[start: start + PAGE_SIZE]:
  932. yield entry(i, evaluated)
  933. return OnDemandPagedList(page_func, PAGE_SIZE)
  934. def page_num(i):
  935. return (i + PAGE_SIZE - 1) // PAGE_SIZE
  936. def generator_entries(evaluated):
  937. for i in INDICES:
  938. yield entry(i, evaluated)
  939. def list_entries(evaluated):
  940. return list(generator_entries(evaluated))
  941. def lazylist_entries(evaluated):
  942. return LazyList(generator_entries(evaluated))
  943. def get_downloaded_info_dicts(params, entries):
  944. ydl = YDL(params)
  945. ydl.process_ie_result({
  946. '_type': 'playlist',
  947. 'id': 'test',
  948. 'extractor': 'test:playlist',
  949. 'extractor_key': 'test:playlist',
  950. 'webpage_url': 'http://example.com',
  951. 'entries': entries,
  952. })
  953. return ydl.downloaded_info_dicts
  954. def test_selection(params, expected_ids, evaluate_all=False):
  955. expected_ids = list(expected_ids)
  956. if evaluate_all:
  957. generator_eval = pagedlist_eval = INDICES
  958. elif not expected_ids:
  959. generator_eval = pagedlist_eval = []
  960. else:
  961. generator_eval = INDICES[0: max(expected_ids)]
  962. pagedlist_eval = INDICES[PAGE_SIZE * page_num(min(expected_ids)) - PAGE_SIZE:
  963. PAGE_SIZE * page_num(max(expected_ids))]
  964. for name, func, expected_eval in (
  965. ('list', list_entries, INDICES),
  966. ('Generator', generator_entries, generator_eval),
  967. # ('LazyList', lazylist_entries, generator_eval), # Generator and LazyList follow the exact same code path
  968. ('PagedList', pagedlist_entries, pagedlist_eval),
  969. ):
  970. evaluated = []
  971. entries = func(evaluated)
  972. results = [(v['playlist_autonumber'] - 1, (int(v['id']), v['playlist_index']))
  973. for v in get_downloaded_info_dicts(params, entries)]
  974. self.assertEqual(results, list(enumerate(zip(expected_ids, expected_ids))), f'Entries of {name} for {params}')
  975. self.assertEqual(sorted(evaluated), expected_eval, f'Evaluation of {name} for {params}')
  976. test_selection({}, INDICES)
  977. test_selection({'playlistend': 20}, INDICES, True)
  978. test_selection({'playlistend': 2}, INDICES[:2])
  979. test_selection({'playliststart': 11}, [], True)
  980. test_selection({'playliststart': 2}, INDICES[1:])
  981. test_selection({'playlist_items': '2-4'}, INDICES[1:4])
  982. test_selection({'playlist_items': '2,4'}, [2, 4])
  983. test_selection({'playlist_items': '20'}, [], True)
  984. test_selection({'playlist_items': '0'}, [])
  985. # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
  986. test_selection({'playlist_items': '2-4,3-4,3'}, [2, 3, 4])
  987. test_selection({'playlist_items': '4,2'}, [4, 2])
  988. # Tests for https://github.com/yt-dlp/yt-dlp/issues/720
  989. # https://github.com/yt-dlp/yt-dlp/issues/302
  990. test_selection({'playlistreverse': True}, INDICES[::-1])
  991. test_selection({'playliststart': 2, 'playlistreverse': True}, INDICES[:0:-1])
  992. test_selection({'playlist_items': '2,4', 'playlistreverse': True}, [4, 2])
  993. test_selection({'playlist_items': '4,2'}, [4, 2])
  994. # Tests for --playlist-items start:end:step
  995. test_selection({'playlist_items': ':'}, INDICES, True)
  996. test_selection({'playlist_items': '::1'}, INDICES, True)
  997. test_selection({'playlist_items': '::-1'}, INDICES[::-1], True)
  998. test_selection({'playlist_items': ':6'}, INDICES[:6])
  999. test_selection({'playlist_items': ':-6'}, INDICES[:-5], True)
  1000. test_selection({'playlist_items': '-1:6:-2'}, INDICES[:4:-2], True)
  1001. test_selection({'playlist_items': '9:-6:-2'}, INDICES[8:3:-2], True)
  1002. test_selection({'playlist_items': '1:inf:2'}, INDICES[::2], True)
  1003. test_selection({'playlist_items': '-2:inf'}, INDICES[-2:], True)
  1004. test_selection({'playlist_items': ':inf:-1'}, [], True)
  1005. test_selection({'playlist_items': '0-2:2'}, [2])
  1006. test_selection({'playlist_items': '1-:2'}, INDICES[::2], True)
  1007. test_selection({'playlist_items': '0--2:2'}, INDICES[1:-1:2], True)
  1008. test_selection({'playlist_items': '10::3'}, [10], True)
  1009. test_selection({'playlist_items': '-1::3'}, [10], True)
  1010. test_selection({'playlist_items': '11::3'}, [], True)
  1011. test_selection({'playlist_items': '-15::2'}, INDICES[1::2], True)
  1012. test_selection({'playlist_items': '-15::15'}, [], True)
  1013. def test_do_not_override_ie_key_in_url_transparent(self):
  1014. ydl = YDL()
  1015. class Foo1IE(InfoExtractor):
  1016. _VALID_URL = r'foo1:'
  1017. def _real_extract(self, url):
  1018. return {
  1019. '_type': 'url_transparent',
  1020. 'url': 'foo2:',
  1021. 'ie_key': 'Foo2',
  1022. 'title': 'foo1 title',
  1023. 'id': 'foo1_id',
  1024. }
  1025. class Foo2IE(InfoExtractor):
  1026. _VALID_URL = r'foo2:'
  1027. def _real_extract(self, url):
  1028. return {
  1029. '_type': 'url',
  1030. 'url': 'foo3:',
  1031. 'ie_key': 'Foo3',
  1032. }
  1033. class Foo3IE(InfoExtractor):
  1034. _VALID_URL = r'foo3:'
  1035. def _real_extract(self, url):
  1036. return _make_result([{'url': TEST_URL}], title='foo3 title')
  1037. ydl.add_info_extractor(Foo1IE(ydl))
  1038. ydl.add_info_extractor(Foo2IE(ydl))
  1039. ydl.add_info_extractor(Foo3IE(ydl))
  1040. ydl.extract_info('foo1:')
  1041. downloaded = ydl.downloaded_info_dicts[0]
  1042. self.assertEqual(downloaded['url'], TEST_URL)
  1043. self.assertEqual(downloaded['title'], 'foo1 title')
  1044. self.assertEqual(downloaded['id'], 'testid')
  1045. self.assertEqual(downloaded['extractor'], 'testex')
  1046. self.assertEqual(downloaded['extractor_key'], 'TestEx')
  1047. # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
  1048. def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
  1049. class _YDL(YDL):
  1050. def __init__(self, *args, **kwargs):
  1051. super().__init__(*args, **kwargs)
  1052. def trouble(self, s, tb=None):
  1053. pass
  1054. ydl = _YDL({
  1055. 'format': 'extra',
  1056. 'ignoreerrors': True,
  1057. })
  1058. class VideoIE(InfoExtractor):
  1059. _VALID_URL = r'video:(?P<id>\d+)'
  1060. def _real_extract(self, url):
  1061. video_id = self._match_id(url)
  1062. formats = [{
  1063. 'format_id': 'default',
  1064. 'url': 'url:',
  1065. }]
  1066. if video_id == '0':
  1067. raise ExtractorError('foo')
  1068. if video_id == '2':
  1069. formats.append({
  1070. 'format_id': 'extra',
  1071. 'url': TEST_URL,
  1072. })
  1073. return {
  1074. 'id': video_id,
  1075. 'title': f'Video {video_id}',
  1076. 'formats': formats,
  1077. }
  1078. class PlaylistIE(InfoExtractor):
  1079. _VALID_URL = r'playlist:'
  1080. def _entries(self):
  1081. for n in range(3):
  1082. video_id = str(n)
  1083. yield {
  1084. '_type': 'url_transparent',
  1085. 'ie_key': VideoIE.ie_key(),
  1086. 'id': video_id,
  1087. 'url': f'video:{video_id}',
  1088. 'title': f'Video Transparent {video_id}',
  1089. }
  1090. def _real_extract(self, url):
  1091. return self.playlist_result(self._entries())
  1092. ydl.add_info_extractor(VideoIE(ydl))
  1093. ydl.add_info_extractor(PlaylistIE(ydl))
  1094. info = ydl.extract_info('playlist:')
  1095. entries = info['entries']
  1096. self.assertEqual(len(entries), 3)
  1097. self.assertTrue(entries[0] is None)
  1098. self.assertTrue(entries[1] is None)
  1099. self.assertEqual(len(ydl.downloaded_info_dicts), 1)
  1100. downloaded = ydl.downloaded_info_dicts[0]
  1101. entries[2].pop('requested_downloads', None)
  1102. self.assertEqual(entries[2], downloaded)
  1103. self.assertEqual(downloaded['url'], TEST_URL)
  1104. self.assertEqual(downloaded['title'], 'Video Transparent 2')
  1105. self.assertEqual(downloaded['id'], '2')
  1106. self.assertEqual(downloaded['extractor'], 'Video')
  1107. self.assertEqual(downloaded['extractor_key'], 'Video')
  1108. def test_header_cookies(self):
  1109. from http.cookiejar import Cookie
  1110. ydl = FakeYDL()
  1111. ydl.report_warning = lambda *_, **__: None
  1112. def cookie(name, value, version=None, domain='', path='', secure=False, expires=None):
  1113. return Cookie(
  1114. version or 0, name, value, None, False,
  1115. domain, bool(domain), bool(domain), path, bool(path),
  1116. secure, expires, False, None, None, rest={})
  1117. _test_url = 'https://yt.dlp/test'
  1118. def test(encoded_cookies, cookies, *, headers=False, round_trip=None, error_re=None):
  1119. def _test():
  1120. ydl.cookiejar.clear()
  1121. ydl._load_cookies(encoded_cookies, autoscope=headers)
  1122. if headers:
  1123. ydl._apply_header_cookies(_test_url)
  1124. data = {'url': _test_url}
  1125. ydl._calc_headers(data)
  1126. self.assertCountEqual(
  1127. map(vars, ydl.cookiejar), map(vars, cookies),
  1128. 'Extracted cookiejar.Cookie is not the same')
  1129. if not headers:
  1130. self.assertEqual(
  1131. data.get('cookies'), round_trip or encoded_cookies,
  1132. 'Cookie is not the same as round trip')
  1133. ydl.__dict__['_YoutubeDL__header_cookies'] = []
  1134. with self.subTest(msg=encoded_cookies):
  1135. if not error_re:
  1136. _test()
  1137. return
  1138. with self.assertRaisesRegex(Exception, error_re):
  1139. _test()
  1140. test('test=value; Domain=.yt.dlp', [cookie('test', 'value', domain='.yt.dlp')])
  1141. test('test=value', [cookie('test', 'value')], error_re=r'Unscoped cookies are not allowed')
  1142. test('cookie1=value1; Domain=.yt.dlp; Path=/test; cookie2=value2; Domain=.yt.dlp; Path=/', [
  1143. cookie('cookie1', 'value1', domain='.yt.dlp', path='/test'),
  1144. cookie('cookie2', 'value2', domain='.yt.dlp', path='/')])
  1145. test('test=value; Domain=.yt.dlp; Path=/test; Secure; Expires=9999999999', [
  1146. cookie('test', 'value', domain='.yt.dlp', path='/test', secure=True, expires=9999999999)])
  1147. test('test="value; "; path=/test; domain=.yt.dlp', [
  1148. cookie('test', 'value; ', domain='.yt.dlp', path='/test')],
  1149. round_trip='test="value\\073 "; Domain=.yt.dlp; Path=/test')
  1150. test('name=; Domain=.yt.dlp', [cookie('name', '', domain='.yt.dlp')],
  1151. round_trip='name=""; Domain=.yt.dlp')
  1152. test('test=value', [cookie('test', 'value', domain='.yt.dlp')], headers=True)
  1153. test('cookie1=value; Domain=.yt.dlp; cookie2=value', [], headers=True, error_re=r'Invalid syntax')
  1154. ydl.deprecated_feature = ydl.report_error
  1155. test('test=value', [], headers=True, error_re=r'Passing cookies as a header is a potential security risk')
  1156. def test_infojson_cookies(self):
  1157. TEST_FILE = 'test_infojson_cookies.info.json'
  1158. TEST_URL = 'https://example.com/example.mp4'
  1159. COOKIES = 'a=b; Domain=.example.com; c=d; Domain=.example.com'
  1160. COOKIE_HEADER = {'Cookie': 'a=b; c=d'}
  1161. ydl = FakeYDL()
  1162. ydl.process_info = lambda x: ydl._write_info_json('test', x, TEST_FILE)
  1163. def make_info(info_header_cookies=False, fmts_header_cookies=False, cookies_field=False):
  1164. fmt = {'url': TEST_URL}
  1165. if fmts_header_cookies:
  1166. fmt['http_headers'] = COOKIE_HEADER
  1167. if cookies_field:
  1168. fmt['cookies'] = COOKIES
  1169. return _make_result([fmt], http_headers=COOKIE_HEADER if info_header_cookies else None)
  1170. def test(initial_info, note):
  1171. result = {}
  1172. result['processed'] = ydl.process_ie_result(initial_info)
  1173. self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
  1174. msg=f'No cookies set in cookiejar after initial process when {note}')
  1175. ydl.cookiejar.clear()
  1176. with open(TEST_FILE) as infojson:
  1177. result['loaded'] = ydl.sanitize_info(json.load(infojson), True)
  1178. result['final'] = ydl.process_ie_result(result['loaded'].copy(), download=False)
  1179. self.assertTrue(ydl.cookiejar.get_cookies_for_url(TEST_URL),
  1180. msg=f'No cookies set in cookiejar after final process when {note}')
  1181. ydl.cookiejar.clear()
  1182. for key in ('processed', 'loaded', 'final'):
  1183. info = result[key]
  1184. self.assertIsNone(
  1185. traverse_obj(info, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False),
  1186. msg=f'Cookie header not removed in {key} result when {note}')
  1187. self.assertEqual(
  1188. traverse_obj(info, ((None, ('formats', 0)), 'cookies'), get_all=False), COOKIES,
  1189. msg=f'No cookies field found in {key} result when {note}')
  1190. test({'url': TEST_URL, 'http_headers': COOKIE_HEADER, 'id': '1', 'title': 'x'}, 'no formats field')
  1191. test(make_info(info_header_cookies=True), 'info_dict header cokies')
  1192. test(make_info(fmts_header_cookies=True), 'format header cookies')
  1193. test(make_info(info_header_cookies=True, fmts_header_cookies=True), 'info_dict and format header cookies')
  1194. test(make_info(info_header_cookies=True, fmts_header_cookies=True, cookies_field=True), 'all cookies fields')
  1195. test(make_info(cookies_field=True), 'cookies format field')
  1196. test({'url': TEST_URL, 'cookies': COOKIES, 'id': '1', 'title': 'x'}, 'info_dict cookies field only')
  1197. try_rm(TEST_FILE)
  1198. def test_add_headers_cookie(self):
  1199. def check_for_cookie_header(result):
  1200. return traverse_obj(result, ((None, ('formats', 0)), 'http_headers', 'Cookie'), casesense=False, get_all=False)
  1201. ydl = FakeYDL({'http_headers': {'Cookie': 'a=b'}})
  1202. ydl._apply_header_cookies(_make_result([])['webpage_url']) # Scope to input webpage URL: .example.com
  1203. fmt = {'url': 'https://example.com/video.mp4'}
  1204. result = ydl.process_ie_result(_make_result([fmt]), download=False)
  1205. self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies in result info_dict')
  1206. self.assertEqual(result.get('cookies'), 'a=b; Domain=.example.com', msg='No cookies were set in cookies field')
  1207. self.assertIn('a=b', ydl.cookiejar.get_cookie_header(fmt['url']), msg='No cookies were set in cookiejar')
  1208. fmt = {'url': 'https://wrong.com/video.mp4'}
  1209. result = ydl.process_ie_result(_make_result([fmt]), download=False)
  1210. self.assertIsNone(check_for_cookie_header(result), msg='http_headers cookies for wrong domain')
  1211. self.assertFalse(result.get('cookies'), msg='Cookies set in cookies field for wrong domain')
  1212. self.assertFalse(ydl.cookiejar.get_cookie_header(fmt['url']), msg='Cookies set in cookiejar for wrong domain')
  1213. def test_load_plugins_compat(self):
  1214. # Should try to reload plugins if they haven't already been loaded
  1215. all_plugins_loaded.value = False
  1216. FakeYDL().close()
  1217. assert all_plugins_loaded.value
  1218. if __name__ == '__main__':
  1219. unittest.main()