test_YoutubeDL.py 60 KB

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