]>
Commit | Line | Data |
---|---|---|
fd5ff020 FV |
1 | #!/usr/bin/env python |
2 | ||
44a5f171 PH |
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 | ||
dd508b7c | 9 | from test.helper import ( |
0990305d | 10 | assertGreaterEqual, |
70b7e3fb | 11 | expect_warnings, |
dd508b7c | 12 | get_params, |
ff14fc49 | 13 | gettestcases, |
257cfebf | 14 | expect_info_dict, |
257cfebf PH |
15 | try_rm, |
16 | report_warning, | |
dd508b7c | 17 | ) |
44a5f171 PH |
18 | |
19 | ||
efe8902f | 20 | import hashlib |
fd5ff020 | 21 | import io |
7f60b5aa | 22 | import json |
6b3aef80 | 23 | import socket |
cdab8aa3 | 24 | |
8222d8de | 25 | import youtube_dl.YoutubeDL |
42f7d2f5 | 26 | from youtube_dl.compat import ( |
dcf3eec4 | 27 | compat_http_client, |
44a5f171 | 28 | compat_urllib_error, |
f6cc16f5 | 29 | compat_HTTPError, |
42f7d2f5 PH |
30 | ) |
31 | from youtube_dl.utils import ( | |
44a5f171 PH |
32 | DownloadError, |
33 | ExtractorError, | |
753727cd | 34 | format_bytes, |
44a5f171 PH |
35 | UnavailableVideoError, |
36 | ) | |
9ee2b5f6 | 37 | from youtube_dl.extractor import get_info_extractor |
fd5ff020 | 38 | |
8cc83b8d FV |
39 | RETRIES = 3 |
40 | ||
8222d8de | 41 | class YoutubeDL(youtube_dl.YoutubeDL): |
fd5ff020 | 42 | def __init__(self, *args, **kwargs): |
fd5ff020 | 43 | self.to_stderr = self.to_screen |
0eaf520d | 44 | self.processed_info_dicts = [] |
8222d8de | 45 | super(YoutubeDL, self).__init__(*args, **kwargs) |
476203d0 | 46 | def report_warning(self, message): |
be95cac1 FV |
47 | # Don't accept warnings during tests |
48 | raise ExtractorError(message) | |
0eaf520d FV |
49 | def process_info(self, info_dict): |
50 | self.processed_info_dicts.append(info_dict) | |
8222d8de | 51 | return super(YoutubeDL, self).process_info(info_dict) |
1535ac2a | 52 | |
fd5ff020 FV |
53 | def _file_md5(fn): |
54 | with open(fn, 'rb') as f: | |
55 | return hashlib.md5(f.read()).hexdigest() | |
56 | ||
ff14fc49 | 57 | defs = gettestcases() |
6b47c7f2 | 58 | |
0eaf520d | 59 | |
1535ac2a | 60 | class TestDownload(unittest.TestCase): |
744435f2 | 61 | maxDiff = None |
fd5ff020 | 62 | def setUp(self): |
fd5ff020 FV |
63 | self.defs = defs |
64 | ||
911ee27e | 65 | ### Dynamically generate tests |
5d01a647 PH |
66 | def generator(test_case): |
67 | ||
1535ac2a | 68 | def test_template(self): |
d1cade5a | 69 | ie = youtube_dl.extractor.get_info_extractor(test_case['name']) |
9ee2b5f6 | 70 | other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])] |
e8ee972c PH |
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]) | |
74 | ||
bc2884af JMF |
75 | def print_skipping(reason): |
76 | print('Skipping %s: %s' % (test_case['name'], reason)) | |
9ee2b5f6 | 77 | if not ie.working(): |
bc2884af | 78 | print_skipping('IE marked as not _WORKING') |
fd5ff020 | 79 | return |
e8ee972c PH |
80 | |
81 | for tc in test_cases: | |
82 | info_dict = tc.get('info_dict', {}) | |
83 | if not tc.get('file') and not (info_dict.get('id') and info_dict.get('ext')): | |
2437fbca | 84 | raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?') |
e8ee972c | 85 | |
fd5ff020 | 86 | if 'skip' in test_case: |
bc2884af | 87 | print_skipping(test_case['skip']) |
fd5ff020 | 88 | return |
9ee2b5f6 JMF |
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()) | |
92 | return | |
0eaf520d | 93 | |
44a5f171 | 94 | params = get_params(test_case.get('params', {})) |
e8ee972c PH |
95 | if is_playlist and 'playlist' not in test_case: |
96 | params.setdefault('extract_flat', True) | |
97 | params.setdefault('skip_download', True) | |
0eaf520d | 98 | |
8222d8de | 99 | ydl = YoutubeDL(params) |
023fa8c4 | 100 | ydl.add_default_info_extractors() |
bffbd5f0 PH |
101 | finished_hook_called = set() |
102 | def _hook(status): | |
103 | if status['status'] == 'finished': | |
104 | finished_hook_called.add(status['filename']) | |
933605d7 | 105 | ydl.add_progress_hook(_hook) |
70b7e3fb | 106 | expect_warnings(ydl, test_case.get('expected_warnings', [])) |
5c892b0b | 107 | |
702665c0 JMF |
108 | def get_tc_filename(tc): |
109 | return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {})) | |
110 | ||
28570840 PH |
111 | res_dict = None |
112 | def try_rm_tcs_files(tcs=None): | |
113 | if tcs is None: | |
114 | tcs = test_cases | |
115 | for tc in tcs: | |
702665c0 JMF |
116 | tc_filename = get_tc_filename(tc) |
117 | try_rm(tc_filename) | |
118 | try_rm(tc_filename + '.part') | |
4eb92208 | 119 | try_rm(os.path.splitext(tc_filename)[0] + '.info.json') |
702665c0 | 120 | try_rm_tcs_files() |
5c892b0b | 121 | try: |
dd508b7c FV |
122 | try_num = 1 |
123 | while True: | |
8cc83b8d | 124 | try: |
e8ee972c PH |
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']) | |
8cc83b8d | 129 | except (DownloadError, ExtractorError) as err: |
8cc83b8d | 130 | # Check if the exception is not a network related one |
dcf3eec4 | 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): |
8cc83b8d FV |
132 | raise |
133 | ||
dd508b7c FV |
134 | if try_num == RETRIES: |
135 | report_warning(u'Failed due to network errors, skipping...') | |
136 | return | |
137 | ||
138 | print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num)) | |
139 | ||
140 | try_num += 1 | |
8cc83b8d FV |
141 | else: |
142 | break | |
5c892b0b | 143 | |
e8ee972c PH |
144 | if is_playlist: |
145 | self.assertEqual(res_dict['_type'], 'playlist') | |
d6e6a422 | 146 | self.assertTrue('entries' in res_dict) |
e8ee972c | 147 | expect_info_dict(self, test_case.get('info_dict', {}), res_dict) |
d6e6a422 | 148 | |
e8ee972c | 149 | if 'playlist_mincount' in test_case: |
0990305d PH |
150 | assertGreaterEqual( |
151 | self, | |
e8ee972c PH |
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']))) | |
829476b8 PH |
157 | if 'playlist_count' in test_case: |
158 | self.assertEqual( | |
159 | len(res_dict['entries']), | |
160 | test_case['playlist_count'], | |
28570840 | 161 | 'Expected %d entries in playlist %s, but got %d.' % ( |
22a6f150 | 162 | test_case['playlist_count'], |
28570840 | 163 | test_case['url'], |
22a6f150 PH |
164 | len(res_dict['entries']), |
165 | )) | |
28570840 PH |
166 | if 'playlist_duration_sum' in test_case: |
167 | got_duration = sum(e['duration'] for e in res_dict['entries']) | |
168 | self.assertEqual( | |
169 | test_case['playlist_duration_sum'], got_duration) | |
e8ee972c | 170 | |
5c892b0b | 171 | for tc in test_cases: |
702665c0 | 172 | tc_filename = get_tc_filename(tc) |
511eda8e | 173 | if not test_case.get('params', {}).get('skip_download', False): |
702665c0 JMF |
174 | self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename) |
175 | self.assertTrue(tc_filename in finished_hook_called) | |
08a36c35 S |
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) | |
181 | assertGreaterEqual( | |
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))) | |
186 | if 'md5' in tc: | |
187 | md5_for_file = _file_md5(tc_filename) | |
188 | self.assertEqual(md5_for_file, tc['md5']) | |
4eb92208 | 189 | info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json' |
f744c0f3 PH |
190 | self.assertTrue( |
191 | os.path.exists(info_json_fn), | |
192 | 'Missing info file %s' % info_json_fn) | |
4eb92208 | 193 | with io.open(info_json_fn, encoding='utf-8') as infof: |
5c892b0b | 194 | info_dict = json.load(infof) |
257cfebf PH |
195 | |
196 | expect_info_dict(self, tc.get('info_dict', {}), info_dict) | |
5c892b0b | 197 | finally: |
702665c0 | 198 | try_rm_tcs_files() |
d6e6a422 | 199 | if is_playlist and res_dict is not None and res_dict.get('entries'): |
28570840 PH |
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) | |
fd5ff020 | 204 | |
1535ac2a | 205 | return test_template |
fd5ff020 | 206 | |
5d01a647 | 207 | ### And add them to TestDownload |
f7ab6cbe | 208 | for n, test_case in enumerate(defs): |
5d01a647 | 209 | test_method = generator(test_case) |
2eb88d95 PH |
210 | tname = 'test_' + str(test_case['name']) |
211 | i = 1 | |
212 | while hasattr(TestDownload, tname): | |
41beccba | 213 | tname = 'test_' + str(test_case['name']) + '_' + str(i) |
2eb88d95 PH |
214 | i += 1 |
215 | test_method.__name__ = tname | |
fd5ff020 | 216 | setattr(TestDownload, test_method.__name__, test_method) |
5d01a647 | 217 | del test_method |
cdab8aa3 PH |
218 | |
219 | ||
220 | if __name__ == '__main__': | |
221 | unittest.main() |