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