helper.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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(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 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. '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 (
  184. not any(key.startswith(f'{prefix}_') for prefix in IGNORED_PREFIXES)
  185. or key == '_old_archive_ids')
  186. }
  187. # display_id may be generated from id
  188. if test_info_dict.get('display_id') == test_info_dict.get('id'):
  189. test_info_dict.pop('display_id')
  190. # Remove deprecated fields
  191. for old in YoutubeDL._deprecated_multivalue_fields.keys():
  192. test_info_dict.pop(old, None)
  193. # release_year may be generated from release_date
  194. if try_call(lambda: test_info_dict['release_year'] == int(test_info_dict['release_date'][:4])):
  195. test_info_dict.pop('release_year')
  196. # Check url for flat entries
  197. if got_dict.get('_type', 'video') != 'video' and got_dict.get('url'):
  198. test_info_dict['url'] = got_dict['url']
  199. return test_info_dict
  200. def expect_info_dict(self, got_dict, expected_dict):
  201. expect_dict(self, got_dict, expected_dict)
  202. # Check for the presence of mandatory fields
  203. if got_dict.get('_type') not in ('playlist', 'multi_video'):
  204. mandatory_fields = ['id', 'title']
  205. if expected_dict.get('ext'):
  206. mandatory_fields.extend(('url', 'ext'))
  207. for key in mandatory_fields:
  208. self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
  209. # Check for mandatory fields that are automatically set by YoutubeDL
  210. if got_dict.get('_type', 'video') == 'video':
  211. for key in ['webpage_url', 'extractor', 'extractor_key']:
  212. self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
  213. test_info_dict = sanitize_got_info_dict(got_dict)
  214. missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
  215. if missing_keys:
  216. def _repr(v):
  217. if isinstance(v, str):
  218. return "'%s'" % v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
  219. elif isinstance(v, type):
  220. return v.__name__
  221. else:
  222. return repr(v)
  223. info_dict_str = ''.join(
  224. f' {_repr(k)}: {_repr(v)},\n'
  225. for k, v in test_info_dict.items() if k not in missing_keys)
  226. if info_dict_str:
  227. info_dict_str += '\n'
  228. info_dict_str += ''.join(
  229. f' {_repr(k)}: {_repr(test_info_dict[k])},\n'
  230. for k in missing_keys)
  231. info_dict_str = '\n\'info_dict\': {\n' + info_dict_str + '},\n'
  232. write_string(info_dict_str.replace('\n', '\n '), out=sys.stderr)
  233. self.assertFalse(
  234. missing_keys,
  235. 'Missing keys in test definition: %s' % (
  236. ', '.join(sorted(missing_keys))))
  237. def assertRegexpMatches(self, text, regexp, msg=None):
  238. if hasattr(self, 'assertRegexp'):
  239. return self.assertRegexp(text, regexp, msg)
  240. else:
  241. m = re.match(regexp, text)
  242. if not m:
  243. note = 'Regexp didn\'t match: %r not found' % (regexp)
  244. if len(text) < 1000:
  245. note += ' in %r' % text
  246. if msg is None:
  247. msg = note
  248. else:
  249. msg = note + ', ' + msg
  250. self.assertTrue(m, msg)
  251. def assertGreaterEqual(self, got, expected, msg=None):
  252. if not (got >= expected):
  253. if msg is None:
  254. msg = f'{got!r} not greater than or equal to {expected!r}'
  255. self.assertTrue(got >= expected, msg)
  256. def assertLessEqual(self, got, expected, msg=None):
  257. if not (got <= expected):
  258. if msg is None:
  259. msg = f'{got!r} not less than or equal to {expected!r}'
  260. self.assertTrue(got <= expected, msg)
  261. def assertEqual(self, got, expected, msg=None):
  262. if not (got == expected):
  263. if msg is None:
  264. msg = f'{got!r} not equal to {expected!r}'
  265. self.assertTrue(got == expected, msg)
  266. def expect_warnings(ydl, warnings_re):
  267. real_warning = ydl.report_warning
  268. def _report_warning(w, *args, **kwargs):
  269. if not any(re.search(w_re, w) for w_re in warnings_re):
  270. real_warning(w, *args, **kwargs)
  271. ydl.report_warning = _report_warning
  272. def http_server_port(httpd):
  273. if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
  274. # In Jython SSLSocket is not a subclass of socket.socket
  275. sock = httpd.socket.sock
  276. else:
  277. sock = httpd.socket
  278. return sock.getsockname()[1]
  279. def verify_address_availability(address):
  280. if find_available_port(address) is None:
  281. pytest.skip(f'Unable to bind to source address {address} (address may not exist)')