Debian Codegraph @

test/test_ytdl.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 # Copyright 2022-2026 Mike Fährmann
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License version 2 as
8 # published by the Free Software Foundation.
9
10 import os
11 import sys
12 import unittest
13
14 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15 from gallery_dl import ytdl, util, config, exception # noqa E402
16 from gallery_dl.extractor.ytdl import YoutubeDLExtractor # noqa E402
17
18
19 class Test_CommandlineArguments(unittest.TestCase):
20 module_name = "youtube_dl"
21
22 @classmethod
23 def setUpClass(cls):
24 try:
25 cls.module = __import__(cls.module_name)
26 except (ImportError, SyntaxError):
27 raise unittest.SkipTest(
28 f"cannot import module '{cls.module_name}'")
29 cls.default = ytdl.parse_command_line(cls.module, [])
30 cls.ytdlp = hasattr(cls.module, "cookies")
31
32 def test_ignore_errors(self):
33 self._("--ignore-errors" , "ignoreerrors", True)
34 self._("--abort-on-error", "ignoreerrors", False)
35
36 def test_default_search(self):
37 self._(["--default-search", "foo"] , "default_search", "foo")
38
39 def test_mark_watched(self):
40 self._("--mark-watched" , "mark_watched", True)
41 self._("--no-mark-watched", "mark_watched", False)
42
43 def test_proxy(self):
44 self._(["--proxy", "socks5://127.0.0.1:1080/"],
45 "proxy", "socks5://127.0.0.1:1080/")
46 self._(["--geo-verification-proxy", "127.0.0.1"],
47 "geo_verification_proxy", "127.0.0.1")
48
49 def test_network_options(self):
50 self._(["--socket-timeout", "3.5"],
51 "socket_timeout", 3.5)
52 self._(["--source-address", "127.0.0.1"],
53 "source_address", "127.0.0.1")
54 self._("-4" , "source_address", "0.0.0.0")
55 self._("--force-ipv4", "source_address", "0.0.0.0")
56 self._("-6" , "source_address", "::")
57 self._("--force-ipv6", "source_address", "::")
58
59 def test_thumbnail_options(self):
60 self._("--write-thumbnail", "writethumbnail", True)
61 self._("--write-all-thumbnails", "write_all_thumbnails", True)
62
63 def test_authentication_options(self):
64 self._(["-u" , "foo"], "username", "foo")
65 self._(["--username", "foo"], "username", "foo")
66
67 self._(["-p" , "bar"], "password", "bar")
68 self._(["--password", "bar"], "password", "bar")
69
70 self._(["--ap-mso" , "mso"], "ap_mso", "mso")
71 self._(["--ap-username", "foo"], "ap_username", "foo")
72 self._(["--ap-password", "bar"], "ap_password", "bar")
73
74 self._(["-2" , "pass"], "twofactor", "pass")
75 self._(["--twofactor", "pass"], "twofactor", "pass")
76
77 self._(["--video-password", "pass"], "videopassword", "pass")
78
79 self._("-n" , "usenetrc", True)
80 self._("--netrc", "usenetrc", True)
81
82 def test_subtitle_options(self):
83 self._("--write-sub" , "writesubtitles" , True)
84 self._("--write-auto-sub", "writeautomaticsub", True)
85
86 self._(["--sub-format", "best"], "subtitlesformat", "best")
87 self._(["--sub-langs", "en,ru"], "subtitleslangs", ["en", "ru"])
88
89 def test_retries(self):
90 inf = float("inf")
91
92 self._(["--retries", "5"], "retries", 5)
93 self._(["--retries", "inf"], "retries", inf)
94 self._(["--retries", "infinite"], "retries", inf)
95 self._(["--fragment-retries", "8"], "fragment_retries", 8)
96 self._(["--fragment-retries", "inf"], "fragment_retries", inf)
97 self._(["--fragment-retries", "infinite"], "fragment_retries", inf)
98
99 def test_geo_bypass(self):
100 self._("--geo-bypass", "geo_bypass", True)
101 self._("--no-geo-bypass", "geo_bypass", False)
102 self._(["--geo-bypass-country", "EN"], "geo_bypass_country", "EN")
103 self._(["--geo-bypass-ip-block", "198.51.100.14/24"],
104 "geo_bypass_ip_block", "198.51.100.14/24")
105
106 def test_headers(self):
107 try:
108 headers = self.module.utils.networking.std_headers
109 except AttributeError:
110 headers = self.module.std_headers
111
112 self.assertNotEqual(headers["User-Agent"], "Foo/1.0")
113 self._(["--user-agent", "Foo/1.0"])
114 self.assertEqual(headers["User-Agent"], "Foo/1.0")
115
116 self.assertNotIn("Referer", headers)
117 self._(["--referer", "http://example.org/"])
118 self.assertEqual(headers["Referer"], "http://example.org/")
119
120 self.assertNotEqual(headers["Accept"], "*/*")
121 self.assertNotIn("DNT", headers)
122 self._([
123 "--add-header", "accept:*/*",
124 "--add-header", "dnt:1",
125 ])
126 self.assertEqual(headers["accept"], "*/*")
127 self.assertEqual(headers["dnt"], "1")
128
129 def test_extract_audio(self):
130 opts = self._(["--extract-audio"])
131 self.assertEqual(opts["postprocessors"][0], {
132 "key": "FFmpegExtractAudio",
133 "preferredcodec": "best",
134 "preferredquality": "5",
135 "nopostoverwrites": False,
136 })
137
138 opts = self._([
139 "--extract-audio",
140 "--audio-format", "opus",
141 "--audio-quality", "9",
142 "--no-post-overwrites",
143 ])
144 self.assertEqual(opts["postprocessors"][0], {
145 "key": "FFmpegExtractAudio",
146 "preferredcodec": "opus",
147 "preferredquality": "9",
148 "nopostoverwrites": True,
149 })
150
151 def test_recode_video(self):
152 opts = self._(["--recode-video", " mkv "])
153 self.assertEqual(opts["postprocessors"][0], {
154 "key": "FFmpegVideoConvertor",
155 "preferedformat": "mkv",
156 })
157
158 def test_subs(self):
159 opts = self._(["--convert-subs", "srt"])
160 conv = {"key": "FFmpegSubtitlesConvertor", "format": "srt"}
161 if self.ytdlp:
162 conv["when"] = "before_dl"
163 self.assertEqual(opts["postprocessors"][0], conv)
164
165 def test_embed(self):
166 subs = {"key": "FFmpegEmbedSubtitle"}
167 thumb = {"key": "EmbedThumbnail", "already_have_thumbnail": False}
168 if self.ytdlp:
169 subs["already_have_subtitle"] = False
170
171 opts = self._(["--embed-subs", "--embed-thumbnail"])
172 self.assertEqual(opts["postprocessors"][:2], [subs, thumb])
173
174 thumb["already_have_thumbnail"] = True
175 if self.ytdlp:
176 subs["already_have_subtitle"] = True
177 thumb["already_have_thumbnail"] = "all"
178
179 opts = self._([
180 "--embed-thumbnail",
181 "--embed-subs",
182 "--write-sub",
183 "--write-all-thumbnails",
184 ])
185 self.assertEqual(opts["postprocessors"][:2], [subs, thumb])
186
187 def test_metadata(self):
188 opts = self._("--add-metadata")
189 self.assertEqual(opts["postprocessors"][0], {"key": "FFmpegMetadata"})
190
191 def test_metadata_from_title(self):
192 opts = self._(["--metadata-from-title", "%(artist)s - %(title)s"])
193 self.assertEqual(opts["postprocessors"][0], {
194 "key": "MetadataFromTitle",
195 "titleformat": "%(artist)s - %(title)s",
196 })
197
198 def test_xattr(self):
199 opts = self._("--xattrs")
200 self.assertEqual(opts["postprocessors"][0], {"key": "XAttrMetadata"})
201
202 def test_noop(self):
203 cmdline = [
204 "--update",
205 "--dump-user-agent",
206 "-F",
207 "--list-formats",
208 "--list-extractors",
209 "--list-thumbnails",
210 "--list-subs",
211 "--ap-list-mso",
212 "--extractor-descriptions",
213 "--ignore-config",
214 ]
215
216 if not self.ytdlp:
217 cmdline.extend((
218 "--dump-json",
219 "--dump-single-json",
220 "--config-location", "~",
221 ))
222
223 result = self._(cmdline)
224 result["daterange"] = self.default["daterange"]
225 self.assertEqual(result, self.default)
226
227 def _(self, cmdline, option=util.SENTINEL, expected=None):
228 if isinstance(cmdline, str):
229 cmdline = [cmdline]
230 result = ytdl.parse_command_line(self.module, cmdline)
231 if option is not util.SENTINEL:
232 self.assertEqual(result[option], expected, option)
233 return result
234
235
236 class Test_CommandlineArguments_YtDlp(Test_CommandlineArguments):
237 module_name = "yt_dlp"
238
239 def test_retries_extractor(self):
240 inf = float("inf")
241
242 self._(["--extractor-retries", "5"], "extractor_retries", 5)
243 self._(["--extractor-retries", "inf"], "extractor_retries", inf)
244 self._(["--extractor-retries", "infinite"], "extractor_retries", inf)
245
246 def test_remuxs_video(self):
247 opts = self._(["--remux-video", " mkv "])
248 self.assertEqual(opts["postprocessors"][0], {
249 "key": "FFmpegVideoRemuxer",
250 "preferedformat": "mkv",
251 })
252
253 def test_metadata(self):
254 opts = self._(["--embed-metadata",
255 "--no-embed-chapters",
256 "--embed-info-json"])
257 self.assertEqual(opts["postprocessors"][0], {
258 "key": "FFmpegMetadata",
259 "add_chapters": False,
260 "add_metadata": True,
261 "add_infojson": True,
262 })
263
264 def test_metadata_from_title(self):
265 opts = self._(["--metadata-from-title", "%(artist)s - %(title)s"])
266 self.assertEqual(opts["postprocessors"][0], {
267 "key" : "MetadataParser",
268 "when" : "pre_process",
269 "actions": [self.module.MetadataFromFieldPP.to_action(
270 "title:%(artist)s - %(title)s")],
271 })
272
273 def test_geo_bypass(self):
274 try:
275 ytdl.parse_command_line(self.module, ["--xff", "default"])
276 except Exception:
277 # before --xff (c16644642)
278 return Test_CommandlineArguments.test_geo_bypass(self)
279
280 self._(["--xff", "default"],
281 "geo_bypass", "default")
282 self._(["--xff", "never"],
283 "geo_bypass", "never")
284 self._(["--xff", "EN"],
285 "geo_bypass", "EN")
286 self._(["--xff", "198.51.100.14/24"],
287 "geo_bypass", "198.51.100.14/24")
288
289 self._("--geo-bypass",
290 "geo_bypass", "default")
291 self._("--no-geo-bypass",
292 "geo_bypass", "never")
293 self._(["--geo-bypass-country", "EN"],
294 "geo_bypass", "EN")
295 self._(["--geo-bypass-ip-block", "198.51.100.14/24"],
296 "geo_bypass", "198.51.100.14/24")
297
298 def test_cookiesfrombrowser(self):
299 self._(["--cookies-from-browser", "firefox"],
300 "cookiesfrombrowser", ("firefox", None, None, None))
301 self._(["--cookies-from-browser", "firefox:profile"],
302 "cookiesfrombrowser", ("firefox", "profile", None, None))
303 self._(["--cookies-from-browser", "firefox+keyring"],
304 "cookiesfrombrowser", ("firefox", None, "KEYRING", None))
305 self._(["--cookies-from-browser", "firefox::container"],
306 "cookiesfrombrowser", ("firefox", None, None, "container"))
307 self._(["--cookies-from-browser",
308 "firefox+keyring:profile::container"],
309 "cookiesfrombrowser",
310 ("firefox", "profile", "KEYRING", "container"))
311
312 def test_imperonate(self):
313 if not hasattr(self.module, "ImpersonateTarget"):
314 self.skipTest("'ImpersonateTarget' not available")
315 opts = self._(["--impersonate", "Chrome-110"])
316 self.assertEqual(opts["impersonate"],
317 self.module.ImpersonateTarget("chrome", "110"))
318
319
320 class MockYtdlModule:
321 class utils:
322 class YoutubeDLError(Exception):
323 pass
324
325
326 class MockYtdlInstance:
327 def __init__(self, ignoreerrors):
328 self.params = {"ignoreerrors": ignoreerrors}
329
330
331 class Test_YoutubeDLExtractor(unittest.TestCase):
332 def setUp(self):
333 class ExtractorMock(YoutubeDLExtractor):
334 def __init__(self):
335 self.exc = exception
336 self.extr = ExtractorMock.__new__(ExtractorMock)
337 self.extr.exc = exception
338
339 def test_process_entries_restart_propagation(self):
340 ytdl_module = MockYtdlModule()
341 ytdl_instance = MockYtdlInstance(ignoreerrors=False)
342
343 def mock_extract_info(url, dl, ie_key):
344 raise exception.RestartExtraction()
345 ytdl_instance.extract_info = mock_extract_info
346
347 entries = [{"_type": "url", "url": "test_url"}]
348 with self.assertRaises(exception.RestartExtraction):
349 list(self.extr._process_entries(
350 ytdl_module, ytdl_instance, entries))
351
352 def test_process_entries_ignoreerrors_true(self):
353 ytdl_module = MockYtdlModule()
354 ytdl_instance = MockYtdlInstance(ignoreerrors=True)
355
356 def mock_extract_info(url, dl, ie_key):
357 raise ytdl_module.utils.YoutubeDLError("Some Error")
358 ytdl_instance.extract_info = mock_extract_info
359
360 entries = [
361 {"_type": "url", "url": "test_url1"},
362 {"_type": "url", "url": "test_url2"}
363 ]
364 results = list(self.extr._process_entries(
365 ytdl_module, ytdl_instance, entries))
366 self.assertEqual(results, [])
367
368 def test_process_entries_ignoreerrors_false(self):
369 ytdl_module = MockYtdlModule()
370 ytdl_instance = MockYtdlInstance(ignoreerrors=False)
371
372 def mock_extract_info(url, dl, ie_key):
373 raise ytdl_module.utils.YoutubeDLError("Some Error")
374 ytdl_instance.extract_info = mock_extract_info
375
376 entries = [{"_type": "url", "url": "test_url"}]
377 with self.assertRaises(exception.AbortExtraction):
378 list(self.extr._process_entries(
379 ytdl_module, ytdl_instance, entries))
380
381
382 if __name__ == "__main__":
383 unittest.main(warnings="ignore")