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.compat import compat_os_name
  12. from yt_dlp.utils import preferredencoding, try_call, write_string, find_available_port
  13. if 'pytest' in sys.modules:
  14. import pytest
  15. is_download_test = pytest.mark.download
  16. else:
  17. def is_download_test(test_class):
  18. return test_class
  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 yt_dlp.extractor.gen_extractors():
  75. yield from ie.get_testcases(include_onlymatching)
  76. def getwebpagetestcases():
  77. for ie in yt_dlp.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. f'Expect a list of length {len(expected)}, but got a list of length {len(got)} for field {field}')
  118. for index, (item_got, item_expected) in enumerate(zip(got, expected)):
  119. type_got = type(item_got)
  120. type_expected = type(item_expected)
  121. self.assertEqual(
  122. type_expected, type_got,
  123. f'Type mismatch for list item at index {index} for field {field}, '
  124. f'expected {type_expected!r}, got {type_got!r}')
  125. expect_value(self, item_got, item_expected, field)
  126. else:
  127. if isinstance(expected, str) and expected.startswith('md5:'):
  128. self.assertTrue(
  129. isinstance(got, str),
  130. f'Expected field {field} to be a unicode object, but got value {got!r} of type {type(got)!r}')
  131. got = 'md5:' + md5(got)
  132. elif isinstance(expected, str) and re.match(r'^(?:min|max)?count:\d+', expected):
  133. self.assertTrue(
  134. isinstance(got, (list, dict)),
  135. f'Expected field {field} to be a list or a dict, but it is of type {type(got).__name__}')
  136. op, _, expected_num = expected.partition(':')
  137. expected_num = int(expected_num)
  138. if op == 'mincount':
  139. assert_func = assertGreaterEqual
  140. msg_tmpl = 'Expected %d items in field %s, but only got %d'
  141. elif op == 'maxcount':
  142. assert_func = assertLessEqual
  143. msg_tmpl = 'Expected maximum %d items in field %s, but got %d'
  144. elif op == 'count':
  145. assert_func = assertEqual
  146. msg_tmpl = 'Expected exactly %d items in field %s, but got %d'
  147. else:
  148. assert False
  149. assert_func(
  150. self, len(got), expected_num,
  151. msg_tmpl % (expected_num, field, len(got)))
  152. return
  153. self.assertEqual(
  154. expected, got,
  155. f'Invalid value for field {field}, expected {expected!r}, got {got!r}')
  156. def expect_dict(self, got_dict, expected_dict):
  157. for info_field, expected in expected_dict.items():
  158. got = got_dict.get(info_field)
  159. expect_value(self, got, expected, info_field)
  160. def sanitize_got_info_dict(got_dict):
  161. IGNORED_FIELDS = (
  162. *YoutubeDL._format_fields,
  163. # Lists
  164. 'formats', 'thumbnails', 'subtitles', 'automatic_captions', 'comments', 'entries',
  165. # Auto-generated
  166. 'autonumber', 'playlist', 'format_index', 'video_ext', 'audio_ext', 'duration_string', 'epoch', 'n_entries',
  167. 'fulltitle', 'extractor', 'extractor_key', 'filename', 'filepath', 'infojson_filename', 'original_url',
  168. # Only live_status needs to be checked
  169. 'is_live', 'was_live',
  170. )
  171. IGNORED_PREFIXES = ('', 'playlist', 'requested', 'webpage')
  172. def sanitize(key, value):
  173. if isinstance(value, str) and len(value) > 100 and key != 'thumbnail':
  174. return f'md5:{md5(value)}'
  175. elif isinstance(value, list) and len(value) > 10:
  176. return f'count:{len(value)}'
  177. elif key.endswith('_count') and isinstance(value, int):
  178. return int
  179. return value
  180. test_info_dict = {
  181. key: sanitize(key, value) for key, value in got_dict.items()
  182. if value is not None and key not in IGNORED_FIELDS and (
  183. not any(key.startswith(f'{prefix}_') for prefix in IGNORED_PREFIXES)
  184. or key == '_old_archive_ids')
  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. # Remove deprecated fields
  190. for old in YoutubeDL._deprecated_multivalue_fields:
  191. test_info_dict.pop(old, None)
  192. # release_year may be generated from release_date
  193. if try_call(lambda: test_info_dict['release_year'] == int(test_info_dict['release_date'][:4])):
  194. test_info_dict.pop('release_year')
  195. # Check url for flat entries
  196. if got_dict.get('_type', 'video') != 'video' and got_dict.get('url'):
  197. test_info_dict['url'] = got_dict['url']
  198. return test_info_dict
  199. def expect_info_dict(self, got_dict, expected_dict):
  200. expect_dict(self, got_dict, expected_dict)
  201. # Check for the presence of mandatory fields
  202. if got_dict.get('_type') not in ('playlist', 'multi_video'):
  203. mandatory_fields = ['id', 'title']
  204. if expected_dict.get('ext'):
  205. mandatory_fields.extend(('url', 'ext'))
  206. for key in mandatory_fields:
  207. self.assertTrue(got_dict.get(key), f'Missing mandatory field {key}')
  208. # Check for mandatory fields that are automatically set by YoutubeDL
  209. if got_dict.get('_type', 'video') == 'video':
  210. for key in ['webpage_url', 'extractor', 'extractor_key']:
  211. self.assertTrue(got_dict.get(key), f'Missing field: {key}')
  212. test_info_dict = sanitize_got_info_dict(got_dict)
  213. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  214. if missing_keys:
  215. def _repr(v):
  216. if isinstance(v, str):
  217. return "'{}'".format(v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n'))
  218. elif isinstance(v, type):
  219. return v.__name__
  220. else:
  221. return repr(v)
  222. info_dict_str = ''.join(
  223. f' {_repr(k)}: {_repr(v)},\n'
  224. for k, v in test_info_dict.items() if k not in missing_keys)
  225. if info_dict_str:
  226. info_dict_str += '\n'
  227. info_dict_str += ''.join(
  228. f' {_repr(k)}: {_repr(test_info_dict[k])},\n'
  229. for k in missing_keys)
  230. info_dict_str = '\n\'info_dict\': {\n' + info_dict_str + '},\n'
  231. write_string(info_dict_str.replace('\n', '\n '), out=sys.stderr)
  232. self.assertFalse(
  233. missing_keys,
  234. 'Missing keys in test definition: {}'.format(', '.join(sorted(missing_keys))))
  235. def assertRegexpMatches(self, text, regexp, msg=None):
  236. if hasattr(self, 'assertRegexp'):
  237. return self.assertRegexp(text, regexp, msg)
  238. else:
  239. m = re.match(regexp, text)
  240. if not m:
  241. note = f'Regexp didn\'t match: {regexp!r} not found'
  242. if len(text) < 1000:
  243. note += f' in {text!r}'
  244. if msg is None:
  245. msg = note
  246. else:
  247. msg = note + ', ' + msg
  248. self.assertTrue(m, msg)
  249. def assertGreaterEqual(self, got, expected, msg=None):
  250. if not (got >= expected):
  251. if msg is None:
  252. msg = f'{got!r} not greater than or equal to {expected!r}'
  253. self.assertTrue(got >= expected, msg)
  254. def assertLessEqual(self, got, expected, msg=None):
  255. if not (got <= expected):
  256. if msg is None:
  257. msg = f'{got!r} not less than or equal to {expected!r}'
  258. self.assertTrue(got <= expected, msg)
  259. def assertEqual(self, got, expected, msg=None):
  260. if got != expected:
  261. if msg is None:
  262. msg = f'{got!r} not equal to {expected!r}'
  263. self.assertTrue(got == expected, msg)
  264. def expect_warnings(ydl, warnings_re):
  265. real_warning = ydl.report_warning
  266. def _report_warning(w, *args, **kwargs):
  267. if not any(re.search(w_re, w) for w_re in warnings_re):
  268. real_warning(w, *args, **kwargs)
  269. ydl.report_warning = _report_warning
  270. def http_server_port(httpd):
  271. if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
  272. # In Jython SSLSocket is not a subclass of socket.socket
  273. sock = httpd.socket.sock
  274. else:
  275. sock = httpd.socket
  276. return sock.getsockname()[1]
  277. def verify_address_availability(address):
  278. if find_available_port(address) is None:
  279. pytest.skip(f'Unable to bind to source address {address} (address may not exist)')
  280. def validate_and_send(rh, req):
  281. rh.validate(req)
  282. return rh.send(req)