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.

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