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.

170 lines
6.1 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. get_testcases,
  10. global_setup,
  11. try_rm,
  12. md5,
  13. report_warning
  14. )
  15. global_setup()
  16. import hashlib
  17. import io
  18. import json
  19. import socket
  20. import youtube_dl.YoutubeDL
  21. from youtube_dl.utils import (
  22. compat_str,
  23. compat_urllib_error,
  24. compat_HTTPError,
  25. DownloadError,
  26. ExtractorError,
  27. UnavailableVideoError,
  28. )
  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 = get_testcases()
  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. 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. print_skipping('The output file cannot be know, the "file" '
  62. 'key is missing or the info_dict is incomplete')
  63. return
  64. if 'skip' in test_case:
  65. print_skipping(test_case['skip'])
  66. return
  67. params = get_params(test_case.get('params', {}))
  68. ydl = YoutubeDL(params)
  69. ydl.add_default_info_extractors()
  70. finished_hook_called = set()
  71. def _hook(status):
  72. if status['status'] == 'finished':
  73. finished_hook_called.add(status['filename'])
  74. ydl.fd.add_progress_hook(_hook)
  75. def get_tc_filename(tc):
  76. return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
  77. test_cases = test_case.get('playlist', [test_case])
  78. def try_rm_tcs_files():
  79. for tc in test_cases:
  80. tc_filename = get_tc_filename(tc)
  81. try_rm(tc_filename)
  82. try_rm(tc_filename + '.part')
  83. try_rm(tc_filename + '.info.json')
  84. try_rm_tcs_files()
  85. try:
  86. try_num = 1
  87. while True:
  88. try:
  89. ydl.download([test_case['url']])
  90. except (DownloadError, ExtractorError) as err:
  91. # Check if the exception is not a network related one
  92. if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError) or (err.exc_info[0] == compat_HTTPError and err.exc_info[1].code == 503):
  93. raise
  94. if try_num == RETRIES:
  95. report_warning(u'Failed due to network errors, skipping...')
  96. return
  97. print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
  98. try_num += 1
  99. else:
  100. break
  101. for tc in test_cases:
  102. tc_filename = get_tc_filename(tc)
  103. if not test_case.get('params', {}).get('skip_download', False):
  104. self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
  105. self.assertTrue(tc_filename in finished_hook_called)
  106. self.assertTrue(os.path.exists(tc_filename + '.info.json'))
  107. if 'md5' in tc:
  108. md5_for_file = _file_md5(tc_filename)
  109. self.assertEqual(md5_for_file, tc['md5'])
  110. with io.open(tc_filename + '.info.json', encoding='utf-8') as infof:
  111. info_dict = json.load(infof)
  112. for (info_field, expected) in tc.get('info_dict', {}).items():
  113. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  114. got = 'md5:' + md5(info_dict.get(info_field))
  115. else:
  116. got = info_dict.get(info_field)
  117. self.assertEqual(expected, got,
  118. u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
  119. # If checkable fields are missing from the test case, print the info_dict
  120. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  121. for key, value in info_dict.items()
  122. if value and key in ('title', 'description', 'uploader', 'upload_date', 'uploader_id', 'location'))
  123. if not all(key in tc.get('info_dict', {}).keys() for key in test_info_dict.keys()):
  124. sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=2) + u'\n')
  125. # Check for the presence of mandatory fields
  126. for key in ('id', 'url', 'title', 'ext'):
  127. self.assertTrue(key in info_dict.keys() and info_dict[key])
  128. finally:
  129. try_rm_tcs_files()
  130. return test_template
  131. ### And add them to TestDownload
  132. for n, test_case in enumerate(defs):
  133. test_method = generator(test_case)
  134. tname = 'test_' + str(test_case['name'])
  135. i = 1
  136. while hasattr(TestDownload, tname):
  137. tname = 'test_' + str(test_case['name']) + '_' + str(i)
  138. i += 1
  139. test_method.__name__ = tname
  140. setattr(TestDownload, test_method.__name__, test_method)
  141. del test_method
  142. if __name__ == '__main__':
  143. unittest.main()