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.

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