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