helper.py 12 KB

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