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.

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