Merge branch 'cinemassacre' of github.com:rzhxeo/youtube-dl into rzhxeo-cinemassacre
[youtube-dl] / 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 youtube_dl._setup_opener(timeout=10)
16
17 PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "parameters.json")
18 with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
19     parameters = json.load(pf)
20
21
22 def try_rm(filename):
23     """ Remove a file if it exists """
24     try:
25         os.remove(filename)
26     except OSError as ose:
27         if ose.errno != errno.ENOENT:
28             raise
29
30
31 class FakeYDL(YoutubeDL):
32     def __init__(self):
33         # Different instances of the downloader can't share the same dictionary
34         # some test set the "sublang" parameter, which would break the md5 checks.
35         params = dict(parameters)
36         super(FakeYDL, self).__init__(params)
37         self.result = []
38         
39     def to_screen(self, s, skip_eol=None):
40         print(s)
41
42     def trouble(self, s, tb=None):
43         raise Exception(s)
44
45     def download(self, x):
46         self.result.append(x)
47
48     def expect_warning(self, regex):
49         # Silence an expected warning matching a regex
50         old_report_warning = self.report_warning
51         def report_warning(self, message):
52             if re.match(regex, message): return
53             old_report_warning(message)
54         self.report_warning = types.MethodType(report_warning, self)
55
56 def get_testcases():
57     for ie in youtube_dl.extractor.gen_extractors():
58         t = getattr(ie, '_TEST', None)
59         if t:
60             t['name'] = type(ie).__name__[:-len('IE')]
61             yield t
62         for t in getattr(ie, '_TESTS', []):
63             t['name'] = type(ie).__name__[:-len('IE')]
64             yield t