]> Raphaƫl G. Git Repositories - youtubedl/blob - test/helper.py
Update changelog.
[youtubedl] / test / helper.py
1 import errno
2 import io
3 import hashlib
4 import json
5 import os.path
6 import re
7 import types
8 import sys
9
10 import youtube_dl.extractor
11 from youtube_dl import YoutubeDL
12 from youtube_dl.utils import preferredencoding
13
14
15 def global_setup():
16 youtube_dl._setup_opener(timeout=10)
17
18
19 def get_params(override=None):
20 PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
21 "parameters.json")
22 with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
23 parameters = json.load(pf)
24 if override:
25 parameters.update(override)
26 return parameters
27
28
29 def try_rm(filename):
30 """ Remove a file if it exists """
31 try:
32 os.remove(filename)
33 except OSError as ose:
34 if ose.errno != errno.ENOENT:
35 raise
36
37
38 def report_warning(message):
39 '''
40 Print the message to stderr, it will be prefixed with 'WARNING:'
41 If stderr is a tty file the 'WARNING:' will be colored
42 '''
43 if sys.stderr.isatty() and os.name != 'nt':
44 _msg_header = u'\033[0;33mWARNING:\033[0m'
45 else:
46 _msg_header = u'WARNING:'
47 output = u'%s %s\n' % (_msg_header, message)
48 if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
49 output = output.encode(preferredencoding())
50 sys.stderr.write(output)
51
52
53 class FakeYDL(YoutubeDL):
54 def __init__(self, override=None):
55 # Different instances of the downloader can't share the same dictionary
56 # some test set the "sublang" parameter, which would break the md5 checks.
57 params = get_params(override=override)
58 super(FakeYDL, self).__init__(params)
59 self.result = []
60
61 def to_screen(self, s, skip_eol=None):
62 print(s)
63
64 def trouble(self, s, tb=None):
65 raise Exception(s)
66
67 def download(self, x):
68 self.result.append(x)
69
70 def expect_warning(self, regex):
71 # Silence an expected warning matching a regex
72 old_report_warning = self.report_warning
73 def report_warning(self, message):
74 if re.match(regex, message): return
75 old_report_warning(message)
76 self.report_warning = types.MethodType(report_warning, self)
77
78 def get_testcases():
79 for ie in youtube_dl.extractor.gen_extractors():
80 t = getattr(ie, '_TEST', None)
81 if t:
82 t['name'] = type(ie).__name__[:-len('IE')]
83 yield t
84 for t in getattr(ie, '_TESTS', []):
85 t['name'] = type(ie).__name__[:-len('IE')]
86 yield t
87
88
89 md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()