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.

162 lines
5.8 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 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),
  86. u'Expected a %s object, but got %s for field %s' % (
  87. compat_str.__name__, type(got).__name__, info_field))
  88. self.assertTrue(
  89. match_rex.match(got),
  90. u'field %s (value: %r) should match %r' % (info_field, got, match_str))
  91. elif isinstance(expected, type):
  92. got = got_dict.get(info_field)
  93. self.assertTrue(isinstance(got, expected),
  94. u'Expected type %r for field %s, but got value %r of type %r' % (expected, info_field, got, type(got)))
  95. else:
  96. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  97. got = 'md5:' + md5(got_dict.get(info_field))
  98. else:
  99. got = got_dict.get(info_field)
  100. self.assertEqual(expected, got,
  101. u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
  102. # Check for the presence of mandatory fields
  103. if got_dict.get('_type') != 'playlist':
  104. for key in ('id', 'url', 'title', 'ext'):
  105. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  106. # Check for mandatory fields that are automatically set by YoutubeDL
  107. for key in ['webpage_url', 'extractor', 'extractor_key']:
  108. self.assertTrue(got_dict.get(key), u'Missing field: %s' % key)
  109. # Are checkable fields missing from the test case definition?
  110. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  111. for key, value in got_dict.items()
  112. if value and key in ('title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location'))
  113. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  114. if missing_keys:
  115. sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=4) + u'\n')
  116. self.assertFalse(
  117. missing_keys,
  118. 'Missing keys in test definition: %s' % (
  119. ', '.join(sorted(missing_keys))))
  120. def assertRegexpMatches(self, text, regexp, msg=None):
  121. if hasattr(self, 'assertRegexp'):
  122. return self.assertRegexp(text, regexp, msg)
  123. else:
  124. m = re.match(regexp, text)
  125. if not m:
  126. note = 'Regexp didn\'t match: %r not found in %r' % (regexp, text)
  127. if msg is None:
  128. msg = note
  129. else:
  130. msg = note + ', ' + msg
  131. self.assertTrue(m, msg)
  132. def assertGreaterEqual(self, got, expected, msg=None):
  133. if not (got >= expected):
  134. if msg is None:
  135. msg = '%r not greater than or equal to %r' % (got, expected)
  136. self.assertTrue(got >= expected, msg)