3 # Allow direct execution
7 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9 from test.helper import (
24 import youtube_dl.YoutubeDL
25 from youtube_dl.utils import (
32 UnavailableVideoError,
34 from youtube_dl.extractor import get_info_extractor
38 class YoutubeDL(youtube_dl.YoutubeDL):
39 def __init__(self, *args, **kwargs):
40 self.to_stderr = self.to_screen
41 self.processed_info_dicts = []
42 super(YoutubeDL, self).__init__(*args, **kwargs)
43 def report_warning(self, message):
44 # Don't accept warnings during tests
45 raise ExtractorError(message)
46 def process_info(self, info_dict):
47 self.processed_info_dicts.append(info_dict)
48 return super(YoutubeDL, self).process_info(info_dict)
51 with open(fn, 'rb') as f:
52 return hashlib.md5(f.read()).hexdigest()
57 class TestDownload(unittest.TestCase):
62 ### Dynamically generate tests
63 def generator(test_case):
65 def test_template(self):
66 ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
67 other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
68 is_playlist = any(k.startswith('playlist') for k in test_case)
69 test_cases = test_case.get(
70 'playlist', [] if is_playlist else [test_case])
72 def print_skipping(reason):
73 print('Skipping %s: %s' % (test_case['name'], reason))
75 print_skipping('IE marked as not _WORKING')
79 info_dict = tc.get('info_dict', {})
80 if not tc.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
81 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
83 if 'skip' in test_case:
84 print_skipping(test_case['skip'])
86 for other_ie in other_ies:
87 if not other_ie.working():
88 print_skipping(u'test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
91 params = get_params(test_case.get('params', {}))
92 if is_playlist and 'playlist' not in test_case:
93 params.setdefault('extract_flat', True)
94 params.setdefault('skip_download', True)
96 ydl = YoutubeDL(params)
97 ydl.add_default_info_extractors()
98 finished_hook_called = set()
100 if status['status'] == 'finished':
101 finished_hook_called.add(status['filename'])
102 ydl.add_progress_hook(_hook)
104 def get_tc_filename(tc):
105 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
108 def try_rm_tcs_files(tcs=None):
112 tc_filename = get_tc_filename(tc)
114 try_rm(tc_filename + '.part')
115 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
121 # We're not using .download here sine that is just a shim
122 # for outside error handling, and returns the exit code
123 # instead of the result dict.
124 res_dict = ydl.extract_info(test_case['url'])
125 except (DownloadError, ExtractorError) as err:
126 # Check if the exception is not a network related one
127 if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError, compat_http_client.BadStatusLine) or (err.exc_info[0] == compat_HTTPError and err.exc_info[1].code == 503):
130 if try_num == RETRIES:
131 report_warning(u'Failed due to network errors, skipping...')
134 print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
141 self.assertEqual(res_dict['_type'], 'playlist')
142 expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
143 if 'playlist_mincount' in test_case:
146 len(res_dict['entries']),
147 test_case['playlist_mincount'],
148 'Expected at least %d in playlist %s, but got only %d' % (
149 test_case['playlist_mincount'], test_case['url'],
150 len(res_dict['entries'])))
151 if 'playlist_count' in test_case:
153 len(res_dict['entries']),
154 test_case['playlist_count'],
155 'Expected %d entries in playlist %s, but got %d.' % (
156 test_case['playlist_count'],
158 len(res_dict['entries']),
160 if 'playlist_duration_sum' in test_case:
161 got_duration = sum(e['duration'] for e in res_dict['entries'])
163 test_case['playlist_duration_sum'], got_duration)
165 for tc in test_cases:
166 tc_filename = get_tc_filename(tc)
167 if not test_case.get('params', {}).get('skip_download', False):
168 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
169 self.assertTrue(tc_filename in finished_hook_called)
170 expected_minsize = tc.get('file_minsize', 10000)
171 if expected_minsize is not None:
172 if params.get('test'):
173 expected_minsize = max(expected_minsize, 10000)
174 got_fsize = os.path.getsize(tc_filename)
176 self, got_fsize, expected_minsize,
177 'Expected %s to be at least %s, but it\'s only %s ' %
178 (tc_filename, format_bytes(expected_minsize),
179 format_bytes(got_fsize)))
181 md5_for_file = _file_md5(tc_filename)
182 self.assertEqual(md5_for_file, tc['md5'])
183 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
184 self.assertTrue(os.path.exists(info_json_fn))
185 with io.open(info_json_fn, encoding='utf-8') as infof:
186 info_dict = json.load(infof)
188 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
191 if is_playlist and res_dict is not None:
192 # Remove all other files that may have been extracted if the
193 # extractor returns full results even with extract_flat
194 res_tcs = [{'info_dict': e} for e in res_dict['entries']]
195 try_rm_tcs_files(res_tcs)
199 ### And add them to TestDownload
200 for n, test_case in enumerate(defs):
201 test_method = generator(test_case)
202 tname = 'test_' + str(test_case['name'])
204 while hasattr(TestDownload, tname):
205 tname = 'test_' + str(test_case['name']) + '_' + str(i)
207 test_method.__name__ = tname
208 setattr(TestDownload, test_method.__name__, test_method)
212 if __name__ == '__main__':