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.3 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. import errno
  2. import io
  3. import hashlib
  4. import json
  5. import os.path
  6. import re
  7. import types
  8. import sys
  9. import youtube_dl.extractor
  10. from youtube_dl import YoutubeDL
  11. from youtube_dl.utils import (
  12. compat_str,
  13. preferredencoding,
  14. )
  15. def get_params(override=None):
  16. PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  17. "parameters.json")
  18. with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
  19. parameters = json.load(pf)
  20. if override:
  21. parameters.update(override)
  22. return parameters
  23. def try_rm(filename):
  24. """ Remove a file if it exists """
  25. try:
  26. os.remove(filename)
  27. except OSError as ose:
  28. if ose.errno != errno.ENOENT:
  29. raise
  30. def report_warning(message):
  31. '''
  32. Print the message to stderr, it will be prefixed with 'WARNING:'
  33. If stderr is a tty file the 'WARNING:' will be colored
  34. '''
  35. if sys.stderr.isatty() and os.name != 'nt':
  36. _msg_header = u'\033[0;33mWARNING:\033[0m'
  37. else:
  38. _msg_header = u'WARNING:'
  39. output = u'%s %s\n' % (_msg_header, message)
  40. if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
  41. output = output.encode(preferredencoding())
  42. sys.stderr.write(output)
  43. class FakeYDL(YoutubeDL):
  44. def __init__(self, override=None):
  45. # Different instances of the downloader can't share the same dictionary
  46. # some test set the "sublang" parameter, which would break the md5 checks.
  47. params = get_params(override=override)
  48. super(FakeYDL, self).__init__(params)
  49. self.result = []
  50. def to_screen(self, s, skip_eol=None):
  51. print(s)
  52. def trouble(self, s, tb=None):
  53. raise Exception(s)
  54. def download(self, x):
  55. self.result.append(x)
  56. def expect_warning(self, regex):
  57. # Silence an expected warning matching a regex
  58. old_report_warning = self.report_warning
  59. def report_warning(self, message):
  60. if re.match(regex, message): return
  61. old_report_warning(message)
  62. self.report_warning = types.MethodType(report_warning, self)
  63. def gettestcases(include_onlymatching=False):
  64. for ie in youtube_dl.extractor.gen_extractors():
  65. t = getattr(ie, '_TEST', None)
  66. if t:
  67. assert not hasattr(ie, '_TESTS'), \
  68. '%s has _TEST and _TESTS' % type(ie).__name__
  69. tests = [t]
  70. else:
  71. tests = getattr(ie, '_TESTS', [])
  72. for t in tests:
  73. if not include_onlymatching and t.get('only_matching', False):
  74. continue
  75. t['name'] = type(ie).__name__[:-len('IE')]
  76. yield t
  77. md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
  78. def expect_info_dict(self, expected_dict, got_dict):
  79. for info_field, expected in expected_dict.items():
  80. if isinstance(expected, compat_str) and expected.startswith('re:'):
  81. got = got_dict.get(info_field)
  82. match_str = expected[len('re:'):]
  83. match_rex = re.compile(match_str)
  84. self.assertTrue(
  85. isinstance(got, compat_str) and match_rex.match(got),
  86. u'field %s (value: %r) should match %r' % (info_field, got, match_str))
  87. elif isinstance(expected, type):
  88. got = got_dict.get(info_field)
  89. self.assertTrue(isinstance(got, expected),
  90. u'Expected type %r for field %s, but got value %r of type %r' % (expected, info_field, got, type(got)))
  91. else:
  92. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  93. got = 'md5:' + md5(got_dict.get(info_field))
  94. else:
  95. got = got_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. # Check for the presence of mandatory fields
  99. for key in ('id', 'url', 'title', 'ext'):
  100. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  101. # Check for mandatory fields that are automatically set by YoutubeDL
  102. for key in ['webpage_url', 'extractor', 'extractor_key']:
  103. self.assertTrue(got_dict.get(key), u'Missing field: %s' % key)
  104. # Are checkable fields missing from the test case definition?
  105. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  106. for key, value in got_dict.items()
  107. if value and key in ('title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location'))
  108. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  109. if missing_keys:
  110. sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=4) + u'\n')
  111. self.assertFalse(
  112. missing_keys,
  113. 'Missing keys in test definition: %s' % (
  114. ', '.join(sorted(missing_keys))))
  115. def assertRegexpMatches(self, text, regexp, msg=None):
  116. if hasattr(self, 'assertRegexpMatches'):
  117. return self.assertRegexpMatches(text, regexp, msg)
  118. else:
  119. m = re.match(regexp, text)
  120. if not m:
  121. note = 'Regexp didn\'t match: %r not found in %r' % (regexp, text)
  122. if msg is None:
  123. msg = note
  124. else:
  125. msg = note + ', ' + msg
  126. self.assertTrue(m, msg)