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.

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