test_download.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. #!/usr/bin/env python
  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_warnings,
  11. expect_value,
  12. get_params,
  13. gettestcases,
  14. expect_info_dict,
  15. try_rm,
  16. report_warning,
  17. )
  18. import hashlib
  19. import io
  20. import json
  21. import socket
  22. import youtube_dl.YoutubeDL
  23. from youtube_dl.compat import (
  24. compat_http_client,
  25. compat_urllib_error,
  26. compat_HTTPError,
  27. )
  28. from youtube_dl.utils import (
  29. DownloadError,
  30. ExtractorError,
  31. format_bytes,
  32. UnavailableVideoError,
  33. )
  34. from youtube_dl.extractor import get_info_extractor
  35. RETRIES = 3
  36. class YoutubeDL(youtube_dl.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)
  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. 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. def __str__(self):
  57. """Identify each test with the `add_ie` attribute, if available."""
  58. def strclass(cls):
  59. """From 2.7's unittest; 2.6 had _strclass so we can't import it."""
  60. return '%s.%s' % (cls.__module__, cls.__name__)
  61. add_ie = getattr(self, self._testMethodName).add_ie
  62. return '%s (%s)%s:' % (self._testMethodName,
  63. strclass(self.__class__),
  64. ' [%s]' % add_ie if add_ie else '')
  65. def setUp(self):
  66. self.defs = defs
  67. # Dynamically generate tests
  68. def generator(test_case, tname):
  69. def test_template(self):
  70. ie = youtube_dl.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. if not ie.working():
  78. print_skipping('IE marked as not _WORKING')
  79. return
  80. for tc in test_cases:
  81. info_dict = tc.get('info_dict', {})
  82. if not (info_dict.get('id') and info_dict.get('ext')):
  83. raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
  84. if 'skip' in test_case:
  85. print_skipping(test_case['skip'])
  86. return
  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. return
  91. params = get_params(test_case.get('params', {}))
  92. params['outtmpl'] = tname + '_' + params['outtmpl']
  93. if is_playlist and 'playlist' not in test_case:
  94. params.setdefault('extract_flat', 'in_playlist')
  95. params.setdefault('skip_download', True)
  96. ydl = YoutubeDL(params, auto_init=False)
  97. ydl.add_default_info_extractors()
  98. finished_hook_called = set()
  99. def _hook(status):
  100. if status['status'] == 'finished':
  101. finished_hook_called.add(status['filename'])
  102. ydl.add_progress_hook(_hook)
  103. expect_warnings(ydl, test_case.get('expected_warnings', []))
  104. def get_tc_filename(tc):
  105. return ydl.prepare_filename(tc.get('info_dict', {}))
  106. res_dict = None
  107. def try_rm_tcs_files(tcs=None):
  108. if tcs is None:
  109. tcs = test_cases
  110. for tc in tcs:
  111. tc_filename = get_tc_filename(tc)
  112. try_rm(tc_filename)
  113. try_rm(tc_filename + '.part')
  114. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  115. try_rm_tcs_files()
  116. try:
  117. try_num = 1
  118. while True:
  119. try:
  120. # We're not using .download here since that is just a shim
  121. # for outside error handling, and returns the exit code
  122. # instead of the result dict.
  123. res_dict = ydl.extract_info(
  124. test_case['url'],
  125. force_generic_extractor=params.get('force_generic_extractor', False))
  126. except (DownloadError, ExtractorError) as err:
  127. # Check if the exception is not a network related one
  128. 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):
  129. raise
  130. if try_num == RETRIES:
  131. report_warning('%s failed due to network errors, skipping...' % tname)
  132. return
  133. print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
  134. try_num += 1
  135. else:
  136. break
  137. if is_playlist:
  138. self.assertTrue(res_dict['_type'] in ['playlist', 'multi_video'])
  139. self.assertTrue('entries' in res_dict)
  140. expect_info_dict(self, res_dict, test_case.get('info_dict', {}))
  141. if 'playlist_mincount' in test_case:
  142. assertGreaterEqual(
  143. self,
  144. len(res_dict['entries']),
  145. test_case['playlist_mincount'],
  146. 'Expected at least %d in playlist %s, but got only %d' % (
  147. test_case['playlist_mincount'], test_case['url'],
  148. len(res_dict['entries'])))
  149. if 'playlist_count' in test_case:
  150. self.assertEqual(
  151. len(res_dict['entries']),
  152. test_case['playlist_count'],
  153. 'Expected %d entries in playlist %s, but got %d.' % (
  154. test_case['playlist_count'],
  155. test_case['url'],
  156. len(res_dict['entries']),
  157. ))
  158. if 'playlist_duration_sum' in test_case:
  159. got_duration = sum(e['duration'] for e in res_dict['entries'])
  160. self.assertEqual(
  161. test_case['playlist_duration_sum'], got_duration)
  162. for tc_num, tc in enumerate(test_cases):
  163. tc_res_dict = res_dict['entries'][tc_num] if is_playlist else res_dict
  164. expect_info_dict(self, tc_res_dict, tc.get('info_dict', {}))
  165. tc_filename = get_tc_filename(tc)
  166. if not test_case.get('params', {}).get('skip_download', False):
  167. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  168. self.assertTrue(tc_filename in finished_hook_called)
  169. expected_minsize = tc.get('file_minsize', 10000)
  170. if expected_minsize is not None:
  171. if params.get('test'):
  172. expected_minsize = max(expected_minsize, 10000)
  173. got_fsize = os.path.getsize(tc_filename)
  174. assertGreaterEqual(
  175. self, got_fsize, expected_minsize,
  176. 'Expected %s to be at least %s, but it\'s only %s ' %
  177. (tc_filename, format_bytes(expected_minsize),
  178. format_bytes(got_fsize)))
  179. if 'md5' in tc:
  180. md5_for_file = _file_md5(tc_filename)
  181. self.assertEqual(md5_for_file, tc['md5'])
  182. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  183. self.assertTrue(
  184. os.path.exists(info_json_fn),
  185. 'Missing info file %s' % info_json_fn)
  186. with io.open(info_json_fn, encoding='utf-8') as infof:
  187. info_dict = json.load(infof)
  188. expect_info_dict(self, info_dict, tc.get('info_dict', {}))
  189. finally:
  190. try_rm_tcs_files()
  191. if is_playlist and res_dict is not None and res_dict.get('entries'):
  192. # Remove all other files that may have been extracted if the
  193. # extractor returns full results even with extract_flat
  194. res_tcs = [{'info_dict': e} for e in res_dict['entries']]
  195. try_rm_tcs_files(res_tcs)
  196. return test_template
  197. # And add them to TestDownload
  198. for n, test_case in enumerate(defs):
  199. tname = 'test_' + str(test_case['name'])
  200. i = 1
  201. while hasattr(TestDownload, tname):
  202. tname = 'test_%s_%d' % (test_case['name'], i)
  203. i += 1
  204. test_method = generator(test_case, tname)
  205. test_method.__name__ = str(tname)
  206. ie_list = test_case.get('add_ie')
  207. test_method.add_ie = ie_list and ','.join(ie_list)
  208. setattr(TestDownload, test_method.__name__, test_method)
  209. del test_method
  210. if __name__ == '__main__':
  211. unittest.main()