logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

test_download.py (10807B)


  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. get_params,
  12. gettestcases,
  13. expect_info_dict,
  14. try_rm,
  15. report_warning,
  16. )
  17. import hashlib
  18. import json
  19. import socket
  20. import youtube_dl.YoutubeDL
  21. from youtube_dl.compat import (
  22. compat_http_client,
  23. compat_HTTPError,
  24. compat_open as open,
  25. compat_urllib_error,
  26. )
  27. from youtube_dl.utils import (
  28. DownloadError,
  29. ExtractorError,
  30. error_to_compat_str,
  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. 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. if not (info_dict.get('id') and info_dict.get('ext')):
  83. raise Exception('Test definition (%s) requires both \'id\' and \'ext\' keys present to define the output file' % (tname, ))
  84. if 'skip' in test_case:
  85. print_skipping(test_case['skip'])
  86. for other_ie in other_ies:
  87. if not other_ie.working():
  88. print_skipping('test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
  89. params = get_params(test_case.get('params', {}))
  90. params['outtmpl'] = tname + '_' + params['outtmpl']
  91. if is_playlist and 'playlist' not in test_case:
  92. params.setdefault('extract_flat', 'in_playlist')
  93. params.setdefault('playlistend', test_case.get('playlist_mincount'))
  94. params.setdefault('skip_download', True)
  95. ydl = YoutubeDL(params, auto_init=False)
  96. ydl.add_default_info_extractors()
  97. finished_hook_called = set()
  98. def _hook(status):
  99. if status['status'] == 'finished':
  100. finished_hook_called.add(status['filename'])
  101. ydl.add_progress_hook(_hook)
  102. expect_warnings(ydl, test_case.get('expected_warnings', []))
  103. def get_tc_filename(tc):
  104. return ydl.prepare_filename(tc.get('info_dict', {}))
  105. res_dict = None
  106. def try_rm_tcs_files(tcs=None):
  107. if tcs is None:
  108. tcs = test_cases
  109. for tc in tcs:
  110. tc_filename = get_tc_filename(tc)
  111. try_rm(tc_filename)
  112. try_rm(tc_filename + '.part')
  113. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  114. try_rm_tcs_files()
  115. try:
  116. try_num = 1
  117. while True:
  118. try:
  119. # We're not using .download here since that is just a shim
  120. # for outside error handling, and returns the exit code
  121. # instead of the result dict.
  122. res_dict = ydl.extract_info(
  123. test_case['url'],
  124. force_generic_extractor=params.get('force_generic_extractor', False))
  125. except (DownloadError, ExtractorError) as err:
  126. # Check if the exception is not a network related one
  127. 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):
  128. msg = getattr(err, 'msg', error_to_compat_str(err))
  129. err.msg = '%s (%s)' % (msg, tname, )
  130. raise err
  131. if try_num == RETRIES:
  132. report_warning('%s failed due to network errors, skipping...' % tname)
  133. return
  134. print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
  135. try_num += 1
  136. else:
  137. break
  138. if is_playlist:
  139. self.assertTrue(res_dict['_type'] in ['playlist', 'multi_video'])
  140. self.assertTrue('entries' in res_dict)
  141. expect_info_dict(self, res_dict, test_case.get('info_dict', {}))
  142. if 'playlist_mincount' in test_case:
  143. assertGreaterEqual(
  144. self,
  145. len(res_dict['entries']),
  146. test_case['playlist_mincount'],
  147. 'Expected at least %d in playlist %s, but got only %d' % (
  148. test_case['playlist_mincount'], test_case['url'],
  149. len(res_dict['entries'])))
  150. if 'playlist_count' in test_case:
  151. self.assertEqual(
  152. len(res_dict['entries']),
  153. test_case['playlist_count'],
  154. 'Expected %d entries in playlist %s, but got %d.' % (
  155. test_case['playlist_count'],
  156. test_case['url'],
  157. len(res_dict['entries']),
  158. ))
  159. if 'playlist_duration_sum' in test_case:
  160. got_duration = sum(e['duration'] for e in res_dict['entries'])
  161. self.assertEqual(
  162. test_case['playlist_duration_sum'], got_duration)
  163. # Generalize both playlists and single videos to unified format for
  164. # simplicity
  165. if 'entries' not in res_dict:
  166. res_dict['entries'] = [res_dict]
  167. for tc_num, tc in enumerate(test_cases):
  168. tc_res_dict = res_dict['entries'][tc_num]
  169. # First, check test cases' data against extracted data alone
  170. expect_info_dict(self, tc_res_dict, tc.get('info_dict', {}))
  171. # Now, check downloaded file consistency
  172. # support test-case with volatile ID, signalled by regexp value
  173. if tc.get('info_dict', {}).get('id', '').startswith('re:'):
  174. test_id = tc['info_dict']['id']
  175. tc['info_dict']['id'] = tc_res_dict['id']
  176. else:
  177. test_id = None
  178. tc_filename = get_tc_filename(tc)
  179. if test_id:
  180. tc['info_dict']['id'] = test_id
  181. if not test_case.get('params', {}).get('skip_download', False):
  182. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  183. self.assertTrue(tc_filename in finished_hook_called)
  184. expected_minsize = tc.get('file_minsize', 10000)
  185. if expected_minsize is not None:
  186. if params.get('test'):
  187. expected_minsize = max(expected_minsize, 10000)
  188. got_fsize = os.path.getsize(tc_filename)
  189. assertGreaterEqual(
  190. self, got_fsize, expected_minsize,
  191. 'Expected %s to be at least %s, but it\'s only %s ' %
  192. (tc_filename, format_bytes(expected_minsize),
  193. format_bytes(got_fsize)))
  194. if 'md5' in tc:
  195. md5_for_file = _file_md5(tc_filename)
  196. self.assertEqual(tc['md5'], md5_for_file)
  197. # Finally, check test cases' data again but this time against
  198. # extracted data from info JSON file written during processing
  199. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  200. self.assertTrue(
  201. os.path.exists(info_json_fn),
  202. 'Missing info file %s' % info_json_fn)
  203. with open(info_json_fn, encoding='utf-8') as infof:
  204. info_dict = json.load(infof)
  205. expect_info_dict(self, info_dict, tc.get('info_dict', {}))
  206. finally:
  207. try_rm_tcs_files()
  208. if is_playlist and res_dict is not None and res_dict.get('entries'):
  209. # Remove all other files that may have been extracted if the
  210. # extractor returns full results even with extract_flat
  211. res_tcs = [{'info_dict': e} for e in res_dict['entries']]
  212. try_rm_tcs_files(res_tcs)
  213. return test_template
  214. # And add them to TestDownload
  215. for n, test_case in enumerate(defs):
  216. tname = 'test_' + str(test_case['name'])
  217. i = 1
  218. while hasattr(TestDownload, tname):
  219. tname = 'test_%s_%d' % (test_case['name'], i)
  220. i += 1
  221. test_method = generator(test_case, tname)
  222. test_method.__name__ = str(tname)
  223. ie_list = test_case.get('add_ie')
  224. test_method.add_ie = ie_list and ','.join(ie_list)
  225. setattr(TestDownload, test_method.__name__, test_method)
  226. del test_method
  227. if __name__ == '__main__':
  228. unittest.main()