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