test_download.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env python3
  2. # Allow direct execution
  3. import os
  4. import sys
  5. import unittest
  6. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  7. import collections
  8. import hashlib
  9. import json
  10. from test.helper import (
  11. assertGreaterEqual,
  12. expect_info_dict,
  13. expect_warnings,
  14. get_params,
  15. gettestcases,
  16. getwebpagetestcases,
  17. is_download_test,
  18. report_warning,
  19. try_rm,
  20. )
  21. import yt_dlp.YoutubeDL # isort: split
  22. from yt_dlp.extractor import get_info_extractor
  23. from yt_dlp.networking.exceptions import HTTPError, TransportError
  24. from yt_dlp.utils import (
  25. DownloadError,
  26. ExtractorError,
  27. UnavailableVideoError,
  28. YoutubeDLError,
  29. format_bytes,
  30. join_nonempty,
  31. )
  32. RETRIES = 3
  33. class YoutubeDL(yt_dlp.YoutubeDL):
  34. def __init__(self, *args, **kwargs):
  35. self.to_stderr = self.to_screen
  36. self.processed_info_dicts = []
  37. super().__init__(*args, **kwargs)
  38. def report_warning(self, message, *args, **kwargs):
  39. # Don't accept warnings during tests
  40. raise ExtractorError(message)
  41. def process_info(self, info_dict):
  42. self.processed_info_dicts.append(info_dict.copy())
  43. return super().process_info(info_dict)
  44. def _file_md5(fn):
  45. with open(fn, 'rb') as f:
  46. return hashlib.md5(f.read()).hexdigest()
  47. normal_test_cases = gettestcases()
  48. webpage_test_cases = getwebpagetestcases()
  49. tests_counter = collections.defaultdict(collections.Counter)
  50. @is_download_test
  51. class TestDownload(unittest.TestCase):
  52. # Parallel testing in nosetests. See
  53. # http://nose.readthedocs.org/en/latest/doc_tests/test_multiprocess/multiprocess.html
  54. _multiprocess_shared_ = True
  55. maxDiff = None
  56. COMPLETED_TESTS = {}
  57. def __str__(self):
  58. """Identify each test with the `add_ie` attribute, if available."""
  59. cls, add_ie = type(self), getattr(self, self._testMethodName).add_ie
  60. return f'{self._testMethodName} ({cls.__module__}.{cls.__name__}){f" [{add_ie}]" if add_ie else ""}:'
  61. # Dynamically generate tests
  62. def generator(test_case, tname):
  63. def test_template(self):
  64. if self.COMPLETED_TESTS.get(tname):
  65. return
  66. self.COMPLETED_TESTS[tname] = True
  67. ie = yt_dlp.extractor.get_info_extractor(test_case['name'])()
  68. other_ies = [get_info_extractor(ie_key)() for ie_key in test_case.get('add_ie', [])]
  69. is_playlist = any(k.startswith('playlist') for k in test_case)
  70. test_cases = test_case.get(
  71. 'playlist', [] if is_playlist else [test_case])
  72. def print_skipping(reason):
  73. print('Skipping %s: %s' % (test_case['name'], reason))
  74. self.skipTest(reason)
  75. if not ie.working():
  76. print_skipping('IE marked as not _WORKING')
  77. for tc in test_cases:
  78. if tc.get('expected_exception'):
  79. continue
  80. info_dict = tc.get('info_dict', {})
  81. params = tc.get('params', {})
  82. if not info_dict.get('id'):
  83. raise Exception(f'Test {tname} definition incorrect - "id" key is not present')
  84. elif not info_dict.get('ext') and info_dict.get('_type', 'video') == 'video':
  85. if params.get('skip_download') and params.get('ignore_no_formats_error'):
  86. continue
  87. raise Exception(f'Test {tname} definition incorrect - "ext" key must be present to define the output file')
  88. if 'skip' in test_case:
  89. print_skipping(test_case['skip'])
  90. for other_ie in other_ies:
  91. if not other_ie.working():
  92. print_skipping('test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
  93. params = get_params(test_case.get('params', {}))
  94. params['outtmpl'] = tname + '_' + params['outtmpl']
  95. if is_playlist and 'playlist' not in test_case:
  96. params.setdefault('extract_flat', 'in_playlist')
  97. params.setdefault('playlistend', test_case.get(
  98. 'playlist_mincount', test_case.get('playlist_count', -2) + 1))
  99. params.setdefault('skip_download', True)
  100. ydl = YoutubeDL(params, auto_init=False)
  101. ydl.add_default_info_extractors()
  102. finished_hook_called = set()
  103. def _hook(status):
  104. if status['status'] == 'finished':
  105. finished_hook_called.add(status['filename'])
  106. ydl.add_progress_hook(_hook)
  107. expect_warnings(ydl, test_case.get('expected_warnings', []))
  108. def get_tc_filename(tc):
  109. return ydl.prepare_filename(dict(tc.get('info_dict', {})))
  110. res_dict = None
  111. def match_exception(err):
  112. expected_exception = test_case.get('expected_exception')
  113. if not expected_exception:
  114. return False
  115. if err.__class__.__name__ == expected_exception:
  116. return True
  117. for exc in err.exc_info:
  118. if exc.__class__.__name__ == expected_exception:
  119. return True
  120. return False
  121. def try_rm_tcs_files(tcs=None):
  122. if tcs is None:
  123. tcs = test_cases
  124. for tc in tcs:
  125. tc_filename = get_tc_filename(tc)
  126. try_rm(tc_filename)
  127. try_rm(tc_filename + '.part')
  128. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  129. try_rm_tcs_files()
  130. try:
  131. try_num = 1
  132. while True:
  133. try:
  134. # We're not using .download here since that is just a shim
  135. # for outside error handling, and returns the exit code
  136. # instead of the result dict.
  137. res_dict = ydl.extract_info(
  138. test_case['url'],
  139. force_generic_extractor=params.get('force_generic_extractor', False))
  140. except (DownloadError, ExtractorError) as err:
  141. # Check if the exception is not a network related one
  142. if not isinstance(err.exc_info[1], (TransportError, UnavailableVideoError)) or (isinstance(err.exc_info[1], HTTPError) and err.exc_info[1].status == 503):
  143. if match_exception(err):
  144. return
  145. err.msg = f'{getattr(err, "msg", err)} ({tname})'
  146. raise
  147. if try_num == RETRIES:
  148. report_warning('%s failed due to network errors, skipping...' % tname)
  149. return
  150. print(f'Retrying: {try_num} failed tries\n\n##########\n\n')
  151. try_num += 1
  152. except YoutubeDLError as err:
  153. if match_exception(err):
  154. return
  155. raise
  156. else:
  157. break
  158. if is_playlist:
  159. self.assertTrue(res_dict['_type'] in ['playlist', 'multi_video'])
  160. self.assertTrue('entries' in res_dict)
  161. expect_info_dict(self, res_dict, test_case.get('info_dict', {}))
  162. if 'playlist_mincount' in test_case:
  163. assertGreaterEqual(
  164. self,
  165. len(res_dict['entries']),
  166. test_case['playlist_mincount'],
  167. 'Expected at least %d in playlist %s, but got only %d' % (
  168. test_case['playlist_mincount'], test_case['url'],
  169. len(res_dict['entries'])))
  170. if 'playlist_count' in test_case:
  171. self.assertEqual(
  172. len(res_dict['entries']),
  173. test_case['playlist_count'],
  174. 'Expected %d entries in playlist %s, but got %d.' % (
  175. test_case['playlist_count'],
  176. test_case['url'],
  177. len(res_dict['entries']),
  178. ))
  179. if 'playlist_duration_sum' in test_case:
  180. got_duration = sum(e['duration'] for e in res_dict['entries'])
  181. self.assertEqual(
  182. test_case['playlist_duration_sum'], got_duration)
  183. # Generalize both playlists and single videos to unified format for
  184. # simplicity
  185. if 'entries' not in res_dict:
  186. res_dict['entries'] = [res_dict]
  187. for tc_num, tc in enumerate(test_cases):
  188. tc_res_dict = res_dict['entries'][tc_num]
  189. # First, check test cases' data against extracted data alone
  190. expect_info_dict(self, tc_res_dict, tc.get('info_dict', {}))
  191. if tc_res_dict.get('_type', 'video') != 'video':
  192. continue
  193. # Now, check downloaded file consistency
  194. tc_filename = get_tc_filename(tc)
  195. if not test_case.get('params', {}).get('skip_download', False):
  196. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  197. self.assertTrue(tc_filename in finished_hook_called)
  198. expected_minsize = tc.get('file_minsize', 10000)
  199. if expected_minsize is not None:
  200. if params.get('test'):
  201. expected_minsize = max(expected_minsize, 10000)
  202. got_fsize = os.path.getsize(tc_filename)
  203. assertGreaterEqual(
  204. self, got_fsize, expected_minsize,
  205. 'Expected %s to be at least %s, but it\'s only %s ' %
  206. (tc_filename, format_bytes(expected_minsize),
  207. format_bytes(got_fsize)))
  208. if 'md5' in tc:
  209. md5_for_file = _file_md5(tc_filename)
  210. self.assertEqual(tc['md5'], md5_for_file)
  211. # Finally, check test cases' data again but this time against
  212. # extracted data from info JSON file written during processing
  213. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  214. self.assertTrue(
  215. os.path.exists(info_json_fn),
  216. 'Missing info file %s' % info_json_fn)
  217. with open(info_json_fn, encoding='utf-8') as infof:
  218. info_dict = json.load(infof)
  219. expect_info_dict(self, info_dict, tc.get('info_dict', {}))
  220. finally:
  221. try_rm_tcs_files()
  222. if is_playlist and res_dict is not None and res_dict.get('entries'):
  223. # Remove all other files that may have been extracted if the
  224. # extractor returns full results even with extract_flat
  225. res_tcs = [{'info_dict': e} for e in res_dict['entries']]
  226. try_rm_tcs_files(res_tcs)
  227. ydl.close()
  228. return test_template
  229. # And add them to TestDownload
  230. def inject_tests(test_cases, label=''):
  231. for test_case in test_cases:
  232. name = test_case['name']
  233. tname = join_nonempty('test', name, label, tests_counter[name][label], delim='_')
  234. tests_counter[name][label] += 1
  235. test_method = generator(test_case, tname)
  236. test_method.__name__ = tname
  237. test_method.add_ie = ','.join(test_case.get('add_ie', []))
  238. setattr(TestDownload, test_method.__name__, test_method)
  239. inject_tests(normal_test_cases)
  240. # TODO: disable redirection to the IE to ensure we are actually testing the webpage extraction
  241. inject_tests(webpage_test_cases, 'webpage')
  242. def batch_generator(name):
  243. def test_template(self):
  244. for label, num_tests in tests_counter[name].items():
  245. for i in range(num_tests):
  246. test_name = join_nonempty('test', name, label, i, delim='_')
  247. try:
  248. getattr(self, test_name)()
  249. except unittest.SkipTest:
  250. print(f'Skipped {test_name}')
  251. return test_template
  252. for name in tests_counter:
  253. test_method = batch_generator(name)
  254. test_method.__name__ = f'test_{name}_all'
  255. test_method.add_ie = ''
  256. setattr(TestDownload, test_method.__name__, test_method)
  257. del test_method
  258. if __name__ == '__main__':
  259. unittest.main()