test_download.py 11 KB

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