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.

159 lines
5.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. md5,
  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_str,
  23. compat_urllib_error,
  24. compat_HTTPError,
  25. DownloadError,
  26. ExtractorError,
  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. def print_skipping(reason):
  56. print('Skipping %s: %s' % (test_case['name'], reason))
  57. if not ie.working():
  58. print_skipping('IE marked as not _WORKING')
  59. return
  60. if 'playlist' not in test_case:
  61. info_dict = test_case.get('info_dict', {})
  62. if not test_case.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
  63. raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
  64. if 'skip' in test_case:
  65. print_skipping(test_case['skip'])
  66. return
  67. for other_ie in other_ies:
  68. if not other_ie.working():
  69. print_skipping(u'test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
  70. return
  71. params = get_params(test_case.get('params', {}))
  72. ydl = YoutubeDL(params)
  73. ydl.add_default_info_extractors()
  74. finished_hook_called = set()
  75. def _hook(status):
  76. if status['status'] == 'finished':
  77. finished_hook_called.add(status['filename'])
  78. ydl.add_progress_hook(_hook)
  79. def get_tc_filename(tc):
  80. return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
  81. test_cases = test_case.get('playlist', [test_case])
  82. def try_rm_tcs_files():
  83. for tc in test_cases:
  84. tc_filename = get_tc_filename(tc)
  85. try_rm(tc_filename)
  86. try_rm(tc_filename + '.part')
  87. try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
  88. try_rm_tcs_files()
  89. try:
  90. try_num = 1
  91. while True:
  92. try:
  93. ydl.download([test_case['url']])
  94. except (DownloadError, ExtractorError) as err:
  95. # Check if the exception is not a network related one
  96. 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):
  97. raise
  98. if try_num == RETRIES:
  99. report_warning(u'Failed due to network errors, skipping...')
  100. return
  101. print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
  102. try_num += 1
  103. else:
  104. break
  105. for tc in test_cases:
  106. tc_filename = get_tc_filename(tc)
  107. if not test_case.get('params', {}).get('skip_download', False):
  108. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  109. self.assertTrue(tc_filename in finished_hook_called)
  110. info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
  111. self.assertTrue(os.path.exists(info_json_fn))
  112. if 'md5' in tc:
  113. md5_for_file = _file_md5(tc_filename)
  114. self.assertEqual(md5_for_file, tc['md5'])
  115. with io.open(info_json_fn, encoding='utf-8') as infof:
  116. info_dict = json.load(infof)
  117. expect_info_dict(self, tc.get('info_dict', {}), info_dict)
  118. finally:
  119. try_rm_tcs_files()
  120. return test_template
  121. ### And add them to TestDownload
  122. for n, test_case in enumerate(defs):
  123. test_method = generator(test_case)
  124. tname = 'test_' + str(test_case['name'])
  125. i = 1
  126. while hasattr(TestDownload, tname):
  127. tname = 'test_' + str(test_case['name']) + '_' + str(i)
  128. i += 1
  129. test_method.__name__ = tname
  130. setattr(TestDownload, test_method.__name__, test_method)
  131. del test_method
  132. if __name__ == '__main__':
  133. unittest.main()