test_download.py 11 KB

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