]> jfr.im git - yt-dlp.git/blame - test/helper.py
[toggo] Improve `_VALID_URL` (#3689)
[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
f8271158 12from yt_dlp.compat import compat_os_name, compat_str
13from yt_dlp.utils import preferredencoding, write_string
112da0a0 14
b5ae35ee 15if 'pytest' in sys.modules:
060ac762 16 import pytest
17 is_download_test = pytest.mark.download
18else:
19 def is_download_test(testClass):
20 return testClass
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
dd508b7c
FV
47def report_warning(message):
48 '''
49 Print the message to stderr, it will be prefixed with 'WARNING:'
50 If stderr is a tty file the 'WARNING:' will be colored
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
f4aac741 70 def to_screen(self, s, skip_eol=None):
112da0a0 71 print(s)
f4aac741 72
112da0a0
PH
73 def trouble(self, s, tb=None):
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
00fcc17a 83 def report_warning(self, message):
5f6a1245
JW
84 if re.match(regex, message):
85 return
00fcc17a
FV
86 old_report_warning(message)
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
95md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
257cfebf
PH
96
97
40c931de
QF
98def expect_value(self, got, expected, field):
99 if isinstance(expected, compat_str) and expected.startswith('re:'):
100 match_str = expected[len('re:'):]
101 match_rex = re.compile(match_str)
102
103 self.assertTrue(
104 isinstance(got, compat_str),
86e5f3ed 105 f'Expected a {compat_str.__name__} object, but got {type(got).__name__} for field {field}')
40c931de
QF
106 self.assertTrue(
107 match_rex.match(got),
86e5f3ed 108 f'field {field} (value: {got!r}) should match {match_str!r}')
40c931de
QF
109 elif isinstance(expected, compat_str) and expected.startswith('startswith:'):
110 start_str = expected[len('startswith:'):]
111 self.assertTrue(
112 isinstance(got, compat_str),
86e5f3ed 113 f'Expected a {compat_str.__name__} object, but got {type(got).__name__} for field {field}')
40c931de
QF
114 self.assertTrue(
115 got.startswith(start_str),
86e5f3ed 116 f'field {field} (value: {got!r}) should start with {start_str!r}')
40c931de
QF
117 elif isinstance(expected, compat_str) and expected.startswith('contains:'):
118 contains_str = expected[len('contains:'):]
119 self.assertTrue(
120 isinstance(got, compat_str),
86e5f3ed 121 f'Expected a {compat_str.__name__} object, but got {type(got).__name__} for field {field}')
40c931de
QF
122 self.assertTrue(
123 contains_str in got,
86e5f3ed 124 f'field {field} (value: {got!r}) should contain {contains_str!r}')
40c931de 125 elif isinstance(expected, type):
2e885de7
S
126 self.assertTrue(
127 isinstance(got, expected),
86e5f3ed 128 f'Expected type {expected!r} for field {field}, but got value {got!r} of type {type(got)!r}')
40c931de
QF
129 elif isinstance(expected, dict) and isinstance(got, dict):
130 expect_dict(self, got, expected)
131 elif isinstance(expected, list) and isinstance(got, list):
2e885de7
S
132 self.assertEqual(
133 len(expected), len(got),
f88f1b40
S
134 'Expect a list of length %d, but got a list of length %d for field %s' % (
135 len(expected), len(got), field))
687c04cb
QF
136 for index, (item_got, item_expected) in enumerate(zip(got, expected)):
137 type_got = type(item_got)
138 type_expected = type(item_expected)
2e885de7
S
139 self.assertEqual(
140 type_expected, type_got,
386a7b52 141 'Type mismatch for list item at index %d for field %s, expected %r, got %r' % (
7d0ada5f 142 index, field, type_expected, type_got))
687c04cb 143 expect_value(self, item_got, item_expected, field)
40c931de
QF
144 else:
145 if isinstance(expected, compat_str) and expected.startswith('md5:'):
6c4c7539
YCH
146 self.assertTrue(
147 isinstance(got, compat_str),
86e5f3ed 148 f'Expected field {field} to be a unicode object, but got value {got!r} of type {type(got)!r}')
40c931de 149 got = 'md5:' + md5(got)
a16c7c03 150 elif isinstance(expected, compat_str) and re.match(r'^(?:min|max)?count:\d+', expected):
9789d753 151 self.assertTrue(
40c931de 152 isinstance(got, (list, dict)),
86e5f3ed 153 f'Expected field {field} to be a list or a dict, but it is of type {type(got).__name__}')
a16c7c03
S
154 op, _, expected_num = expected.partition(':')
155 expected_num = int(expected_num)
156 if op == 'mincount':
157 assert_func = assertGreaterEqual
158 msg_tmpl = 'Expected %d items in field %s, but only got %d'
159 elif op == 'maxcount':
160 assert_func = assertLessEqual
161 msg_tmpl = 'Expected maximum %d items in field %s, but got %d'
162 elif op == 'count':
163 assert_func = assertEqual
164 msg_tmpl = 'Expected exactly %d items in field %s, but got %d'
165 else:
166 assert False
167 assert_func(
40c931de 168 self, len(got), expected_num,
a16c7c03 169 msg_tmpl % (expected_num, field, len(got)))
40c931de 170 return
2e885de7
S
171 self.assertEqual(
172 expected, got,
86e5f3ed 173 f'Invalid value for field {field}, expected {expected!r}, got {got!r}')
40c931de
QF
174
175
176def expect_dict(self, got_dict, expected_dict):
177 for info_field, expected in expected_dict.items():
178 got = got_dict.get(info_field)
179 expect_value(self, got, expected, info_field)
257cfebf 180
93bc7ef1 181
75ad3357 182def sanitize_got_info_dict(got_dict):
183 IGNORED_FIELDS = (
6db9c4d5 184 *YoutubeDL._format_fields,
ff9f925b 185
186 # Lists
187 'formats', 'thumbnails', 'subtitles', 'automatic_captions', 'comments', 'entries',
188
189 # Auto-generated
75ad3357 190 'autonumber', 'playlist', 'format_index', 'video_ext', 'audio_ext', 'duration_string', 'epoch',
497d77e1 191 'fulltitle', 'extractor', 'extractor_key', 'filepath', 'infojson_filename', 'original_url', 'n_entries',
ff9f925b 192
193 # Only live_status needs to be checked
194 'is_live', 'was_live',
195 )
196
75ad3357 197 IGNORED_PREFIXES = ('', 'playlist', 'requested', 'webpage')
ff9f925b 198
199 def sanitize(key, value):
88f23a18 200 if isinstance(value, str) and len(value) > 100 and key != 'thumbnail':
ff9f925b 201 return f'md5:{md5(value)}'
202 elif isinstance(value, list) and len(value) > 10:
203 return f'count:{len(value)}'
976ae3ea 204 elif key.endswith('_count') and isinstance(value, int):
205 return int
ff9f925b 206 return value
207
208 test_info_dict = {
209 key: sanitize(key, value) for key, value in got_dict.items()
75ad3357 210 if value is not None and key not in IGNORED_FIELDS and not any(
211 key.startswith(f'{prefix}_') for prefix in IGNORED_PREFIXES)
ff9f925b 212 }
213
214 # display_id may be generated from id
6970b600 215 if test_info_dict.get('display_id') == test_info_dict.get('id'):
ff9f925b 216 test_info_dict.pop('display_id')
217
75ad3357 218 return test_info_dict
219
220
221def expect_info_dict(self, got_dict, expected_dict):
222 expect_dict(self, got_dict, expected_dict)
223 # Check for the presence of mandatory fields
224 if got_dict.get('_type') not in ('playlist', 'multi_video'):
225 mandatory_fields = ['id', 'title']
226 if expected_dict.get('ext'):
227 mandatory_fields.extend(('url', 'ext'))
228 for key in mandatory_fields:
229 self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
230 # Check for mandatory fields that are automatically set by YoutubeDL
231 for key in ['webpage_url', 'extractor', 'extractor_key']:
232 self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
233
234 test_info_dict = sanitize_got_info_dict(got_dict)
235
ea38e55f
PH
236 missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
237 if missing_keys:
c0f64ac6
PH
238 def _repr(v):
239 if isinstance(v, compat_str):
155f9550 240 return "'%s'" % v.replace('\\', '\\\\').replace("'", "\\'").replace('\n', '\\n')
976ae3ea 241 elif isinstance(v, type):
242 return v.__name__
c0f64ac6
PH
243 else:
244 return repr(v)
dc35bfd2
PH
245 info_dict_str = ''
246 if len(missing_keys) != len(expected_dict):
247 info_dict_str += ''.join(
86e5f3ed 248 f' {_repr(k)}: {_repr(v)},\n'
dc35bfd2 249 for k, v in test_info_dict.items() if k not in missing_keys)
6f53c63d
PH
250
251 if info_dict_str:
252 info_dict_str += '\n'
dc35bfd2 253 info_dict_str += ''.join(
86e5f3ed 254 f' {_repr(k)}: {_repr(test_info_dict[k])},\n'
dc35bfd2 255 for k in missing_keys)
3e6e4999 256 write_string(
f21e915f 257 '\n\'info_dict\': {\n' + info_dict_str + '},\n', out=sys.stderr)
ea38e55f
PH
258 self.assertFalse(
259 missing_keys,
260 'Missing keys in test definition: %s' % (
261 ', '.join(sorted(missing_keys))))
c57f7757
PH
262
263
264def assertRegexpMatches(self, text, regexp, msg=None):
0fd7fd71
PH
265 if hasattr(self, 'assertRegexp'):
266 return self.assertRegexp(text, regexp, msg)
c57f7757
PH
267 else:
268 m = re.match(regexp, text)
269 if not m:
8bdcb436
PH
270 note = 'Regexp didn\'t match: %r not found' % (regexp)
271 if len(text) < 1000:
272 note += ' in %r' % text
c57f7757
PH
273 if msg is None:
274 msg = note
275 else:
276 msg = note + ', ' + msg
277 self.assertTrue(m, msg)
d8624e6a
PH
278
279
280def assertGreaterEqual(self, got, expected, msg=None):
281 if not (got >= expected):
282 if msg is None:
86e5f3ed 283 msg = f'{got!r} not greater than or equal to {expected!r}'
d8624e6a 284 self.assertTrue(got >= expected, msg)
70b7e3fb
PH
285
286
a16c7c03
S
287def assertLessEqual(self, got, expected, msg=None):
288 if not (got <= expected):
289 if msg is None:
86e5f3ed 290 msg = f'{got!r} not less than or equal to {expected!r}'
a16c7c03
S
291 self.assertTrue(got <= expected, msg)
292
293
294def assertEqual(self, got, expected, msg=None):
295 if not (got == expected):
296 if msg is None:
86e5f3ed 297 msg = f'{got!r} not equal to {expected!r}'
a16c7c03
S
298 self.assertTrue(got == expected, msg)
299
300
70b7e3fb
PH
301def expect_warnings(ydl, warnings_re):
302 real_warning = ydl.report_warning
303
304 def _report_warning(w):
305 if not any(re.search(w_re, w) for w_re in warnings_re):
306 real_warning(w)
307
308 ydl.report_warning = _report_warning
95e42d73
XDG
309
310
311def http_server_port(httpd):
312 if os.name == 'java' and isinstance(httpd.socket, ssl.SSLSocket):
313 # In Jython SSLSocket is not a subclass of socket.socket
314 sock = httpd.socket.sock
315 else:
316 sock = httpd.socket
317 return sock.getsockname()[1]