3 # Allow direct execution
7 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9 from test.helper import (
25 import youtube_dl.YoutubeDL
26 from youtube_dl.compat import (
31 from youtube_dl.utils import (
35 UnavailableVideoError,
37 from youtube_dl.extractor import get_info_extractor
41 class YoutubeDL(youtube_dl.YoutubeDL):
42 def __init__(self, *args, **kwargs):
43 self.to_stderr = self.to_screen
44 self.processed_info_dicts = []
45 super(YoutubeDL, self).__init__(*args, **kwargs)
46 def report_warning(self, message):
47 # Don't accept warnings during tests
48 raise ExtractorError(message)
49 def process_info(self, info_dict):
50 self.processed_info_dicts.append(info_dict)
51 return super(YoutubeDL, self).process_info(info_dict)
54 with open(fn, 'rb') as f:
55 return hashlib.md5(f.read()).hexdigest()
60 class TestDownload(unittest.TestCase):
65 ### Dynamically generate tests
66 def generator(test_case):
68 def test_template(self):
69 ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
70 other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
71 is_playlist = any(k.startswith('playlist') for k in test_case)
72 test_cases = test_case.get(
73 'playlist', [] if is_playlist else [test_case])
75 def print_skipping(reason):
76 print('Skipping %s: %s' % (test_case['name'], reason))
78 print_skipping('IE marked as not _WORKING')
82 info_dict = tc.get('info_dict', {})
83 if not tc.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
84 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
86 if 'skip' in test_case:
87 print_skipping(test_case['skip'])
89 for other_ie in other_ies:
90 if not other_ie.working():
91 print_skipping(u'test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
94 params = get_params(test_case.get('params', {}))
95 if is_playlist and 'playlist' not in test_case:
96 params.setdefault('extract_flat', True)
97 params.setdefault('skip_download', True)
99 ydl = YoutubeDL(params, auto_init=False)
100 ydl.add_default_info_extractors()
101 finished_hook_called = set()
103 if status['status'] == 'finished':
104 finished_hook_called.add(status['filename'])
105 ydl.add_progress_hook(_hook)
106 expect_warnings(ydl, test_case.get('expected_warnings', []))
108 def get_tc_filename(tc):
109 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
112 def try_rm_tcs_files(tcs=None):
116 tc_filename = get_tc_filename(tc)
118 try_rm(tc_filename + '.part')
119 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
125 # We're not using .download here sine that is just a shim
126 # for outside error handling, and returns the exit code
127 # instead of the result dict.
128 res_dict = ydl.extract_info(test_case['url'])
129 except (DownloadError, ExtractorError) as err:
130 # Check if the exception is not a network related one
131 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):
134 if try_num == RETRIES:
135 report_warning(u'Failed due to network errors, skipping...')
138 print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
145 self.assertEqual(res_dict['_type'], 'playlist')
146 self.assertTrue('entries' in res_dict)
147 expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
149 if 'playlist_mincount' in test_case:
152 len(res_dict['entries']),
153 test_case['playlist_mincount'],
154 'Expected at least %d in playlist %s, but got only %d' % (
155 test_case['playlist_mincount'], test_case['url'],
156 len(res_dict['entries'])))
157 if 'playlist_count' in test_case:
159 len(res_dict['entries']),
160 test_case['playlist_count'],
161 'Expected %d entries in playlist %s, but got %d.' % (
162 test_case['playlist_count'],
164 len(res_dict['entries']),
166 if 'playlist_duration_sum' in test_case:
167 got_duration = sum(e['duration'] for e in res_dict['entries'])
169 test_case['playlist_duration_sum'], got_duration)
171 for tc in test_cases:
172 tc_filename = get_tc_filename(tc)
173 if not test_case.get('params', {}).get('skip_download', False):
174 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
175 self.assertTrue(tc_filename in finished_hook_called)
176 expected_minsize = tc.get('file_minsize', 10000)
177 if expected_minsize is not None:
178 if params.get('test'):
179 expected_minsize = max(expected_minsize, 10000)
180 got_fsize = os.path.getsize(tc_filename)
182 self, got_fsize, expected_minsize,
183 'Expected %s to be at least %s, but it\'s only %s ' %
184 (tc_filename, format_bytes(expected_minsize),
185 format_bytes(got_fsize)))
187 md5_for_file = _file_md5(tc_filename)
188 self.assertEqual(md5_for_file, tc['md5'])
189 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
191 os.path.exists(info_json_fn),
192 'Missing info file %s' % info_json_fn)
193 with io.open(info_json_fn, encoding='utf-8') as infof:
194 info_dict = json.load(infof)
196 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
199 if is_playlist and res_dict is not None and res_dict.get('entries'):
200 # Remove all other files that may have been extracted if the
201 # extractor returns full results even with extract_flat
202 res_tcs = [{'info_dict': e} for e in res_dict['entries']]
203 try_rm_tcs_files(res_tcs)
207 ### And add them to TestDownload
208 for n, test_case in enumerate(defs):
209 test_method = generator(test_case)
210 tname = 'test_' + str(test_case['name'])
212 while hasattr(TestDownload, tname):
213 tname = 'test_' + str(test_case['name']) + '_' + str(i)
215 test_method.__name__ = tname
216 setattr(TestDownload, test_method.__name__, test_method)
220 if __name__ == '__main__':