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.

213 lines
8.0 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. expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
  119. if 'playlist_mincount' in test_case:
  120. assertGreaterEqual(
  121. self,
  122. len(res_dict['entries']),
  123. test_case['playlist_mincount'],
  124. 'Expected at least %d in playlist %s, but got only %d' % (
  125. test_case['playlist_mincount'], test_case['url'],
  126. len(res_dict['entries'])))
  127. if 'playlist_count' in test_case:
  128. self.assertEqual(
  129. len(res_dict['entries']),
  130. test_case['playlist_count'],
  131. 'Expected %d entries in playlist %s, but got %d.' % (
  132. test_case['playlist_count'],
  133. test_case['url'],
  134. len(res_dict['entries']),
  135. ))
  136. if 'playlist_duration_sum' in test_case:
  137. got_duration = sum(e['duration'] for e in res_dict['entries'])
  138. self.assertEqual(
  139. test_case['playlist_duration_sum'], got_duration)
  140. for tc in test_cases:
  141. tc_filename = get_tc_filename(tc)
  142. if not test_case.get('params', {}).get('skip_download', False):
  143. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  144. self.assertTrue(tc_filename in finished_hook_called)
  145. expected_minsize = tc.get('file_minsize', 10000)
  146. if expected_minsize is not None:
  147. if params.get('test'):
  148. expected_minsize = max(expected_minsize, 10000)
  149. got_fsize = os.path.getsize(tc_filename)
  150. assertGreaterEqual(
  151. self, got_fsize, expected_minsize,
  152. 'Expected %s to be at least %s, but it\'s only %s ' %
  153. (tc_filename, format_bytes(expected_minsize),
  154. format_bytes(got_fsize)))
  155. if 'md5' in tc:
  156. md5_for_file = _file_md5(tc_filename)
  157. self.assertEqual(md5_for_file, tc['md5'])
  158. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  159. self.assertTrue(os.path.exists(info_json_fn))
  160. with io.open(info_json_fn, encoding='utf-8') as infof:
  161. info_dict = json.load(infof)
  162. expect_info_dict(self, tc.get('info_dict', {}), info_dict)
  163. finally:
  164. try_rm_tcs_files()
  165. if is_playlist and res_dict is not None:
  166. # Remove all other files that may have been extracted if the
  167. # extractor returns full results even with extract_flat
  168. res_tcs = [{'info_dict': e} for e in res_dict['entries']]
  169. try_rm_tcs_files(res_tcs)
  170. return test_template
  171. ### And add them to TestDownload
  172. for n, test_case in enumerate(defs):
  173. test_method = generator(test_case)
  174. tname = 'test_' + str(test_case['name'])
  175. i = 1
  176. while hasattr(TestDownload, tname):
  177. tname = 'test_' + str(test_case['name']) + '_' + str(i)
  178. i += 1
  179. test_method.__name__ = tname
  180. setattr(TestDownload, test_method.__name__, test_method)
  181. del test_method
  182. if __name__ == '__main__':
  183. unittest.main()