1 from __future__ import unicode_literals
12 import youtube_dl.extractor
13 from youtube_dl import YoutubeDL
14 from youtube_dl.utils import (
20 def get_params(override=None):
21 PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
23 with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
24 parameters = json.load(pf)
26 parameters.update(override)
31 """ Remove a file if it exists """
34 except OSError as ose:
35 if ose.errno != errno.ENOENT:
39 def report_warning(message):
41 Print the message to stderr, it will be prefixed with 'WARNING:'
42 If stderr is a tty file the 'WARNING:' will be colored
44 if sys.stderr.isatty() and os.name != 'nt':
45 _msg_header = '\033[0;33mWARNING:\033[0m'
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)
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)
62 def to_screen(self, s, skip_eol=None):
65 def trouble(self, s, tb=None):
68 def download(self, x):
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)
80 def gettestcases(include_onlymatching=False):
81 for ie in youtube_dl.extractor.gen_extractors():
82 t = getattr(ie, '_TEST', None)
84 assert not hasattr(ie, '_TESTS'), \
85 '%s has _TEST and _TESTS' % type(ie).__name__
88 tests = getattr(ie, '_TESTS', [])
90 if not include_onlymatching and t.get('only_matching', False):
92 t['name'] = type(ie).__name__[:-len('IE')]
96 md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
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)
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))
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)))
118 if isinstance(expected, compat_str) and expected.startswith('md5:'):
119 got = 'md5:' + md5(got_dict.get(info_field))
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))
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)
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())
139 sys.stderr.write('\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=4) + '\n')
142 'Missing keys in test definition: %s' % (
143 ', '.join(sorted(missing_keys))))
146 def assertRegexpMatches(self, text, regexp, msg=None):
147 if hasattr(self, 'assertRegexp'):
148 return self.assertRegexp(text, regexp, msg)
150 m = re.match(regexp, text)
152 note = 'Regexp didn\'t match: %r not found in %r' % (regexp, text)
156 msg = note + ', ' + msg
157 self.assertTrue(m, msg)
160 def assertGreaterEqual(self, got, expected, msg=None):
161 if not (got >= expected):
163 msg = '%r not greater than or equal to %r' % (got, expected)
164 self.assertTrue(got >= expected, msg)