helper.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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 _iter_differences(got, expected, field):
  82. if isinstance(expected, str):
  83. op, _, val = expected.partition(':')
  84. if op in ('mincount', 'maxcount', 'count'):
  85. if not isinstance(got, (list, dict)):
  86. yield field, f'expected either {list.__name__} or {dict.__name__}, got {type(got).__name__}'
  87. return
  88. expected_num = int(val)
  89. got_num = len(got)
  90. if op == 'mincount':
  91. if got_num < expected_num:
  92. yield field, f'expected at least {val} items, got {got_num}'
  93. return
  94. if op == 'maxcount':
  95. if got_num > expected_num:
  96. yield field, f'expected at most {val} items, got {got_num}'
  97. return
  98. assert op == 'count'
  99. if got_num != expected_num:
  100. yield field, f'expected exactly {val} items, got {got_num}'
  101. return
  102. if not isinstance(got, str):
  103. yield field, f'expected {str.__name__}, got {type(got).__name__}'
  104. return
  105. if op == 're':
  106. if not re.match(val, got):
  107. yield field, f'should match {val!r}, got {got!r}'
  108. return
  109. if op == 'startswith':
  110. if not val.startswith(got):
  111. yield field, f'should start with {val!r}, got {got!r}'
  112. return
  113. if op == 'contains':
  114. if not val.startswith(got):
  115. yield field, f'should contain {val!r}, got {got!r}'
  116. return
  117. if op == 'md5':
  118. hash_val = md5(got)
  119. if hash_val != val:
  120. yield field, f'expected hash {val}, got {hash_val}'
  121. return
  122. if got != expected:
  123. yield field, f'expected {expected!r}, got {got!r}'
  124. return
  125. if isinstance(expected, dict) and isinstance(got, dict):
  126. for key, expected_val in expected.items():
  127. if key not in got:
  128. yield field, f'missing key: {key!r}'
  129. continue
  130. field_name = key if field is None else f'{field}.{key}'
  131. yield from _iter_differences(got[key], expected_val, field_name)
  132. return
  133. if isinstance(expected, type):
  134. if not isinstance(got, expected):
  135. yield field, f'expected {expected.__name__}, got {type(got).__name__}'
  136. return
  137. if isinstance(expected, list) and isinstance(got, list):
  138. # TODO: clever diffing algorithm lmao
  139. if len(expected) != len(got):
  140. yield field, f'expected length of {len(expected)}, got {len(got)}'
  141. return
  142. for index, (got_val, expected_val) in enumerate(zip(got, expected)):
  143. field_name = str(index) if field is None else f'{field}.{index}'
  144. yield from _iter_differences(got_val, expected_val, field_name)
  145. return
  146. if got != expected:
  147. yield field, f'expected {expected!r}, got {got!r}'
  148. def _expect_value(message, got, expected, field):
  149. mismatches = list(_iter_differences(got, expected, field))
  150. if not mismatches:
  151. return
  152. fields = [field for field, _ in mismatches if field is not None]
  153. return ''.join((
  154. message, f' ({", ".join(fields)})' if fields else '',
  155. *(f'\n\t{field}: {message}' for field, message in mismatches)))
  156. def expect_value(self, got, expected, field):
  157. if message := _expect_value('values differ', got, expected, field):
  158. self.fail(message)
  159. def expect_dict(self, got_dict, expected_dict):
  160. if message := _expect_value('dictionaries differ', got_dict, expected_dict, None):
  161. self.fail(message)
  162. def sanitize_got_info_dict(got_dict):
  163. IGNORED_FIELDS = (
  164. *YoutubeDL._format_fields,
  165. # Lists
  166. 'formats', 'thumbnails', 'subtitles', 'automatic_captions', 'comments', 'entries',
  167. # Auto-generated
  168. 'autonumber', 'playlist', 'format_index', 'video_ext', 'audio_ext', 'duration_string', 'epoch', 'n_entries',
  169. 'fulltitle', 'extractor', 'extractor_key', 'filename', 'filepath', 'infojson_filename', 'original_url',
  170. # Only live_status needs to be checked
  171. 'is_live', 'was_live',
  172. )
  173. IGNORED_PREFIXES = ('', 'playlist', 'requested', 'webpage')
  174. def sanitize(key, value):
  175. if isinstance(value, str) and len(value) > 100 and key != 'thumbnail':
  176. return f'md5:{md5(value)}'
  177. elif isinstance(value, list) and len(value) > 10:
  178. return f'count:{len(value)}'
  179. elif key.endswith('_count') and isinstance(value, int):
  180. return int
  181. return value
  182. test_info_dict = {
  183. key: sanitize(key, value) for key, value in got_dict.items()
  184. if value is not None and key not in IGNORED_FIELDS and (
  185. not any(key.startswith(f'{prefix}_') for prefix in IGNORED_PREFIXES)
  186. or key == '_old_archive_ids')
  187. }
  188. # display_id may be generated from id
  189. if test_info_dict.get('display_id') == test_info_dict.get('id'):
  190. test_info_dict.pop('display_id')
  191. # Remove deprecated fields
  192. for old in YoutubeDL._deprecated_multivalue_fields:
  193. test_info_dict.pop(old, None)
  194. # release_year may be generated from release_date
  195. if try_call(lambda: test_info_dict['release_year'] == int(test_info_dict['release_date'][:4])):
  196. test_info_dict.pop('release_year')
  197. # Check url for flat entries
  198. if got_dict.get('_type', 'video') != 'video' and got_dict.get('url'):
  199. test_info_dict['url'] = got_dict['url']
  200. return test_info_dict
  201. def expect_info_dict(self, got_dict, expected_dict):
  202. ALLOWED_KEYS_SORT_ORDER = (
  203. # NB: Keep in sync with the docstring of extractor/common.py
  204. 'id', 'ext', 'direct', 'display_id', 'title', 'alt_title', 'description', 'media_type',
  205. 'uploader', 'uploader_id', 'uploader_url', 'channel', 'channel_id', 'channel_url', 'channel_is_verified',
  206. 'channel_follower_count', 'comment_count', 'view_count', 'concurrent_view_count',
  207. 'like_count', 'dislike_count', 'repost_count', 'average_rating', 'age_limit', 'duration', 'thumbnail', 'heatmap',
  208. 'chapters', 'chapter', 'chapter_number', 'chapter_id', 'start_time', 'end_time', 'section_start', 'section_end',
  209. 'categories', 'tags', 'cast', 'composers', 'artists', 'album_artists', 'creators', 'genres',
  210. 'track', 'track_number', 'track_id', 'album', 'album_type', 'disc_number',
  211. 'series', 'series_id', 'season', 'season_number', 'season_id', 'episode', 'episode_number', 'episode_id',
  212. 'timestamp', 'upload_date', 'release_timestamp', 'release_date', 'release_year', 'modified_timestamp', 'modified_date',
  213. 'playable_in_embed', 'availability', 'live_status', 'location', 'license', '_old_archive_ids',
  214. )
  215. expect_dict(self, got_dict, expected_dict)
  216. # Check for the presence of mandatory fields
  217. if got_dict.get('_type') not in ('playlist', 'multi_video'):
  218. mandatory_fields = ['id', 'title']
  219. if expected_dict.get('ext'):
  220. mandatory_fields.extend(('url', 'ext'))
  221. for key in mandatory_fields:
  222. self.assertTrue(got_dict.get(key), f'Missing mandatory field {key}')
  223. # Check for mandatory fields that are automatically set by YoutubeDL
  224. if got_dict.get('_type', 'video') == 'video':
  225. for key in ['webpage_url', 'extractor', 'extractor_key']:
  226. self.assertTrue(got_dict.get(key), f'Missing field: {key}')
  227. test_info_dict = sanitize_got_info_dict(got_dict)
  228. # Check for invalid/misspelled field names being returned by the extractor
  229. invalid_keys = sorted(test_info_dict.keys() - ALLOWED_KEYS_SORT_ORDER)
  230. self.assertFalse(invalid_keys, f'Invalid fields returned by the extractor: {", ".join(invalid_keys)}')
  231. missing_keys = sorted(
  232. test_info_dict.keys() - expected_dict.keys(),
  233. key=lambda x: ALLOWED_KEYS_SORT_ORDER.index(x))
  234. if missing_keys:
  235. def _repr(v):
  236. if isinstance(v, str):
  237. return "'{}'".format(v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n'))
  238. elif isinstance(v, type):
  239. return v.__name__
  240. else:
  241. return repr(v)
  242. info_dict_str = ''.join(
  243. f' {_repr(k)}: {_repr(v)},\n'
  244. for k, v in test_info_dict.items() if k not in missing_keys)
  245. if info_dict_str:
  246. info_dict_str += '\n'
  247. info_dict_str += ''.join(
  248. f' {_repr(k)}: {_repr(test_info_dict[k])},\n'
  249. for k in missing_keys)
  250. info_dict_str = '\n\'info_dict\': {\n' + info_dict_str + '},\n'
  251. write_string(info_dict_str.replace('\n', '\n '), out=sys.stderr)
  252. self.assertFalse(
  253. missing_keys,
  254. 'Missing keys in test definition: {}'.format(', '.join(sorted(missing_keys))))
  255. def assertRegexpMatches(self, text, regexp, msg=None):
  256. if hasattr(self, 'assertRegexp'):
  257. return self.assertRegexp(text, regexp, msg)
  258. else:
  259. m = re.match(regexp, text)
  260. if not m:
  261. note = f'Regexp didn\'t match: {regexp!r} not found'
  262. if len(text) < 1000:
  263. note += f' in {text!r}'
  264. if msg is None:
  265. msg = note
  266. else:
  267. msg = note + ', ' + msg
  268. self.assertTrue(m, msg)
  269. def assertGreaterEqual(self, got, expected, msg=None):
  270. if not (got >= expected):
  271. if msg is None:
  272. msg = f'{got!r} not greater than or equal to {expected!r}'
  273. self.assertTrue(got >= expected, msg)
  274. def assertLessEqual(self, got, expected, msg=None):
  275. if not (got <= expected):
  276. if msg is None:
  277. msg = f'{got!r} not less than or equal to {expected!r}'
  278. self.assertTrue(got <= expected, msg)
  279. def assertEqual(self, got, expected, msg=None):
  280. if got != expected:
  281. if msg is None:
  282. msg = f'{got!r} not equal to {expected!r}'
  283. self.assertTrue(got == expected, msg)
  284. def expect_warnings(ydl, warnings_re):
  285. real_warning = ydl.report_warning
  286. def _report_warning(w, *args, **kwargs):
  287. if not any(re.search(w_re, w) for w_re in warnings_re):
  288. real_warning(w, *args, **kwargs)
  289. ydl.report_warning = _report_warning
  290. def http_server_port(httpd):
  291. if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
  292. # In Jython SSLSocket is not a subclass of socket.socket
  293. sock = httpd.socket.sock
  294. else:
  295. sock = httpd.socket
  296. return sock.getsockname()[1]
  297. def verify_address_availability(address):
  298. if find_available_port(address) is None:
  299. pytest.skip(f'Unable to bind to source address {address} (address may not exist)')
  300. def validate_and_send(rh, req):
  301. rh.validate(req)
  302. return rh.send(req)