test_download.py 7.4 KB

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