test_download.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 hypervideo_dl.YoutubeDL # isort: split
  22. from hypervideo_dl.extractor import get_info_extractor
  23. from hypervideo_dl.networking.exceptions import HTTPError, TransportError
  24. from hypervideo_dl.utils import (
  25. DownloadError,
  26. ExtractorError,
  27. UnavailableVideoError,
  28. format_bytes,
  29. join_nonempty,
  30. )
  31. RETRIES = 3
  32. class YoutubeDL(hypervideo_dl.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 = hypervideo_dl.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 %s: %s' % (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. info_dict = tc.get('info_dict', {})
  78. params = tc.get('params', {})
  79. if not info_dict.get('id'):
  80. raise Exception(f'Test {tname} definition incorrect - "id" key is not present')
  81. elif not info_dict.get('ext') and info_dict.get('_type', 'video') == 'video':
  82. if params.get('skip_download') and params.get('ignore_no_formats_error'):
  83. continue
  84. raise Exception(f'Test {tname} definition incorrect - "ext" key must be present to define the output file')
  85. if 'skip' in test_case:
  86. print_skipping(test_case['skip'])
  87. for other_ie in other_ies:
  88. if not other_ie.working():
  89. print_skipping('test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
  90. params = get_params(test_case.get('params', {}))
  91. params['outtmpl'] = tname + '_' + params['outtmpl']
  92. if is_playlist and 'playlist' not in test_case:
  93. params.setdefault('extract_flat', 'in_playlist')
  94. params.setdefault('playlistend', test_case.get(
  95. 'playlist_mincount', test_case.get('playlist_count', -2) + 1))
  96. params.setdefault('skip_download', True)
  97. ydl = YoutubeDL(params, auto_init=False)
  98. ydl.add_default_info_extractors()
  99. finished_hook_called = set()
  100. def _hook(status):
  101. if status['status'] == 'finished':
  102. finished_hook_called.add(status['filename'])
  103. ydl.add_progress_hook(_hook)
  104. expect_warnings(ydl, test_case.get('expected_warnings', []))
  105. def get_tc_filename(tc):
  106. return ydl.prepare_filename(dict(tc.get('info_dict', {})))
  107. res_dict = None
  108. def try_rm_tcs_files(tcs=None):
  109. if tcs is None:
  110. tcs = test_cases
  111. for tc in tcs:
  112. tc_filename = get_tc_filename(tc)
  113. try_rm(tc_filename)
  114. try_rm(tc_filename + '.part')
  115. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  116. try_rm_tcs_files()
  117. try:
  118. try_num = 1
  119. while True:
  120. try:
  121. # We're not using .download here since that is just a shim
  122. # for outside error handling, and returns the exit code
  123. # instead of the result dict.
  124. res_dict = ydl.extract_info(
  125. test_case['url'],
  126. force_generic_extractor=params.get('force_generic_extractor', False))
  127. except (DownloadError, ExtractorError) as err:
  128. # Check if the exception is not a network related one
  129. if not isinstance(err.exc_info[1], (TransportError, UnavailableVideoError)) or (isinstance(err.exc_info[1], HTTPError) and err.exc_info[1].status == 503):
  130. err.msg = f'{getattr(err, "msg", err)} ({tname})'
  131. raise
  132. if try_num == RETRIES:
  133. report_warning('%s failed due to network errors, skipping...' % tname)
  134. return
  135. print(f'Retrying: {try_num} failed tries\n\n##########\n\n')
  136. try_num += 1
  137. else:
  138. break
  139. if is_playlist:
  140. self.assertTrue(res_dict['_type'] in ['playlist', 'multi_video'])
  141. self.assertTrue('entries' in res_dict)
  142. expect_info_dict(self, res_dict, test_case.get('info_dict', {}))
  143. if 'playlist_mincount' in test_case:
  144. assertGreaterEqual(
  145. self,
  146. len(res_dict['entries']),
  147. test_case['playlist_mincount'],
  148. 'Expected at least %d in playlist %s, but got only %d' % (
  149. test_case['playlist_mincount'], test_case['url'],
  150. len(res_dict['entries'])))
  151. if 'playlist_count' in test_case:
  152. self.assertEqual(
  153. len(res_dict['entries']),
  154. test_case['playlist_count'],
  155. 'Expected %d entries in playlist %s, but got %d.' % (
  156. test_case['playlist_count'],
  157. test_case['url'],
  158. len(res_dict['entries']),
  159. ))
  160. if 'playlist_duration_sum' in test_case:
  161. got_duration = sum(e['duration'] for e in res_dict['entries'])
  162. self.assertEqual(
  163. test_case['playlist_duration_sum'], got_duration)
  164. # Generalize both playlists and single videos to unified format for
  165. # simplicity
  166. if 'entries' not in res_dict:
  167. res_dict['entries'] = [res_dict]
  168. for tc_num, tc in enumerate(test_cases):
  169. tc_res_dict = res_dict['entries'][tc_num]
  170. # First, check test cases' data against extracted data alone
  171. expect_info_dict(self, tc_res_dict, tc.get('info_dict', {}))
  172. if tc_res_dict.get('_type', 'video') != 'video':
  173. continue
  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. ydl.close()
  209. return test_template
  210. # And add them to TestDownload
  211. def inject_tests(test_cases, label=''):
  212. for test_case in test_cases:
  213. name = test_case['name']
  214. tname = join_nonempty('test', name, label, tests_counter[name][label], delim='_')
  215. tests_counter[name][label] += 1
  216. test_method = generator(test_case, tname)
  217. test_method.__name__ = tname
  218. test_method.add_ie = ','.join(test_case.get('add_ie', []))
  219. setattr(TestDownload, test_method.__name__, test_method)
  220. inject_tests(normal_test_cases)
  221. # TODO: disable redirection to the IE to ensure we are actually testing the webpage extraction
  222. inject_tests(webpage_test_cases, 'webpage')
  223. def batch_generator(name):
  224. def test_template(self):
  225. for label, num_tests in tests_counter[name].items():
  226. for i in range(num_tests):
  227. test_name = join_nonempty('test', name, label, i, delim='_')
  228. try:
  229. getattr(self, test_name)()
  230. except unittest.SkipTest:
  231. print(f'Skipped {test_name}')
  232. return test_template
  233. for name in tests_counter:
  234. test_method = batch_generator(name)
  235. test_method.__name__ = f'test_{name}_all'
  236. test_method.add_ie = ''
  237. setattr(TestDownload, test_method.__name__, test_method)
  238. del test_method
  239. if __name__ == '__main__':
  240. unittest.main()