test_download.py 11 KB

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