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