test_download.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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 io
  19. import json
  20. import socket
  21. import youtube_dl.YoutubeDL
  22. from youtube_dl.compat import (
  23. compat_http_client,
  24. compat_urllib_error,
  25. compat_HTTPError,
  26. )
  27. from youtube_dl.utils import (
  28. DownloadError,
  29. ExtractorError,
  30. format_bytes,
  31. UnavailableVideoError,
  32. )
  33. from youtube_dl.extractor import get_info_extractor
  34. RETRIES = 3
  35. class YoutubeDL(youtube_dl.YoutubeDL):
  36. def __init__(self, *args, **kwargs):
  37. self.to_stderr = self.to_screen
  38. self.processed_info_dicts = []
  39. super(YoutubeDL, self).__init__(*args, **kwargs)
  40. def report_warning(self, message):
  41. # Don't accept warnings during tests
  42. raise ExtractorError(message)
  43. def process_info(self, info_dict):
  44. self.processed_info_dicts.append(info_dict)
  45. return super(YoutubeDL, self).process_info(info_dict)
  46. def _file_md5(fn):
  47. with open(fn, 'rb') as f:
  48. return hashlib.md5(f.read()).hexdigest()
  49. defs = gettestcases()
  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. def setUp(self):
  56. self.defs = defs
  57. # Dynamically generate tests
  58. def generator(test_case, tname):
  59. def test_template(self):
  60. ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
  61. other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
  62. is_playlist = any(k.startswith('playlist') for k in test_case)
  63. test_cases = test_case.get(
  64. 'playlist', [] if is_playlist else [test_case])
  65. def print_skipping(reason):
  66. print('Skipping %s: %s' % (test_case['name'], reason))
  67. if not ie.working():
  68. print_skipping('IE marked as not _WORKING')
  69. return
  70. for tc in test_cases:
  71. info_dict = tc.get('info_dict', {})
  72. if not (info_dict.get('id') and info_dict.get('ext')):
  73. raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
  74. if 'skip' in test_case:
  75. print_skipping(test_case['skip'])
  76. return
  77. for other_ie in other_ies:
  78. if not other_ie.working():
  79. print_skipping('test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
  80. return
  81. params = get_params(test_case.get('params', {}))
  82. params['outtmpl'] = tname + '_' + params['outtmpl']
  83. if is_playlist and 'playlist' not in test_case:
  84. params.setdefault('extract_flat', 'in_playlist')
  85. params.setdefault('skip_download', True)
  86. ydl = YoutubeDL(params, auto_init=False)
  87. ydl.add_default_info_extractors()
  88. finished_hook_called = set()
  89. def _hook(status):
  90. if status['status'] == 'finished':
  91. finished_hook_called.add(status['filename'])
  92. ydl.add_progress_hook(_hook)
  93. expect_warnings(ydl, test_case.get('expected_warnings', []))
  94. def get_tc_filename(tc):
  95. return ydl.prepare_filename(tc.get('info_dict', {}))
  96. res_dict = None
  97. def try_rm_tcs_files(tcs=None):
  98. if tcs is None:
  99. tcs = test_cases
  100. for tc in tcs:
  101. tc_filename = get_tc_filename(tc)
  102. try_rm(tc_filename)
  103. try_rm(tc_filename + '.part')
  104. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  105. try_rm_tcs_files()
  106. try:
  107. try_num = 1
  108. while True:
  109. try:
  110. # We're not using .download here sine that is just a shim
  111. # for outside error handling, and returns the exit code
  112. # instead of the result dict.
  113. res_dict = ydl.extract_info(
  114. test_case['url'],
  115. force_generic_extractor=params.get('force_generic_extractor', False))
  116. except (DownloadError, ExtractorError) as err:
  117. # Check if the exception is not a network related one
  118. 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):
  119. raise
  120. if try_num == RETRIES:
  121. report_warning('%s failed due to network errors, skipping...' % tname)
  122. return
  123. print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
  124. try_num += 1
  125. else:
  126. break
  127. if is_playlist:
  128. self.assertTrue(res_dict['_type'] in ['playlist', 'multi_video'])
  129. self.assertTrue('entries' in res_dict)
  130. expect_info_dict(self, res_dict, test_case.get('info_dict', {}))
  131. if 'playlist_mincount' in test_case:
  132. assertGreaterEqual(
  133. self,
  134. len(res_dict['entries']),
  135. test_case['playlist_mincount'],
  136. 'Expected at least %d in playlist %s, but got only %d' % (
  137. test_case['playlist_mincount'], test_case['url'],
  138. len(res_dict['entries'])))
  139. if 'playlist_count' in test_case:
  140. self.assertEqual(
  141. len(res_dict['entries']),
  142. test_case['playlist_count'],
  143. 'Expected %d entries in playlist %s, but got %d.' % (
  144. test_case['playlist_count'],
  145. test_case['url'],
  146. len(res_dict['entries']),
  147. ))
  148. if 'playlist_duration_sum' in test_case:
  149. got_duration = sum(e['duration'] for e in res_dict['entries'])
  150. self.assertEqual(
  151. test_case['playlist_duration_sum'], got_duration)
  152. for tc in test_cases:
  153. tc_filename = get_tc_filename(tc)
  154. if not test_case.get('params', {}).get('skip_download', False):
  155. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  156. self.assertTrue(tc_filename in finished_hook_called)
  157. expected_minsize = tc.get('file_minsize', 10000)
  158. if expected_minsize is not None:
  159. if params.get('test'):
  160. expected_minsize = max(expected_minsize, 10000)
  161. got_fsize = os.path.getsize(tc_filename)
  162. assertGreaterEqual(
  163. self, got_fsize, expected_minsize,
  164. 'Expected %s to be at least %s, but it\'s only %s ' %
  165. (tc_filename, format_bytes(expected_minsize),
  166. format_bytes(got_fsize)))
  167. if 'md5' in tc:
  168. md5_for_file = _file_md5(tc_filename)
  169. self.assertEqual(md5_for_file, tc['md5'])
  170. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  171. self.assertTrue(
  172. os.path.exists(info_json_fn),
  173. 'Missing info file %s' % info_json_fn)
  174. with io.open(info_json_fn, encoding='utf-8') as infof:
  175. info_dict = json.load(infof)
  176. expect_info_dict(self, info_dict, tc.get('info_dict', {}))
  177. finally:
  178. try_rm_tcs_files()
  179. if is_playlist and res_dict is not None and res_dict.get('entries'):
  180. # Remove all other files that may have been extracted if the
  181. # extractor returns full results even with extract_flat
  182. res_tcs = [{'info_dict': e} for e in res_dict['entries']]
  183. try_rm_tcs_files(res_tcs)
  184. return test_template
  185. # And add them to TestDownload
  186. for n, test_case in enumerate(defs):
  187. tname = 'test_' + str(test_case['name'])
  188. i = 1
  189. while hasattr(TestDownload, tname):
  190. tname = 'test_%s_%d' % (test_case['name'], i)
  191. i += 1
  192. test_method = generator(test_case, tname)
  193. test_method.__name__ = str(tname)
  194. setattr(TestDownload, test_method.__name__, test_method)
  195. del test_method
  196. if __name__ == '__main__':
  197. unittest.main()