test_download.py 12 KB

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