3 # Allow direct execution
7 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9 from test.helper import (
23 import youtube_dl.YoutubeDL
24 from youtube_dl.utils import (
30 UnavailableVideoError,
32 from youtube_dl.extractor import get_info_extractor
36 class YoutubeDL(youtube_dl.YoutubeDL):
37 def __init__(self, *args, **kwargs):
38 self.to_stderr = self.to_screen
39 self.processed_info_dicts = []
40 super(YoutubeDL, self).__init__(*args, **kwargs)
41 def report_warning(self, message):
42 # Don't accept warnings during tests
43 raise ExtractorError(message)
44 def process_info(self, info_dict):
45 self.processed_info_dicts.append(info_dict)
46 return super(YoutubeDL, self).process_info(info_dict)
49 with open(fn, 'rb') as f:
50 return hashlib.md5(f.read()).hexdigest()
55 class TestDownload(unittest.TestCase):
60 ### Dynamically generate tests
61 def generator(test_case):
63 def test_template(self):
64 ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
65 other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
66 is_playlist = any(k.startswith('playlist') for k in test_case)
67 test_cases = test_case.get(
68 'playlist', [] if is_playlist else [test_case])
70 def print_skipping(reason):
71 print('Skipping %s: %s' % (test_case['name'], reason))
73 print_skipping('IE marked as not _WORKING')
77 info_dict = tc.get('info_dict', {})
78 if not tc.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
79 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
81 if 'skip' in test_case:
82 print_skipping(test_case['skip'])
84 for other_ie in other_ies:
85 if not other_ie.working():
86 print_skipping(u'test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
89 params = get_params(test_case.get('params', {}))
90 if is_playlist and 'playlist' not in test_case:
91 params.setdefault('extract_flat', True)
92 params.setdefault('skip_download', True)
94 ydl = YoutubeDL(params)
95 ydl.add_default_info_extractors()
96 finished_hook_called = set()
98 if status['status'] == 'finished':
99 finished_hook_called.add(status['filename'])
100 ydl.add_progress_hook(_hook)
102 def get_tc_filename(tc):
103 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
105 def try_rm_tcs_files():
106 for tc in test_cases:
107 tc_filename = get_tc_filename(tc)
109 try_rm(tc_filename + '.part')
110 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
116 # We're not using .download here sine that is just a shim
117 # for outside error handling, and returns the exit code
118 # instead of the result dict.
119 res_dict = ydl.extract_info(test_case['url'])
120 except (DownloadError, ExtractorError) as err:
121 # Check if the exception is not a network related one
122 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):
125 if try_num == RETRIES:
126 report_warning(u'Failed due to network errors, skipping...')
129 print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
136 self.assertEqual(res_dict['_type'], 'playlist')
137 expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
138 if 'playlist_mincount' in test_case:
139 self.assertGreaterEqual(
140 len(res_dict['entries']),
141 test_case['playlist_mincount'],
142 'Expected at least %d in playlist %s, but got only %d' % (
143 test_case['playlist_mincount'], test_case['url'],
144 len(res_dict['entries'])))
146 for tc in test_cases:
147 tc_filename = get_tc_filename(tc)
148 if not test_case.get('params', {}).get('skip_download', False):
149 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
150 self.assertTrue(tc_filename in finished_hook_called)
151 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
152 self.assertTrue(os.path.exists(info_json_fn))
154 md5_for_file = _file_md5(tc_filename)
155 self.assertEqual(md5_for_file, tc['md5'])
156 with io.open(info_json_fn, encoding='utf-8') as infof:
157 info_dict = json.load(infof)
159 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
165 ### And add them to TestDownload
166 for n, test_case in enumerate(defs):
167 test_method = generator(test_case)
168 tname = 'test_' + str(test_case['name'])
170 while hasattr(TestDownload, tname):
171 tname = 'test_' + str(test_case['name']) + '_' + str(i)
173 test_method.__name__ = tname
174 setattr(TestDownload, test_method.__name__, test_method)
178 if __name__ == '__main__':