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.

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