]> Raphaƫl G. Git Repositories - youtubedl/blob - test/test_download.py
debian/control: Confirm that the package conforms to policy 3.9.6.
[youtubedl] / test / test_download.py
1 #!/usr/bin/env python
2
3 # Allow direct execution
4 import os
5 import sys
6 import unittest
7 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
9 from test.helper import (
10 assertGreaterEqual,
11 expect_warnings,
12 get_params,
13 gettestcases,
14 expect_info_dict,
15 try_rm,
16 report_warning,
17 )
18
19
20 import hashlib
21 import io
22 import json
23 import socket
24
25 import youtube_dl.YoutubeDL
26 from youtube_dl.utils import (
27 compat_http_client,
28 compat_urllib_error,
29 compat_HTTPError,
30 DownloadError,
31 ExtractorError,
32 format_bytes,
33 UnavailableVideoError,
34 )
35 from youtube_dl.extractor import get_info_extractor
36
37 RETRIES = 3
38
39 class YoutubeDL(youtube_dl.YoutubeDL):
40 def __init__(self, *args, **kwargs):
41 self.to_stderr = self.to_screen
42 self.processed_info_dicts = []
43 super(YoutubeDL, self).__init__(*args, **kwargs)
44 def report_warning(self, message):
45 # Don't accept warnings during tests
46 raise ExtractorError(message)
47 def process_info(self, info_dict):
48 self.processed_info_dicts.append(info_dict)
49 return super(YoutubeDL, self).process_info(info_dict)
50
51 def _file_md5(fn):
52 with open(fn, 'rb') as f:
53 return hashlib.md5(f.read()).hexdigest()
54
55 defs = gettestcases()
56
57
58 class TestDownload(unittest.TestCase):
59 maxDiff = None
60 def setUp(self):
61 self.defs = defs
62
63 ### Dynamically generate tests
64 def generator(test_case):
65
66 def test_template(self):
67 ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
68 other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
69 is_playlist = any(k.startswith('playlist') for k in test_case)
70 test_cases = test_case.get(
71 'playlist', [] if is_playlist else [test_case])
72
73 def print_skipping(reason):
74 print('Skipping %s: %s' % (test_case['name'], reason))
75 if not ie.working():
76 print_skipping('IE marked as not _WORKING')
77 return
78
79 for tc in test_cases:
80 info_dict = tc.get('info_dict', {})
81 if not tc.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
82 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
83
84 if 'skip' in test_case:
85 print_skipping(test_case['skip'])
86 return
87 for other_ie in other_ies:
88 if not other_ie.working():
89 print_skipping(u'test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
90 return
91
92 params = get_params(test_case.get('params', {}))
93 if is_playlist and 'playlist' not in test_case:
94 params.setdefault('extract_flat', True)
95 params.setdefault('skip_download', True)
96
97 ydl = YoutubeDL(params)
98 ydl.add_default_info_extractors()
99 finished_hook_called = set()
100 def _hook(status):
101 if status['status'] == 'finished':
102 finished_hook_called.add(status['filename'])
103 ydl.add_progress_hook(_hook)
104 expect_warnings(ydl, test_case.get('expected_warnings', []))
105
106 def get_tc_filename(tc):
107 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
108
109 res_dict = None
110 def try_rm_tcs_files(tcs=None):
111 if tcs is None:
112 tcs = test_cases
113 for tc in tcs:
114 tc_filename = get_tc_filename(tc)
115 try_rm(tc_filename)
116 try_rm(tc_filename + '.part')
117 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
118 try_rm_tcs_files()
119 try:
120 try_num = 1
121 while True:
122 try:
123 # We're not using .download here sine that is just a shim
124 # for outside error handling, and returns the exit code
125 # instead of the result dict.
126 res_dict = ydl.extract_info(test_case['url'])
127 except (DownloadError, ExtractorError) as err:
128 # Check if the exception is not a network related one
129 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 raise
131
132 if try_num == RETRIES:
133 report_warning(u'Failed due to network errors, skipping...')
134 return
135
136 print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
137
138 try_num += 1
139 else:
140 break
141
142 if is_playlist:
143 self.assertEqual(res_dict['_type'], 'playlist')
144 self.assertTrue('entries' in res_dict)
145 expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
146
147 if 'playlist_mincount' in test_case:
148 assertGreaterEqual(
149 self,
150 len(res_dict['entries']),
151 test_case['playlist_mincount'],
152 'Expected at least %d in playlist %s, but got only %d' % (
153 test_case['playlist_mincount'], test_case['url'],
154 len(res_dict['entries'])))
155 if 'playlist_count' in test_case:
156 self.assertEqual(
157 len(res_dict['entries']),
158 test_case['playlist_count'],
159 'Expected %d entries in playlist %s, but got %d.' % (
160 test_case['playlist_count'],
161 test_case['url'],
162 len(res_dict['entries']),
163 ))
164 if 'playlist_duration_sum' in test_case:
165 got_duration = sum(e['duration'] for e in res_dict['entries'])
166 self.assertEqual(
167 test_case['playlist_duration_sum'], got_duration)
168
169 for tc in test_cases:
170 tc_filename = get_tc_filename(tc)
171 if not test_case.get('params', {}).get('skip_download', False):
172 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
173 self.assertTrue(tc_filename in finished_hook_called)
174 expected_minsize = tc.get('file_minsize', 10000)
175 if expected_minsize is not None:
176 if params.get('test'):
177 expected_minsize = max(expected_minsize, 10000)
178 got_fsize = os.path.getsize(tc_filename)
179 assertGreaterEqual(
180 self, got_fsize, expected_minsize,
181 'Expected %s to be at least %s, but it\'s only %s ' %
182 (tc_filename, format_bytes(expected_minsize),
183 format_bytes(got_fsize)))
184 if 'md5' in tc:
185 md5_for_file = _file_md5(tc_filename)
186 self.assertEqual(md5_for_file, tc['md5'])
187 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
188 self.assertTrue(
189 os.path.exists(info_json_fn),
190 'Missing info file %s' % info_json_fn)
191 with io.open(info_json_fn, encoding='utf-8') as infof:
192 info_dict = json.load(infof)
193
194 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
195 finally:
196 try_rm_tcs_files()
197 if is_playlist and res_dict is not None and res_dict.get('entries'):
198 # Remove all other files that may have been extracted if the
199 # extractor returns full results even with extract_flat
200 res_tcs = [{'info_dict': e} for e in res_dict['entries']]
201 try_rm_tcs_files(res_tcs)
202
203 return test_template
204
205 ### And add them to TestDownload
206 for n, test_case in enumerate(defs):
207 test_method = generator(test_case)
208 tname = 'test_' + str(test_case['name'])
209 i = 1
210 while hasattr(TestDownload, tname):
211 tname = 'test_' + str(test_case['name']) + '_' + str(i)
212 i += 1
213 test_method.__name__ = tname
214 setattr(TestDownload, test_method.__name__, test_method)
215 del test_method
216
217
218 if __name__ == '__main__':
219 unittest.main()