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