test_download.py 11 KB

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