helper.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. import errno
  2. import hashlib
  3. import json
  4. import os.path
  5. import re
  6. import ssl
  7. import sys
  8. import types
  9. import hypervideo_dl.extractor
  10. from hypervideo_dl import YoutubeDL
  11. from hypervideo_dl.compat import compat_os_name
  12. from hypervideo_dl.utils import preferredencoding, write_string
  13. if 'pytest' in sys.modules:
  14. import pytest
  15. is_download_test = pytest.mark.download
  16. else:
  17. def is_download_test(testClass):
  18. return testClass
  19. def get_params(override=None):
  20. PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  21. 'parameters.json')
  22. LOCAL_PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
  23. 'local_parameters.json')
  24. with open(PARAMETERS_FILE, encoding='utf-8') as pf:
  25. parameters = json.load(pf)
  26. if os.path.exists(LOCAL_PARAMETERS_FILE):
  27. with open(LOCAL_PARAMETERS_FILE, encoding='utf-8') as pf:
  28. parameters.update(json.load(pf))
  29. if override:
  30. parameters.update(override)
  31. return parameters
  32. def try_rm(filename):
  33. """ Remove a file if it exists """
  34. try:
  35. os.remove(filename)
  36. except OSError as ose:
  37. if ose.errno != errno.ENOENT:
  38. raise
  39. def report_warning(message, *args, **kwargs):
  40. '''
  41. Print the message to stderr, it will be prefixed with 'WARNING:'
  42. If stderr is a tty file the 'WARNING:' will be colored
  43. '''
  44. if sys.stderr.isatty() and compat_os_name != 'nt':
  45. _msg_header = '\033[0;33mWARNING:\033[0m'
  46. else:
  47. _msg_header = 'WARNING:'
  48. output = f'{_msg_header} {message}\n'
  49. if 'b' in getattr(sys.stderr, 'mode', ''):
  50. output = output.encode(preferredencoding())
  51. sys.stderr.write(output)
  52. class FakeYDL(YoutubeDL):
  53. def __init__(self, override=None):
  54. # Different instances of the downloader can't share the same dictionary
  55. # some test set the "sublang" parameter, which would break the md5 checks.
  56. params = get_params(override=override)
  57. super().__init__(params, auto_init=False)
  58. self.result = []
  59. def to_screen(self, s, *args, **kwargs):
  60. print(s)
  61. def trouble(self, s, *args, **kwargs):
  62. raise Exception(s)
  63. def download(self, x):
  64. self.result.append(x)
  65. def expect_warning(self, regex):
  66. # Silence an expected warning matching a regex
  67. old_report_warning = self.report_warning
  68. def report_warning(self, message, *args, **kwargs):
  69. if re.match(regex, message):
  70. return
  71. old_report_warning(message, *args, **kwargs)
  72. self.report_warning = types.MethodType(report_warning, self)
  73. def gettestcases(include_onlymatching=False):
  74. for ie in hypervideo_dl.extractor.gen_extractors():
  75. yield from ie.get_testcases(include_onlymatching)
  76. def getwebpagetestcases():
  77. for ie in hypervideo_dl.extractor.gen_extractors():
  78. for tc in ie.get_webpage_testcases():
  79. tc.setdefault('add_ie', []).append('Generic')
  80. yield tc
  81. md5 = lambda s: hashlib.md5(s.encode()).hexdigest()
  82. def expect_value(self, got, expected, field):
  83. if isinstance(expected, str) and expected.startswith('re:'):
  84. match_str = expected[len('re:'):]
  85. match_rex = re.compile(match_str)
  86. self.assertTrue(
  87. isinstance(got, str),
  88. f'Expected a {str.__name__} object, but got {type(got).__name__} for field {field}')
  89. self.assertTrue(
  90. match_rex.match(got),
  91. f'field {field} (value: {got!r}) should match {match_str!r}')
  92. elif isinstance(expected, str) and expected.startswith('startswith:'):
  93. start_str = expected[len('startswith:'):]
  94. self.assertTrue(
  95. isinstance(got, str),
  96. f'Expected a {str.__name__} object, but got {type(got).__name__} for field {field}')
  97. self.assertTrue(
  98. got.startswith(start_str),
  99. f'field {field} (value: {got!r}) should start with {start_str!r}')
  100. elif isinstance(expected, str) and expected.startswith('contains:'):
  101. contains_str = expected[len('contains:'):]
  102. self.assertTrue(
  103. isinstance(got, str),
  104. f'Expected a {str.__name__} object, but got {type(got).__name__} for field {field}')
  105. self.assertTrue(
  106. contains_str in got,
  107. f'field {field} (value: {got!r}) should contain {contains_str!r}')
  108. elif isinstance(expected, type):
  109. self.assertTrue(
  110. isinstance(got, expected),
  111. f'Expected type {expected!r} for field {field}, but got value {got!r} of type {type(got)!r}')
  112. elif isinstance(expected, dict) and isinstance(got, dict):
  113. expect_dict(self, got, expected)
  114. elif isinstance(expected, list) and isinstance(got, list):
  115. self.assertEqual(
  116. len(expected), len(got),
  117. 'Expect a list of length %d, but got a list of length %d for field %s' % (
  118. len(expected), len(got), field))
  119. for index, (item_got, item_expected) in enumerate(zip(got, expected)):
  120. type_got = type(item_got)
  121. type_expected = type(item_expected)
  122. self.assertEqual(
  123. type_expected, type_got,
  124. 'Type mismatch for list item at index %d for field %s, expected %r, got %r' % (
  125. index, field, type_expected, type_got))
  126. expect_value(self, item_got, item_expected, field)
  127. else:
  128. if isinstance(expected, str) and expected.startswith('md5:'):
  129. self.assertTrue(
  130. isinstance(got, str),
  131. f'Expected field {field} to be a unicode object, but got value {got!r} of type {type(got)!r}')
  132. got = 'md5:' + md5(got)
  133. elif isinstance(expected, str) and re.match(r'^(?:min|max)?count:\d+', expected):
  134. self.assertTrue(
  135. isinstance(got, (list, dict)),
  136. f'Expected field {field} to be a list or a dict, but it is of type {type(got).__name__}')
  137. op, _, expected_num = expected.partition(':')
  138. expected_num = int(expected_num)
  139. if op == 'mincount':
  140. assert_func = assertGreaterEqual
  141. msg_tmpl = 'Expected %d items in field %s, but only got %d'
  142. elif op == 'maxcount':
  143. assert_func = assertLessEqual
  144. msg_tmpl = 'Expected maximum %d items in field %s, but got %d'
  145. elif op == 'count':
  146. assert_func = assertEqual
  147. msg_tmpl = 'Expected exactly %d items in field %s, but got %d'
  148. else:
  149. assert False
  150. assert_func(
  151. self, len(got), expected_num,
  152. msg_tmpl % (expected_num, field, len(got)))
  153. return
  154. self.assertEqual(
  155. expected, got,
  156. f'Invalid value for field {field}, expected {expected!r}, got {got!r}')
  157. def expect_dict(self, got_dict, expected_dict):
  158. for info_field, expected in expected_dict.items():
  159. got = got_dict.get(info_field)
  160. expect_value(self, got, expected, info_field)
  161. def sanitize_got_info_dict(got_dict):
  162. IGNORED_FIELDS = (
  163. *YoutubeDL._format_fields,
  164. # Lists
  165. 'formats', 'thumbnails', 'subtitles', 'automatic_captions', 'comments', 'entries',
  166. # Auto-generated
  167. 'autonumber', 'playlist', 'format_index', 'video_ext', 'audio_ext', 'duration_string', 'epoch', 'n_entries',
  168. 'fulltitle', 'extractor', 'extractor_key', 'filename', 'filepath', 'infojson_filename', 'original_url',
  169. # Only live_status needs to be checked
  170. 'is_live', 'was_live',
  171. )
  172. IGNORED_PREFIXES = ('', 'playlist', 'requested', 'webpage')
  173. def sanitize(key, value):
  174. if isinstance(value, str) and len(value) > 100 and key != 'thumbnail':
  175. return f'md5:{md5(value)}'
  176. elif isinstance(value, list) and len(value) > 10:
  177. return f'count:{len(value)}'
  178. elif key.endswith('_count') and isinstance(value, int):
  179. return int
  180. return value
  181. test_info_dict = {
  182. key: sanitize(key, value) for key, value in got_dict.items()
  183. if value is not None and key not in IGNORED_FIELDS and not any(
  184. key.startswith(f'{prefix}_') for prefix in IGNORED_PREFIXES)
  185. }
  186. # display_id may be generated from id
  187. if test_info_dict.get('display_id') == test_info_dict.get('id'):
  188. test_info_dict.pop('display_id')
  189. # Check url for flat entries
  190. if got_dict.get('_type', 'video') != 'video' and got_dict.get('url'):
  191. test_info_dict['url'] = got_dict['url']
  192. return test_info_dict
  193. def expect_info_dict(self, got_dict, expected_dict):
  194. expect_dict(self, got_dict, expected_dict)
  195. # Check for the presence of mandatory fields
  196. if got_dict.get('_type') not in ('playlist', 'multi_video'):
  197. mandatory_fields = ['id', 'title']
  198. if expected_dict.get('ext'):
  199. mandatory_fields.extend(('url', 'ext'))
  200. for key in mandatory_fields:
  201. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  202. # Check for mandatory fields that are automatically set by YoutubeDL
  203. if got_dict.get('_type', 'video') == 'video':
  204. for key in ['webpage_url', 'extractor', 'extractor_key']:
  205. self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
  206. test_info_dict = sanitize_got_info_dict(got_dict)
  207. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  208. if missing_keys:
  209. def _repr(v):
  210. if isinstance(v, str):
  211. return "'%s'" % v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
  212. elif isinstance(v, type):
  213. return v.__name__
  214. else:
  215. return repr(v)
  216. info_dict_str = ''.join(
  217. f' {_repr(k)}: {_repr(v)},\n'
  218. for k, v in test_info_dict.items() if k not in missing_keys)
  219. if info_dict_str:
  220. info_dict_str += '\n'
  221. info_dict_str += ''.join(
  222. f' {_repr(k)}: {_repr(test_info_dict[k])},\n'
  223. for k in missing_keys)
  224. info_dict_str = '\n\'info_dict\': {\n' + info_dict_str + '},\n'
  225. write_string(info_dict_str.replace('\n', '\n '), out=sys.stderr)
  226. self.assertFalse(
  227. missing_keys,
  228. 'Missing keys in test definition: %s' % (
  229. ', '.join(sorted(missing_keys))))
  230. def assertRegexpMatches(self, text, regexp, msg=None):
  231. if hasattr(self, 'assertRegexp'):
  232. return self.assertRegexp(text, regexp, msg)
  233. else:
  234. m = re.match(regexp, text)
  235. if not m:
  236. note = 'Regexp didn\'t match: %r not found' % (regexp)
  237. if len(text) < 1000:
  238. note += ' in %r' % text
  239. if msg is None:
  240. msg = note
  241. else:
  242. msg = note + ', ' + msg
  243. self.assertTrue(m, msg)
  244. def assertGreaterEqual(self, got, expected, msg=None):
  245. if not (got >= expected):
  246. if msg is None:
  247. msg = f'{got!r} not greater than or equal to {expected!r}'
  248. self.assertTrue(got >= expected, msg)
  249. def assertLessEqual(self, got, expected, msg=None):
  250. if not (got <= expected):
  251. if msg is None:
  252. msg = f'{got!r} not less than or equal to {expected!r}'
  253. self.assertTrue(got <= expected, msg)
  254. def assertEqual(self, got, expected, msg=None):
  255. if not (got == expected):
  256. if msg is None:
  257. msg = f'{got!r} not equal to {expected!r}'
  258. self.assertTrue(got == expected, msg)
  259. def expect_warnings(ydl, warnings_re):
  260. real_warning = ydl.report_warning
  261. def _report_warning(w, *args, **kwargs):
  262. if not any(re.search(w_re, w) for w_re in warnings_re):
  263. real_warning(w, *args, **kwargs)
  264. ydl.report_warning = _report_warning
  265. def http_server_port(httpd):
  266. if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
  267. # In Jython SSLSocket is not a subclass of socket.socket
  268. sock = httpd.socket.sock
  269. else:
  270. sock = httpd.socket
  271. return sock.getsockname()[1]