You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

215 lines
8.1 KiB

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