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.

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