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.

282 lines
10 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
11 years ago
11 years ago
11 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 re.match(r'^(?:min|max)?count:\d+', expected):
  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. op, _, expected_num = expected.partition(':')
  140. expected_num = int(expected_num)
  141. if op == 'mincount':
  142. assert_func = assertGreaterEqual
  143. msg_tmpl = 'Expected %d items in field %s, but only got %d'
  144. elif op == 'maxcount':
  145. assert_func = assertLessEqual
  146. msg_tmpl = 'Expected maximum %d items in field %s, but got %d'
  147. elif op == 'count':
  148. assert_func = assertEqual
  149. msg_tmpl = 'Expected exactly %d items in field %s, but got %d'
  150. else:
  151. assert False
  152. assert_func(
  153. self, len(got), expected_num,
  154. msg_tmpl % (expected_num, field, len(got)))
  155. return
  156. self.assertEqual(
  157. expected, got,
  158. 'Invalid value for field %s, expected %r, got %r' % (field, expected, got))
  159. def expect_dict(self, got_dict, expected_dict):
  160. for info_field, expected in expected_dict.items():
  161. got = got_dict.get(info_field)
  162. expect_value(self, got, expected, info_field)
  163. def expect_info_dict(self, got_dict, expected_dict):
  164. expect_dict(self, got_dict, expected_dict)
  165. # Check for the presence of mandatory fields
  166. if got_dict.get('_type') not in ('playlist', 'multi_video'):
  167. for key in ('id', 'url', 'title', 'ext'):
  168. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  169. # Check for mandatory fields that are automatically set by YoutubeDL
  170. for key in ['webpage_url', 'extractor', 'extractor_key']:
  171. self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
  172. # Are checkable fields missing from the test case definition?
  173. test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
  174. for key, value in got_dict.items()
  175. if value and key in ('id', 'title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location', 'age_limit'))
  176. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  177. if missing_keys:
  178. def _repr(v):
  179. if isinstance(v, compat_str):
  180. return "'%s'" % v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
  181. else:
  182. return repr(v)
  183. info_dict_str = ''
  184. if len(missing_keys) != len(expected_dict):
  185. info_dict_str += ''.join(
  186. ' %s: %s,\n' % (_repr(k), _repr(v))
  187. for k, v in test_info_dict.items() if k not in missing_keys)
  188. if info_dict_str:
  189. info_dict_str += '\n'
  190. info_dict_str += ''.join(
  191. ' %s: %s,\n' % (_repr(k), _repr(test_info_dict[k]))
  192. for k in missing_keys)
  193. write_string(
  194. '\n\'info_dict\': {\n' + info_dict_str + '},\n', out=sys.stderr)
  195. self.assertFalse(
  196. missing_keys,
  197. 'Missing keys in test definition: %s' % (
  198. ', '.join(sorted(missing_keys))))
  199. def assertRegexpMatches(self, text, regexp, msg=None):
  200. if hasattr(self, 'assertRegexp'):
  201. return self.assertRegexp(text, regexp, msg)
  202. else:
  203. m = re.match(regexp, text)
  204. if not m:
  205. note = 'Regexp didn\'t match: %r not found' % (regexp)
  206. if len(text) < 1000:
  207. note += ' in %r' % text
  208. if msg is None:
  209. msg = note
  210. else:
  211. msg = note + ', ' + msg
  212. self.assertTrue(m, msg)
  213. def assertGreaterEqual(self, got, expected, msg=None):
  214. if not (got >= expected):
  215. if msg is None:
  216. msg = '%r not greater than or equal to %r' % (got, expected)
  217. self.assertTrue(got >= expected, msg)
  218. def assertLessEqual(self, got, expected, msg=None):
  219. if not (got <= expected):
  220. if msg is None:
  221. msg = '%r not less than or equal to %r' % (got, expected)
  222. self.assertTrue(got <= expected, msg)
  223. def assertEqual(self, got, expected, msg=None):
  224. if not (got == expected):
  225. if msg is None:
  226. msg = '%r not equal to %r' % (got, expected)
  227. self.assertTrue(got == expected, msg)
  228. def expect_warnings(ydl, warnings_re):
  229. real_warning = ydl.report_warning
  230. def _report_warning(w):
  231. if not any(re.search(w_re, w) for w_re in warnings_re):
  232. real_warning(w)
  233. ydl.report_warning = _report_warning
  234. def http_server_port(httpd):
  235. if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
  236. # In Jython SSLSocket is not a subclass of socket.socket
  237. sock = httpd.socket.sock
  238. else:
  239. sock = httpd.socket
  240. return sock.getsockname()[1]