]> jfr.im git - yt-dlp.git/blob - test/helper.py
Move try_rm to test helpers
[yt-dlp.git] / test / helper.py
1 import errno
2 import io
3 import json
4 import os.path
5 import re
6 import types
7
8 import youtube_dl.extractor
9 from youtube_dl import YoutubeDL, YoutubeDLHandler
10 from youtube_dl.utils import (
11 compat_cookiejar,
12 compat_urllib_request,
13 )
14
15 # General configuration (from __init__, not very elegant...)
16 jar = compat_cookiejar.CookieJar()
17 cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
18 proxy_handler = compat_urllib_request.ProxyHandler()
19 opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
20 compat_urllib_request.install_opener(opener)
21
22 PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "parameters.json")
23 with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
24 parameters = json.load(pf)
25
26
27 def try_rm(filename):
28 """ Remove a file if it exists """
29 try:
30 os.remove(filename)
31 except OSError as ose:
32 if ose.errno != errno.ENOENT:
33 raise
34
35
36 class FakeYDL(YoutubeDL):
37 def __init__(self):
38 # Different instances of the downloader can't share the same dictionary
39 # some test set the "sublang" parameter, which would break the md5 checks.
40 params = dict(parameters)
41 super(FakeYDL, self).__init__(params)
42 self.result = []
43
44 def to_screen(self, s, skip_eol=None):
45 print(s)
46
47 def trouble(self, s, tb=None):
48 raise Exception(s)
49
50 def download(self, x):
51 self.result.append(x)
52
53 def expect_warning(self, regex):
54 # Silence an expected warning matching a regex
55 old_report_warning = self.report_warning
56 def report_warning(self, message):
57 if re.match(regex, message): return
58 old_report_warning(message)
59 self.report_warning = types.MethodType(report_warning, self)
60
61 def get_testcases():
62 for ie in youtube_dl.extractor.gen_extractors():
63 t = getattr(ie, '_TEST', None)
64 if t:
65 t['name'] = type(ie).__name__[:-len('IE')]
66 yield t
67 for t in getattr(ie, '_TESTS', []):
68 t['name'] = type(ie).__name__[:-len('IE')]
69 yield t