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.

186 lines
6.6 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. 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. def try_rm_tcs_files():
  87. for tc in test_cases:
  88. tc_filename = get_tc_filename(tc)
  89. try_rm(tc_filename)
  90. try_rm(tc_filename + '.part')
  91. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  92. try_rm_tcs_files()
  93. try:
  94. try_num = 1
  95. while True:
  96. try:
  97. # We're not using .download here sine that is just a shim
  98. # for outside error handling, and returns the exit code
  99. # instead of the result dict.
  100. res_dict = ydl.extract_info(test_case['url'])
  101. except (DownloadError, ExtractorError) as err:
  102. # Check if the exception is not a network related one
  103. 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):
  104. raise
  105. if try_num == RETRIES:
  106. report_warning(u'Failed due to network errors, skipping...')
  107. return
  108. print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
  109. try_num += 1
  110. else:
  111. break
  112. if is_playlist:
  113. self.assertEqual(res_dict['_type'], 'playlist')
  114. expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
  115. if 'playlist_mincount' in test_case:
  116. assertGreaterEqual(
  117. self,
  118. len(res_dict['entries']),
  119. test_case['playlist_mincount'],
  120. 'Expected at least %d in playlist %s, but got only %d' % (
  121. test_case['playlist_mincount'], test_case['url'],
  122. len(res_dict['entries'])))
  123. if 'playlist_count' in test_case:
  124. self.assertEqual(
  125. len(res_dict['entries']),
  126. test_case['playlist_count'],
  127. 'Expected at %d in playlist %s, but got %d.')
  128. for tc in test_cases:
  129. tc_filename = get_tc_filename(tc)
  130. if not test_case.get('params', {}).get('skip_download', False):
  131. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  132. self.assertTrue(tc_filename in finished_hook_called)
  133. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  134. self.assertTrue(os.path.exists(info_json_fn))
  135. if 'md5' in tc:
  136. md5_for_file = _file_md5(tc_filename)
  137. self.assertEqual(md5_for_file, tc['md5'])
  138. with io.open(info_json_fn, encoding='utf-8') as infof:
  139. info_dict = json.load(infof)
  140. expect_info_dict(self, tc.get('info_dict', {}), info_dict)
  141. finally:
  142. try_rm_tcs_files()
  143. return test_template
  144. ### And add them to TestDownload
  145. for n, test_case in enumerate(defs):
  146. test_method = generator(test_case)
  147. tname = 'test_' + str(test_case['name'])
  148. i = 1
  149. while hasattr(TestDownload, tname):
  150. tname = 'test_' + str(test_case['name']) + '_' + str(i)
  151. i += 1
  152. test_method.__name__ = tname
  153. setattr(TestDownload, test_method.__name__, test_method)
  154. del test_method
  155. if __name__ == '__main__':
  156. unittest.main()