[test/helper] Modernize
[youtube-dl] / test / helper.py
1 from __future__ import unicode_literals
2
3 import errno
4 import io
5 import hashlib
6 import json
7 import os.path
8 import re
9 import types
10 import sys
11
12 import youtube_dl.extractor
13 from youtube_dl import YoutubeDL
14 from youtube_dl.utils import (
15     compat_str,
16     preferredencoding,
17 )
18
19
20 def get_params(override=None):
21     PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
22                                    "parameters.json")
23     with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
24         parameters = json.load(pf)
25     if override:
26         parameters.update(override)
27     return parameters
28
29
30 def try_rm(filename):
31     """ Remove a file if it exists """
32     try:
33         os.remove(filename)
34     except OSError as ose:
35         if ose.errno != errno.ENOENT:
36             raise
37
38
39 def report_warning(message):
40     '''
41     Print the message to stderr, it will be prefixed with 'WARNING:'
42     If stderr is a tty file the 'WARNING:' will be colored
43     '''
44     if sys.stderr.isatty() and os.name != 'nt':
45         _msg_header = '\033[0;33mWARNING:\033[0m'
46     else:
47         _msg_header = 'WARNING:'
48     output = '%s %s\n' % (_msg_header, message)
49     if 'b' in getattr(sys.stderr, 'mode', '') or sys.version_info[0] < 3:
50         output = output.encode(preferredencoding())
51     sys.stderr.write(output)
52
53
54 class FakeYDL(YoutubeDL):
55     def __init__(self, override=None):
56         # Different instances of the downloader can't share the same dictionary
57         # some test set the "sublang" parameter, which would break the md5 checks.
58         params = get_params(override=override)
59         super(FakeYDL, self).__init__(params)
60         self.result = []
61         
62     def to_screen(self, s, skip_eol=None):
63         print(s)
64
65     def trouble(self, s, tb=None):
66         raise Exception(s)
67
68     def download(self, x):
69         self.result.append(x)
70
71     def expect_warning(self, regex):
72         # Silence an expected warning matching a regex
73         old_report_warning = self.report_warning
74         def report_warning(self, message):
75             if re.match(regex, message): return
76             old_report_warning(message)
77         self.report_warning = types.MethodType(report_warning, self)
78
79
80 def gettestcases(include_onlymatching=False):
81     for ie in youtube_dl.extractor.gen_extractors():
82         t = getattr(ie, '_TEST', None)
83         if t:
84             assert not hasattr(ie, '_TESTS'), \
85                 '%s has _TEST and _TESTS' % type(ie).__name__
86             tests = [t]
87         else:
88             tests = getattr(ie, '_TESTS', [])
89         for t in tests:
90             if not include_onlymatching and t.get('only_matching', False):
91                 continue
92             t['name'] = type(ie).__name__[:-len('IE')]
93             yield t
94
95
96 md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
97
98
99 def expect_info_dict(self, expected_dict, got_dict):
100     for info_field, expected in expected_dict.items():
101         if isinstance(expected, compat_str) and expected.startswith('re:'):
102             got = got_dict.get(info_field)
103             match_str = expected[len('re:'):]
104             match_rex = re.compile(match_str)
105
106             self.assertTrue(
107                 isinstance(got, compat_str),
108                 'Expected a %s object, but got %s for field %s' % (
109                     compat_str.__name__, type(got).__name__, info_field))
110             self.assertTrue(
111                 match_rex.match(got),
112                 'field %s (value: %r) should match %r' % (info_field, got, match_str))
113         elif isinstance(expected, type):
114             got = got_dict.get(info_field)
115             self.assertTrue(isinstance(got, expected),
116                 'Expected type %r for field %s, but got value %r of type %r' % (expected, info_field, got, type(got)))
117         else:
118             if isinstance(expected, compat_str) and expected.startswith('md5:'):
119                 got = 'md5:' + md5(got_dict.get(info_field))
120             else:
121                 got = got_dict.get(info_field)
122             self.assertEqual(expected, got,
123                 'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
124
125     # Check for the presence of mandatory fields
126     if got_dict.get('_type') != 'playlist':
127         for key in ('id', 'url', 'title', 'ext'):
128             self.assertTrue(got_dict.get(key), 'Missing mandatory field %s' % key)
129     # Check for mandatory fields that are automatically set by YoutubeDL
130     for key in ['webpage_url', 'extractor', 'extractor_key']:
131         self.assertTrue(got_dict.get(key), 'Missing field: %s' % key)
132
133     # Are checkable fields missing from the test case definition?
134     test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
135         for key, value in got_dict.items()
136         if value and key in ('title', 'description', 'uploader', 'upload_date', 'timestamp', 'uploader_id', 'location'))
137     missing_keys = set(test_info_dict.keys()) - set(expected_dict.keys())
138     if missing_keys:
139         sys.stderr.write('\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=4) + '\n')
140         self.assertFalse(
141             missing_keys,
142             'Missing keys in test definition: %s' % (
143                 ', '.join(sorted(missing_keys))))
144
145
146 def assertRegexpMatches(self, text, regexp, msg=None):
147     if hasattr(self, 'assertRegexp'):
148         return self.assertRegexp(text, regexp, msg)
149     else:
150         m = re.match(regexp, text)
151         if not m:
152             note = 'Regexp didn\'t match: %r not found in %r' % (regexp, text)
153             if msg is None:
154                 msg = note
155             else:
156                 msg = note + ', ' + msg
157             self.assertTrue(m, msg)
158
159
160 def assertGreaterEqual(self, got, expected, msg=None):
161     if not (got >= expected):
162         if msg is None:
163             msg = '%r not greater than or equal to %r' % (got, expected)
164         self.assertTrue(got >= expected, msg)