test_YoutubeDL.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. #!/usr/bin/env python
  2. from __future__ import unicode_literals
  3. # Allow direct execution
  4. import os
  5. import sys
  6. import unittest
  7. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  8. import copy
  9. from test.helper import FakeYDL, assertRegexpMatches
  10. from youtube_dl import YoutubeDL
  11. from youtube_dl.compat import compat_str, compat_urllib_error
  12. from youtube_dl.extractor import YoutubeIE
  13. from youtube_dl.extractor.common import InfoExtractor
  14. from youtube_dl.postprocessor.common import PostProcessor
  15. from youtube_dl.utils import ExtractorError, match_filter_func
  16. TEST_URL = 'http://localhost/sample.mp4'
  17. class YDL(FakeYDL):
  18. def __init__(self, *args, **kwargs):
  19. super(YDL, self).__init__(*args, **kwargs)
  20. self.downloaded_info_dicts = []
  21. self.msgs = []
  22. def process_info(self, info_dict):
  23. self.downloaded_info_dicts.append(info_dict)
  24. def to_screen(self, msg):
  25. self.msgs.append(msg)
  26. def _make_result(formats, **kwargs):
  27. res = {
  28. 'formats': formats,
  29. 'id': 'testid',
  30. 'title': 'testttitle',
  31. 'extractor': 'testex',
  32. }
  33. res.update(**kwargs)
  34. return res
  35. class TestFormatSelection(unittest.TestCase):
  36. def test_prefer_free_formats(self):
  37. # Same resolution => download webm
  38. ydl = YDL()
  39. ydl.params['prefer_free_formats'] = True
  40. formats = [
  41. {'ext': 'webm', 'height': 460, 'url': TEST_URL},
  42. {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
  43. ]
  44. info_dict = _make_result(formats)
  45. yie = YoutubeIE(ydl)
  46. yie._sort_formats(info_dict['formats'])
  47. ydl.process_ie_result(info_dict)
  48. downloaded = ydl.downloaded_info_dicts[0]
  49. self.assertEqual(downloaded['ext'], 'webm')
  50. # Different resolution => download best quality (mp4)
  51. ydl = YDL()
  52. ydl.params['prefer_free_formats'] = True
  53. formats = [
  54. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  55. {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
  56. ]
  57. info_dict['formats'] = formats
  58. yie = YoutubeIE(ydl)
  59. yie._sort_formats(info_dict['formats'])
  60. ydl.process_ie_result(info_dict)
  61. downloaded = ydl.downloaded_info_dicts[0]
  62. self.assertEqual(downloaded['ext'], 'mp4')
  63. # No prefer_free_formats => prefer mp4 and flv for greater compatibility
  64. ydl = YDL()
  65. ydl.params['prefer_free_formats'] = False
  66. formats = [
  67. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  68. {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
  69. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  70. ]
  71. info_dict['formats'] = formats
  72. yie = YoutubeIE(ydl)
  73. yie._sort_formats(info_dict['formats'])
  74. ydl.process_ie_result(info_dict)
  75. downloaded = ydl.downloaded_info_dicts[0]
  76. self.assertEqual(downloaded['ext'], 'mp4')
  77. ydl = YDL()
  78. ydl.params['prefer_free_formats'] = False
  79. formats = [
  80. {'ext': 'flv', 'height': 720, 'url': TEST_URL},
  81. {'ext': 'webm', 'height': 720, 'url': TEST_URL},
  82. ]
  83. info_dict['formats'] = formats
  84. yie = YoutubeIE(ydl)
  85. yie._sort_formats(info_dict['formats'])
  86. ydl.process_ie_result(info_dict)
  87. downloaded = ydl.downloaded_info_dicts[0]
  88. self.assertEqual(downloaded['ext'], 'flv')
  89. def test_format_selection(self):
  90. formats = [
  91. {'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  92. {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
  93. {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
  94. {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
  95. {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
  96. ]
  97. info_dict = _make_result(formats)
  98. ydl = YDL({'format': '20/47'})
  99. ydl.process_ie_result(info_dict.copy())
  100. downloaded = ydl.downloaded_info_dicts[0]
  101. self.assertEqual(downloaded['format_id'], '47')
  102. ydl = YDL({'format': '20/71/worst'})
  103. ydl.process_ie_result(info_dict.copy())
  104. downloaded = ydl.downloaded_info_dicts[0]
  105. self.assertEqual(downloaded['format_id'], '35')
  106. ydl = YDL()
  107. ydl.process_ie_result(info_dict.copy())
  108. downloaded = ydl.downloaded_info_dicts[0]
  109. self.assertEqual(downloaded['format_id'], '2')
  110. ydl = YDL({'format': 'webm/mp4'})
  111. ydl.process_ie_result(info_dict.copy())
  112. downloaded = ydl.downloaded_info_dicts[0]
  113. self.assertEqual(downloaded['format_id'], '47')
  114. ydl = YDL({'format': '3gp/40/mp4'})
  115. ydl.process_ie_result(info_dict.copy())
  116. downloaded = ydl.downloaded_info_dicts[0]
  117. self.assertEqual(downloaded['format_id'], '35')
  118. ydl = YDL({'format': 'example-with-dashes'})
  119. ydl.process_ie_result(info_dict.copy())
  120. downloaded = ydl.downloaded_info_dicts[0]
  121. self.assertEqual(downloaded['format_id'], 'example-with-dashes')
  122. def test_format_selection_audio(self):
  123. formats = [
  124. {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
  125. {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
  126. {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
  127. {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
  128. ]
  129. info_dict = _make_result(formats)
  130. ydl = YDL({'format': 'bestaudio'})
  131. ydl.process_ie_result(info_dict.copy())
  132. downloaded = ydl.downloaded_info_dicts[0]
  133. self.assertEqual(downloaded['format_id'], 'audio-high')
  134. ydl = YDL({'format': 'worstaudio'})
  135. ydl.process_ie_result(info_dict.copy())
  136. downloaded = ydl.downloaded_info_dicts[0]
  137. self.assertEqual(downloaded['format_id'], 'audio-low')
  138. formats = [
  139. {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
  140. {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
  141. ]
  142. info_dict = _make_result(formats)
  143. ydl = YDL({'format': 'bestaudio/worstaudio/best'})
  144. ydl.process_ie_result(info_dict.copy())
  145. downloaded = ydl.downloaded_info_dicts[0]
  146. self.assertEqual(downloaded['format_id'], 'vid-high')
  147. def test_format_selection_audio_exts(self):
  148. formats = [
  149. {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  150. {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  151. {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
  152. {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  153. {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
  154. ]
  155. info_dict = _make_result(formats)
  156. ydl = YDL({'format': 'best'})
  157. ie = YoutubeIE(ydl)
  158. ie._sort_formats(info_dict['formats'])
  159. ydl.process_ie_result(copy.deepcopy(info_dict))
  160. downloaded = ydl.downloaded_info_dicts[0]
  161. self.assertEqual(downloaded['format_id'], 'aac-64')
  162. ydl = YDL({'format': 'mp3'})
  163. ie = YoutubeIE(ydl)
  164. ie._sort_formats(info_dict['formats'])
  165. ydl.process_ie_result(copy.deepcopy(info_dict))
  166. downloaded = ydl.downloaded_info_dicts[0]
  167. self.assertEqual(downloaded['format_id'], 'mp3-64')
  168. ydl = YDL({'prefer_free_formats': True})
  169. ie = YoutubeIE(ydl)
  170. ie._sort_formats(info_dict['formats'])
  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. formats = [
  190. {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
  191. ]
  192. info_dict = _make_result(formats)
  193. ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
  194. ydl.process_ie_result(info_dict.copy())
  195. downloaded = ydl.downloaded_info_dicts[0]
  196. self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
  197. def test_youtube_format_selection(self):
  198. order = [
  199. '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
  200. # Apple HTTP Live Streaming
  201. '96', '95', '94', '93', '92', '132', '151',
  202. # 3D
  203. '85', '84', '102', '83', '101', '82', '100',
  204. # Dash video
  205. '137', '248', '136', '247', '135', '246',
  206. '245', '244', '134', '243', '133', '242', '160',
  207. # Dash audio
  208. '141', '172', '140', '171', '139',
  209. ]
  210. def format_info(f_id):
  211. info = YoutubeIE._formats[f_id].copy()
  212. # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
  213. # and 'vcodec', while in tests such information is incomplete since
  214. # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
  215. # test_YoutubeDL.test_youtube_format_selection is broken without
  216. # this fix
  217. if 'acodec' in info and 'vcodec' not in info:
  218. info['vcodec'] = 'none'
  219. elif 'vcodec' in info and 'acodec' not in info:
  220. info['acodec'] = 'none'
  221. info['format_id'] = f_id
  222. info['url'] = 'url:' + f_id
  223. return info
  224. formats_order = [format_info(f_id) for f_id in order]
  225. info_dict = _make_result(list(formats_order), extractor='youtube')
  226. ydl = YDL({'format': 'bestvideo+bestaudio'})
  227. yie = YoutubeIE(ydl)
  228. yie._sort_formats(info_dict['formats'])
  229. ydl.process_ie_result(info_dict)
  230. downloaded = ydl.downloaded_info_dicts[0]
  231. self.assertEqual(downloaded['format_id'], '137+141')
  232. self.assertEqual(downloaded['ext'], 'mp4')
  233. info_dict = _make_result(list(formats_order), extractor='youtube')
  234. ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
  235. yie = YoutubeIE(ydl)
  236. yie._sort_formats(info_dict['formats'])
  237. ydl.process_ie_result(info_dict)
  238. downloaded = ydl.downloaded_info_dicts[0]
  239. self.assertEqual(downloaded['format_id'], '38')
  240. info_dict = _make_result(list(formats_order), extractor='youtube')
  241. ydl = YDL({'format': 'bestvideo/best,bestaudio'})
  242. yie = YoutubeIE(ydl)
  243. yie._sort_formats(info_dict['formats'])
  244. ydl.process_ie_result(info_dict)
  245. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  246. self.assertEqual(downloaded_ids, ['137', '141'])
  247. info_dict = _make_result(list(formats_order), extractor='youtube')
  248. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
  249. yie = YoutubeIE(ydl)
  250. yie._sort_formats(info_dict['formats'])
  251. ydl.process_ie_result(info_dict)
  252. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  253. self.assertEqual(downloaded_ids, ['137+141', '248+141'])
  254. info_dict = _make_result(list(formats_order), extractor='youtube')
  255. ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
  256. yie = YoutubeIE(ydl)
  257. yie._sort_formats(info_dict['formats'])
  258. ydl.process_ie_result(info_dict)
  259. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  260. self.assertEqual(downloaded_ids, ['136+141', '247+141'])
  261. info_dict = _make_result(list(formats_order), extractor='youtube')
  262. ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
  263. yie = YoutubeIE(ydl)
  264. yie._sort_formats(info_dict['formats'])
  265. ydl.process_ie_result(info_dict)
  266. downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
  267. self.assertEqual(downloaded_ids, ['248+141'])
  268. for f1, f2 in zip(formats_order, formats_order[1:]):
  269. info_dict = _make_result([f1, f2], extractor='youtube')
  270. ydl = YDL({'format': 'best/bestvideo'})
  271. yie = YoutubeIE(ydl)
  272. yie._sort_formats(info_dict['formats'])
  273. ydl.process_ie_result(info_dict)
  274. downloaded = ydl.downloaded_info_dicts[0]
  275. self.assertEqual(downloaded['format_id'], f1['format_id'])
  276. info_dict = _make_result([f2, f1], extractor='youtube')
  277. ydl = YDL({'format': 'best/bestvideo'})
  278. yie = YoutubeIE(ydl)
  279. yie._sort_formats(info_dict['formats'])
  280. ydl.process_ie_result(info_dict)
  281. downloaded = ydl.downloaded_info_dicts[0]
  282. self.assertEqual(downloaded['format_id'], f1['format_id'])
  283. def test_invalid_format_specs(self):
  284. def assert_syntax_error(format_spec):
  285. ydl = YDL({'format': format_spec})
  286. info_dict = _make_result([{'format_id': 'foo', 'url': TEST_URL}])
  287. self.assertRaises(SyntaxError, ydl.process_ie_result, info_dict)
  288. assert_syntax_error('bestvideo,,best')
  289. assert_syntax_error('+bestaudio')
  290. assert_syntax_error('bestvideo+')
  291. assert_syntax_error('/')
  292. def test_format_filtering(self):
  293. formats = [
  294. {'format_id': 'A', 'filesize': 500, 'width': 1000},
  295. {'format_id': 'B', 'filesize': 1000, 'width': 500},
  296. {'format_id': 'C', 'filesize': 1000, 'width': 400},
  297. {'format_id': 'D', 'filesize': 2000, 'width': 600},
  298. {'format_id': 'E', 'filesize': 3000},
  299. {'format_id': 'F'},
  300. {'format_id': 'G', 'filesize': 1000000},
  301. ]
  302. for f in formats:
  303. f['url'] = 'http://_/'
  304. f['ext'] = 'unknown'
  305. info_dict = _make_result(formats)
  306. ydl = YDL({'format': 'best[filesize<3000]'})
  307. ydl.process_ie_result(info_dict)
  308. downloaded = ydl.downloaded_info_dicts[0]
  309. self.assertEqual(downloaded['format_id'], 'D')
  310. ydl = YDL({'format': 'best[filesize<=3000]'})
  311. ydl.process_ie_result(info_dict)
  312. downloaded = ydl.downloaded_info_dicts[0]
  313. self.assertEqual(downloaded['format_id'], 'E')
  314. ydl = YDL({'format': 'best[filesize <= ? 3000]'})
  315. ydl.process_ie_result(info_dict)
  316. downloaded = ydl.downloaded_info_dicts[0]
  317. self.assertEqual(downloaded['format_id'], 'F')
  318. ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
  319. ydl.process_ie_result(info_dict)
  320. downloaded = ydl.downloaded_info_dicts[0]
  321. self.assertEqual(downloaded['format_id'], 'B')
  322. ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
  323. ydl.process_ie_result(info_dict)
  324. downloaded = ydl.downloaded_info_dicts[0]
  325. self.assertEqual(downloaded['format_id'], 'C')
  326. ydl = YDL({'format': '[filesize>?1]'})
  327. ydl.process_ie_result(info_dict)
  328. downloaded = ydl.downloaded_info_dicts[0]
  329. self.assertEqual(downloaded['format_id'], 'G')
  330. ydl = YDL({'format': '[filesize<1M]'})
  331. ydl.process_ie_result(info_dict)
  332. downloaded = ydl.downloaded_info_dicts[0]
  333. self.assertEqual(downloaded['format_id'], 'E')
  334. ydl = YDL({'format': '[filesize<1MiB]'})
  335. ydl.process_ie_result(info_dict)
  336. downloaded = ydl.downloaded_info_dicts[0]
  337. self.assertEqual(downloaded['format_id'], 'G')
  338. ydl = YDL({'format': 'all[width>=400][width<=600]'})
  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, ['B', 'C', 'D'])
  342. ydl = YDL({'format': 'best[height<40]'})
  343. try:
  344. ydl.process_ie_result(info_dict)
  345. except ExtractorError:
  346. pass
  347. self.assertEqual(ydl.downloaded_info_dicts, [])
  348. class TestYoutubeDL(unittest.TestCase):
  349. def test_subtitles(self):
  350. def s_formats(lang, autocaption=False):
  351. return [{
  352. 'ext': ext,
  353. 'url': 'http://localhost/video.%s.%s' % (lang, ext),
  354. '_auto': autocaption,
  355. } for ext in ['vtt', 'srt', 'ass']]
  356. subtitles = dict((l, s_formats(l)) for l in ['en', 'fr', 'es'])
  357. auto_captions = dict((l, s_formats(l, True)) for l in ['it', 'pt', 'es'])
  358. info_dict = {
  359. 'id': 'test',
  360. 'title': 'Test',
  361. 'url': 'http://localhost/video.mp4',
  362. 'subtitles': subtitles,
  363. 'automatic_captions': auto_captions,
  364. 'extractor': 'TEST',
  365. }
  366. def get_info(params={}):
  367. params.setdefault('simulate', True)
  368. ydl = YDL(params)
  369. ydl.report_warning = lambda *args, **kargs: None
  370. return ydl.process_video_result(info_dict, download=False)
  371. result = get_info()
  372. self.assertFalse(result.get('requested_subtitles'))
  373. self.assertEqual(result['subtitles'], subtitles)
  374. self.assertEqual(result['automatic_captions'], auto_captions)
  375. result = get_info({'writesubtitles': True})
  376. subs = result['requested_subtitles']
  377. self.assertTrue(subs)
  378. self.assertEqual(set(subs.keys()), set(['en']))
  379. self.assertTrue(subs['en'].get('data') is None)
  380. self.assertEqual(subs['en']['ext'], 'ass')
  381. result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
  382. subs = result['requested_subtitles']
  383. self.assertEqual(subs['en']['ext'], 'srt')
  384. result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
  385. subs = result['requested_subtitles']
  386. self.assertTrue(subs)
  387. self.assertEqual(set(subs.keys()), set(['es', 'fr']))
  388. result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  389. subs = result['requested_subtitles']
  390. self.assertTrue(subs)
  391. self.assertEqual(set(subs.keys()), set(['es', 'pt']))
  392. self.assertFalse(subs['es']['_auto'])
  393. self.assertTrue(subs['pt']['_auto'])
  394. result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
  395. subs = result['requested_subtitles']
  396. self.assertTrue(subs)
  397. self.assertEqual(set(subs.keys()), set(['es', 'pt']))
  398. self.assertTrue(subs['es']['_auto'])
  399. self.assertTrue(subs['pt']['_auto'])
  400. def test_add_extra_info(self):
  401. test_dict = {
  402. 'extractor': 'Foo',
  403. }
  404. extra_info = {
  405. 'extractor': 'Bar',
  406. 'playlist': 'funny videos',
  407. }
  408. YDL.add_extra_info(test_dict, extra_info)
  409. self.assertEqual(test_dict['extractor'], 'Foo')
  410. self.assertEqual(test_dict['playlist'], 'funny videos')
  411. def test_prepare_filename(self):
  412. info = {
  413. 'id': '1234',
  414. 'ext': 'mp4',
  415. 'width': None,
  416. }
  417. def fname(templ):
  418. ydl = YoutubeDL({'outtmpl': templ})
  419. return ydl.prepare_filename(info)
  420. self.assertEqual(fname('%(id)s.%(ext)s'), '1234.mp4')
  421. self.assertEqual(fname('%(id)s-%(width)s.%(ext)s'), '1234-NA.mp4')
  422. # Replace missing fields with 'NA'
  423. self.assertEqual(fname('%(uploader_date)s-%(id)s.%(ext)s'), 'NA-1234.mp4')
  424. def test_format_note(self):
  425. ydl = YoutubeDL()
  426. self.assertEqual(ydl._format_note({}), '')
  427. assertRegexpMatches(self, ydl._format_note({
  428. 'vbr': 10,
  429. }), '^\s*10k$')
  430. assertRegexpMatches(self, ydl._format_note({
  431. 'fps': 30,
  432. }), '^30fps$')
  433. def test_postprocessors(self):
  434. filename = 'post-processor-testfile.mp4'
  435. audiofile = filename + '.mp3'
  436. class SimplePP(PostProcessor):
  437. def run(self, info):
  438. with open(audiofile, 'wt') as f:
  439. f.write('EXAMPLE')
  440. return [info['filepath']], info
  441. def run_pp(params, PP):
  442. with open(filename, 'wt') as f:
  443. f.write('EXAMPLE')
  444. ydl = YoutubeDL(params)
  445. ydl.add_post_processor(PP())
  446. ydl.post_process(filename, {'filepath': filename})
  447. run_pp({'keepvideo': True}, SimplePP)
  448. self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
  449. self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
  450. os.unlink(filename)
  451. os.unlink(audiofile)
  452. run_pp({'keepvideo': False}, SimplePP)
  453. self.assertFalse(os.path.exists(filename), '%s exists' % filename)
  454. self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
  455. os.unlink(audiofile)
  456. class ModifierPP(PostProcessor):
  457. def run(self, info):
  458. with open(info['filepath'], 'wt') as f:
  459. f.write('MODIFIED')
  460. return [], info
  461. run_pp({'keepvideo': False}, ModifierPP)
  462. self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
  463. os.unlink(filename)
  464. def test_match_filter(self):
  465. class FilterYDL(YDL):
  466. def __init__(self, *args, **kwargs):
  467. super(FilterYDL, self).__init__(*args, **kwargs)
  468. self.params['simulate'] = True
  469. def process_info(self, info_dict):
  470. super(YDL, self).process_info(info_dict)
  471. def _match_entry(self, info_dict, incomplete):
  472. res = super(FilterYDL, self)._match_entry(info_dict, incomplete)
  473. if res is None:
  474. self.downloaded_info_dicts.append(info_dict)
  475. return res
  476. first = {
  477. 'id': '1',
  478. 'url': TEST_URL,
  479. 'title': 'one',
  480. 'extractor': 'TEST',
  481. 'duration': 30,
  482. 'filesize': 10 * 1024,
  483. }
  484. second = {
  485. 'id': '2',
  486. 'url': TEST_URL,
  487. 'title': 'two',
  488. 'extractor': 'TEST',
  489. 'duration': 10,
  490. 'description': 'foo',
  491. 'filesize': 5 * 1024,
  492. }
  493. videos = [first, second]
  494. def get_videos(filter_=None):
  495. ydl = FilterYDL({'match_filter': filter_})
  496. for v in videos:
  497. ydl.process_ie_result(v, download=True)
  498. return [v['id'] for v in ydl.downloaded_info_dicts]
  499. res = get_videos()
  500. self.assertEqual(res, ['1', '2'])
  501. def f(v):
  502. if v['id'] == '1':
  503. return None
  504. else:
  505. return 'Video id is not 1'
  506. res = get_videos(f)
  507. self.assertEqual(res, ['1'])
  508. f = match_filter_func('duration < 30')
  509. res = get_videos(f)
  510. self.assertEqual(res, ['2'])
  511. f = match_filter_func('description = foo')
  512. res = get_videos(f)
  513. self.assertEqual(res, ['2'])
  514. f = match_filter_func('description =? foo')
  515. res = get_videos(f)
  516. self.assertEqual(res, ['1', '2'])
  517. f = match_filter_func('filesize > 5KiB')
  518. res = get_videos(f)
  519. self.assertEqual(res, ['1'])
  520. def test_playlist_items_selection(self):
  521. entries = [{
  522. 'id': compat_str(i),
  523. 'title': compat_str(i),
  524. 'url': TEST_URL,
  525. } for i in range(1, 5)]
  526. playlist = {
  527. '_type': 'playlist',
  528. 'id': 'test',
  529. 'entries': entries,
  530. 'extractor': 'test:playlist',
  531. 'extractor_key': 'test:playlist',
  532. 'webpage_url': 'http://example.com',
  533. }
  534. def get_ids(params):
  535. ydl = YDL(params)
  536. # make a copy because the dictionary can be modified
  537. ydl.process_ie_result(playlist.copy())
  538. return [int(v['id']) for v in ydl.downloaded_info_dicts]
  539. result = get_ids({})
  540. self.assertEqual(result, [1, 2, 3, 4])
  541. result = get_ids({'playlistend': 10})
  542. self.assertEqual(result, [1, 2, 3, 4])
  543. result = get_ids({'playlistend': 2})
  544. self.assertEqual(result, [1, 2])
  545. result = get_ids({'playliststart': 10})
  546. self.assertEqual(result, [])
  547. result = get_ids({'playliststart': 2})
  548. self.assertEqual(result, [2, 3, 4])
  549. result = get_ids({'playlist_items': '2-4'})
  550. self.assertEqual(result, [2, 3, 4])
  551. result = get_ids({'playlist_items': '2,4'})
  552. self.assertEqual(result, [2, 4])
  553. result = get_ids({'playlist_items': '10'})
  554. self.assertEqual(result, [])
  555. def test_urlopen_no_file_protocol(self):
  556. # see https://github.com/rg3/youtube-dl/issues/8227
  557. ydl = YDL()
  558. self.assertRaises(compat_urllib_error.URLError, ydl.urlopen, 'file:///etc/passwd')
  559. def test_do_not_override_ie_key_in_url_transparent(self):
  560. ydl = YDL()
  561. class Foo1IE(InfoExtractor):
  562. _VALID_URL = r'foo1:'
  563. def _real_extract(self, url):
  564. return {
  565. '_type': 'url_transparent',
  566. 'url': 'foo2:',
  567. 'ie_key': 'Foo2',
  568. }
  569. class Foo2IE(InfoExtractor):
  570. _VALID_URL = r'foo2:'
  571. def _real_extract(self, url):
  572. return {
  573. '_type': 'url',
  574. 'url': 'foo3:',
  575. 'ie_key': 'Foo3',
  576. }
  577. class Foo3IE(InfoExtractor):
  578. _VALID_URL = r'foo3:'
  579. def _real_extract(self, url):
  580. return _make_result([{'url': TEST_URL}])
  581. ydl.add_info_extractor(Foo1IE(ydl))
  582. ydl.add_info_extractor(Foo2IE(ydl))
  583. ydl.add_info_extractor(Foo3IE(ydl))
  584. ydl.extract_info('foo1:')
  585. downloaded = ydl.downloaded_info_dicts[0]
  586. self.assertEqual(downloaded['url'], TEST_URL)
  587. if __name__ == '__main__':
  588. unittest.main()