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.

150 lines
5.4 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 get_params, get_testcases, global_setup, try_rm, md5
  8. global_setup()
  9. import hashlib
  10. import io
  11. import json
  12. import socket
  13. import youtube_dl.YoutubeDL
  14. from youtube_dl.utils import (
  15. compat_str,
  16. compat_urllib_error,
  17. DownloadError,
  18. ExtractorError,
  19. UnavailableVideoError,
  20. )
  21. RETRIES = 3
  22. class YoutubeDL(youtube_dl.YoutubeDL):
  23. def __init__(self, *args, **kwargs):
  24. self.to_stderr = self.to_screen
  25. self.processed_info_dicts = []
  26. super(YoutubeDL, self).__init__(*args, **kwargs)
  27. def report_warning(self, message):
  28. # Don't accept warnings during tests
  29. raise ExtractorError(message)
  30. def process_info(self, info_dict):
  31. self.processed_info_dicts.append(info_dict)
  32. return super(YoutubeDL, self).process_info(info_dict)
  33. def _file_md5(fn):
  34. with open(fn, 'rb') as f:
  35. return hashlib.md5(f.read()).hexdigest()
  36. defs = get_testcases()
  37. class TestDownload(unittest.TestCase):
  38. maxDiff = None
  39. def setUp(self):
  40. self.defs = defs
  41. ### Dynamically generate tests
  42. def generator(test_case):
  43. def test_template(self):
  44. ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
  45. def print_skipping(reason):
  46. print('Skipping %s: %s' % (test_case['name'], reason))
  47. if not ie._WORKING:
  48. print_skipping('IE marked as not _WORKING')
  49. return
  50. if 'playlist' not in test_case and not test_case['file']:
  51. print_skipping('No output file specified')
  52. return
  53. if 'skip' in test_case:
  54. print_skipping(test_case['skip'])
  55. return
  56. params = get_params(test_case.get('params', {}))
  57. ydl = YoutubeDL(params)
  58. ydl.add_default_info_extractors()
  59. finished_hook_called = set()
  60. def _hook(status):
  61. if status['status'] == 'finished':
  62. finished_hook_called.add(status['filename'])
  63. ydl.fd.add_progress_hook(_hook)
  64. test_cases = test_case.get('playlist', [test_case])
  65. for tc in test_cases:
  66. try_rm(tc['file'])
  67. try_rm(tc['file'] + '.part')
  68. try_rm(tc['file'] + '.info.json')
  69. try:
  70. for retry in range(1, RETRIES + 1):
  71. try:
  72. ydl.download([test_case['url']])
  73. except (DownloadError, ExtractorError) as err:
  74. if retry == RETRIES: raise
  75. # Check if the exception is not a network related one
  76. if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
  77. raise
  78. print('Retrying: {0} failed tries\n\n##########\n\n'.format(retry))
  79. else:
  80. break
  81. for tc in test_cases:
  82. if not test_case.get('params', {}).get('skip_download', False):
  83. self.assertTrue(os.path.exists(tc['file']), msg='Missing file ' + tc['file'])
  84. self.assertTrue(tc['file'] in finished_hook_called)
  85. self.assertTrue(os.path.exists(tc['file'] + '.info.json'))
  86. if 'md5' in tc:
  87. md5_for_file = _file_md5(tc['file'])
  88. self.assertEqual(md5_for_file, tc['md5'])
  89. with io.open(tc['file'] + '.info.json', encoding='utf-8') as infof:
  90. info_dict = json.load(infof)
  91. for (info_field, expected) in tc.get('info_dict', {}).items():
  92. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  93. got = 'md5:' + md5(info_dict.get(info_field))
  94. else:
  95. got = info_dict.get(info_field)
  96. self.assertEqual(expected, got,
  97. u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
  98. # If checkable fields are missing from the test case, print the info_dict
  99. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  100. for key, value in info_dict.items()
  101. if value and key in ('title', 'description', 'uploader', 'upload_date', 'uploader_id', 'location'))
  102. if not all(key in tc.get('info_dict', {}).keys() for key in test_info_dict.keys()):
  103. sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=2) + u'\n')
  104. # Check for the presence of mandatory fields
  105. for key in ('id', 'url', 'title', 'ext'):
  106. self.assertTrue(key in info_dict.keys() and info_dict[key])
  107. finally:
  108. for tc in test_cases:
  109. try_rm(tc['file'])
  110. try_rm(tc['file'] + '.part')
  111. try_rm(tc['file'] + '.info.json')
  112. return test_template
  113. ### And add them to TestDownload
  114. for n, test_case in enumerate(defs):
  115. test_method = generator(test_case)
  116. tname = 'test_' + str(test_case['name'])
  117. i = 1
  118. while hasattr(TestDownload, tname):
  119. tname = 'test_' + str(test_case['name']) + '_' + str(i)
  120. i += 1
  121. test_method.__name__ = tname
  122. setattr(TestDownload, test_method.__name__, test_method)
  123. del test_method
  124. if __name__ == '__main__':
  125. unittest.main()