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.

256 lines
9.6 KiB

12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
12 years ago
10 years ago
12 years ago
12 years ago
12 years ago
10 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 ssl
  10. import sys
  11. import youtube_dl.extractor
  12. from youtube_dl import YoutubeDL
  13. from youtube_dl.compat import (
  14. compat_os_name,
  15. compat_str,
  16. )
  17. from youtube_dl.utils import (
  18. preferredencoding,
  19. write_string,
  20. )
  21. def get_params(override=None):
  22. PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  23. "parameters.json")
  24. LOCAL_PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  25. "local_parameters.json")
  26. with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
  27. parameters = json.load(pf)
  28. if os.path.exists(LOCAL_PARAMETERS_FILE):
  29. with io.open(LOCAL_PARAMETERS_FILE, encoding='utf-8') as pf:
  30. parameters.update(json.load(pf))
  31. if override:
  32. parameters.update(override)
  33. return parameters
  34. def try_rm(filename):
  35. """ Remove a file if it exists """
  36. try:
  37. os.remove(filename)
  38. except OSError as ose:
  39. if ose.errno != errno.ENOENT:
  40. raise
  41. def report_warning(message):
  42. '''
  43. Print the message to stderr, it will be prefixed with 'WARNING:'
  44. If stderr is a tty file the 'WARNING:' will be colored
  45. '''
  46. if sys.stderr.isatty() and compat_os_name != 'nt':
  47. _msg_header = '\033[0;33mWARNING:\033[0m'
  48. else:
  49. _msg_header = 'WARNING:'
  50. output = '%s %s\n' % (_msg_header, message)
  51. if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
  52. output = output.encode(preferredencoding())
  53. sys.stderr.write(output)
  54. class FakeYDL(YoutubeDL):
  55. def __init__(self, override=None):
  56. # Different instances of the downloader can't share the same dictionary
  57. # some test set the "sublang" parameter, which would break the md5 checks.
  58. params = get_params(override=override)
  59. super(FakeYDL, self).__init__(params, auto_init=False)
  60. self.result = []
  61. def to_screen(self, s, skip_eol=None):
  62. print(s)
  63. def trouble(self, s, tb=None):
  64. raise Exception(s)
  65. def download(self, x):
  66. self.result.append(x)
  67. def expect_warning(self, regex):
  68. # Silence an expected warning matching a regex
  69. old_report_warning = self.report_warning
  70. def report_warning(self, message):
  71. if re.match(regex, message):
  72. return
  73. old_report_warning(message)
  74. self.report_warning = types.MethodType(report_warning, self)
  75. def gettestcases(include_onlymatching=False):
  76. for ie in youtube_dl.extractor.gen_extractors():
  77. for tc in ie.get_testcases(include_onlymatching):
  78. yield tc
  79. md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
  80. def expect_value(self, got, expected, field):
  81. if isinstance(expected, compat_str) and expected.startswith('re:'):
  82. match_str = expected[len('re:'):]
  83. match_rex = re.compile(match_str)
  84. self.assertTrue(
  85. isinstance(got, compat_str),
  86. 'Expected a %s object, but got %s for field %s' % (
  87. compat_str.__name__, type(got).__name__, field))
  88. self.assertTrue(
  89. match_rex.match(got),
  90. 'field %s (value: %r) should match %r' % (field, got, match_str))
  91. elif isinstance(expected, compat_str) and expected.startswith('startswith:'):
  92. start_str = expected[len('startswith:'):]
  93. self.assertTrue(
  94. isinstance(got, compat_str),
  95. 'Expected a %s object, but got %s for field %s' % (
  96. compat_str.__name__, type(got).__name__, field))
  97. self.assertTrue(
  98. got.startswith(start_str),
  99. 'field %s (value: %r) should start with %r' % (field, got, start_str))
  100. elif isinstance(expected, compat_str) and expected.startswith('contains:'):
  101. contains_str = expected[len('contains:'):]
  102. self.assertTrue(
  103. isinstance(got, compat_str),
  104. 'Expected a %s object, but got %s for field %s' % (
  105. compat_str.__name__, type(got).__name__, field))
  106. self.assertTrue(
  107. contains_str in got,
  108. 'field %s (value: %r) should contain %r' % (field, got, contains_str))
  109. elif isinstance(expected, type):
  110. self.assertTrue(
  111. isinstance(got, expected),
  112. 'Expected type %r for field %s, but got value %r of type %r' % (expected, field, got, type(got)))
  113. elif isinstance(expected, dict) and isinstance(got, dict):
  114. expect_dict(self, got, expected)
  115. elif isinstance(expected, list) and isinstance(got, list):
  116. self.assertEqual(
  117. len(expected), len(got),
  118. 'Expect a list of length %d, but got a list of length %d for field %s' % (
  119. len(expected), len(got), field))
  120. for index, (item_got, item_expected) in enumerate(zip(got, expected)):
  121. type_got = type(item_got)
  122. type_expected = type(item_expected)
  123. self.assertEqual(
  124. type_expected, type_got,
  125. 'Type mismatch for list item at index %d for field %s, expected %r, got %r' % (
  126. index, field, type_expected, type_got))
  127. expect_value(self, item_got, item_expected, field)
  128. else:
  129. if isinstance(expected, compat_str) and expected.startswith('md5:'):
  130. self.assertTrue(
  131. isinstance(got, compat_str),
  132. 'Expected field %s to be a unicode object, but got value %r of type %r' % (field, got, type(got)))
  133. got = 'md5:' + md5(got)
  134. elif isinstance(expected, compat_str) and expected.startswith('mincount:'):
  135. self.assertTrue(
  136. isinstance(got, (list, dict)),
  137. 'Expected field %s to be a list or a dict, but it is of type %s' % (
  138. field, type(got).__name__))
  139. expected_num = int(expected.partition(':')[2])
  140. assertGreaterEqual(
  141. self, len(got), expected_num,
  142. 'Expected %d items in field %s, but only got %d' % (expected_num, field, len(got)))
  143. return
  144. self.assertEqual(
  145. expected, got,
  146. 'Invalid value for field %s, expected %r, got %r' % (field, expected, got))
  147. def expect_dict(self, got_dict, expected_dict):
  148. for info_field, expected in expected_dict.items():
  149. got = got_dict.get(info_field)
  150. expect_value(self, got, expected, info_field)
  151. def expect_info_dict(self, got_dict, expected_dict):
  152. expect_dict(self, got_dict, expected_dict)
  153. # Check for the presence of mandatory fields
  154. if got_dict.get('_type') not in ('playlist', 'multi_video'):
  155. for key in ('id', 'url', 'title', 'ext'):
  156. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  157. # Check for mandatory fields that are automatically set by YoutubeDL
  158. for key in ['webpage_url', 'extractor', 'extractor_key']:
  159. self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
  160. # Are checkable fields missing from the test case definition?
  161. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  162. for key, value in got_dict.items()
  163. if value and key in ('id', 'title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location', 'age_limit'))
  164. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  165. if missing_keys:
  166. def _repr(v):
  167. if isinstance(v, compat_str):
  168. return "'%s'" % v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
  169. else:
  170. return repr(v)
  171. info_dict_str = ''
  172. if len(missing_keys) != len(expected_dict):
  173. info_dict_str += ''.join(
  174. ' %s: %s,\n' % (_repr(k), _repr(v))
  175. for k, v in test_info_dict.items() if k not in missing_keys)
  176. if info_dict_str:
  177. info_dict_str += '\n'
  178. info_dict_str += ''.join(
  179. ' %s: %s,\n' % (_repr(k), _repr(test_info_dict[k]))
  180. for k in missing_keys)
  181. write_string(
  182. '\n\'info_dict\': {\n' + info_dict_str + '},\n', out=sys.stderr)
  183. self.assertFalse(
  184. missing_keys,
  185. 'Missing keys in test definition: %s' % (
  186. ', '.join(sorted(missing_keys))))
  187. def assertRegexpMatches(self, text, regexp, msg=None):
  188. if hasattr(self, 'assertRegexp'):
  189. return self.assertRegexp(text, regexp, msg)
  190. else:
  191. m = re.match(regexp, text)
  192. if not m:
  193. note = 'Regexp didn\'t match: %r not found' % (regexp)
  194. if len(text) < 1000:
  195. note += ' in %r' % text
  196. if msg is None:
  197. msg = note
  198. else:
  199. msg = note + ', ' + msg
  200. self.assertTrue(m, msg)
  201. def assertGreaterEqual(self, got, expected, msg=None):
  202. if not (got >= expected):
  203. if msg is None:
  204. msg = '%r not greater than or equal to %r' % (got, expected)
  205. self.assertTrue(got >= expected, msg)
  206. def expect_warnings(ydl, warnings_re):
  207. real_warning = ydl.report_warning
  208. def _report_warning(w):
  209. if not any(re.search(w_re, w) for w_re in warnings_re):
  210. real_warning(w)
  211. ydl.report_warning = _report_warning
  212. def http_server_port(httpd):
  213. if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
  214. # In Jython SSLSocket is not a subclass of socket.socket
  215. sock = httpd.socket.sock
  216. else:
  217. sock = httpd.socket
  218. return sock.getsockname()[1]