]>
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 |
44a5f171 | 26 | from youtube_dl.utils import ( |
dcf3eec4 | 27 | compat_http_client, |
44a5f171 | 28 | compat_urllib_error, |
f6cc16f5 | 29 | compat_HTTPError, |
44a5f171 PH |
30 | DownloadError, |
31 | ExtractorError, | |
753727cd | 32 | format_bytes, |
44a5f171 PH |
33 | UnavailableVideoError, |
34 | ) | |
9ee2b5f6 | 35 | from youtube_dl.extractor import get_info_extractor |
fd5ff020 | 36 | |
8cc83b8d FV |
37 | RETRIES = 3 |
38 | ||
8222d8de | 39 | class YoutubeDL(youtube_dl.YoutubeDL): |
fd5ff020 | 40 | def __init__(self, *args, **kwargs): |
fd5ff020 | 41 | self.to_stderr = self.to_screen |
0eaf520d | 42 | self.processed_info_dicts = [] |
8222d8de | 43 | super(YoutubeDL, self).__init__(*args, **kwargs) |
476203d0 | 44 | def report_warning(self, message): |
be95cac1 FV |
45 | # Don't accept warnings during tests |
46 | raise ExtractorError(message) | |
0eaf520d FV |
47 | def process_info(self, info_dict): |
48 | self.processed_info_dicts.append(info_dict) | |
8222d8de | 49 | return super(YoutubeDL, self).process_info(info_dict) |
1535ac2a | 50 | |
fd5ff020 FV |
51 | def _file_md5(fn): |
52 | with open(fn, 'rb') as f: | |
53 | return hashlib.md5(f.read()).hexdigest() | |
54 | ||
ff14fc49 | 55 | defs = gettestcases() |
6b47c7f2 | 56 | |
0eaf520d | 57 | |
1535ac2a | 58 | class TestDownload(unittest.TestCase): |
744435f2 | 59 | maxDiff = None |
fd5ff020 | 60 | def setUp(self): |
fd5ff020 FV |
61 | self.defs = defs |
62 | ||
911ee27e | 63 | ### Dynamically generate tests |
5d01a647 PH |
64 | def generator(test_case): |
65 | ||
1535ac2a | 66 | def test_template(self): |
d1cade5a | 67 | ie = youtube_dl.extractor.get_info_extractor(test_case['name']) |
9ee2b5f6 | 68 | other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])] |
e8ee972c PH |
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 | ||
bc2884af JMF |
73 | def print_skipping(reason): |
74 | print('Skipping %s: %s' % (test_case['name'], reason)) | |
9ee2b5f6 | 75 | if not ie.working(): |
bc2884af | 76 | print_skipping('IE marked as not _WORKING') |
fd5ff020 | 77 | return |
e8ee972c PH |
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')): | |
2437fbca | 82 | raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?') |
e8ee972c | 83 | |
fd5ff020 | 84 | if 'skip' in test_case: |
bc2884af | 85 | print_skipping(test_case['skip']) |
fd5ff020 | 86 | return |
9ee2b5f6 JMF |
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 | |
0eaf520d | 91 | |
44a5f171 | 92 | params = get_params(test_case.get('params', {})) |
e8ee972c PH |
93 | if is_playlist and 'playlist' not in test_case: |
94 | params.setdefault('extract_flat', True) | |
95 | params.setdefault('skip_download', True) | |
0eaf520d | 96 | |
8222d8de | 97 | ydl = YoutubeDL(params) |
023fa8c4 | 98 | ydl.add_default_info_extractors() |
bffbd5f0 PH |
99 | finished_hook_called = set() |
100 | def _hook(status): | |
101 | if status['status'] == 'finished': | |
102 | finished_hook_called.add(status['filename']) | |
933605d7 | 103 | ydl.add_progress_hook(_hook) |
70b7e3fb | 104 | expect_warnings(ydl, test_case.get('expected_warnings', [])) |
5c892b0b | 105 | |
702665c0 JMF |
106 | def get_tc_filename(tc): |
107 | return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {})) | |
108 | ||
28570840 PH |
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: | |
702665c0 JMF |
114 | tc_filename = get_tc_filename(tc) |
115 | try_rm(tc_filename) | |
116 | try_rm(tc_filename + '.part') | |
4eb92208 | 117 | try_rm(os.path.splitext(tc_filename)[0] + '.info.json') |
702665c0 | 118 | try_rm_tcs_files() |
5c892b0b | 119 | try: |
dd508b7c FV |
120 | try_num = 1 |
121 | while True: | |
8cc83b8d | 122 | try: |
e8ee972c PH |
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']) | |
8cc83b8d | 127 | except (DownloadError, ExtractorError) as err: |
8cc83b8d | 128 | # Check if the exception is not a network related one |
dcf3eec4 | 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): |
8cc83b8d FV |
130 | raise |
131 | ||
dd508b7c FV |
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 | |
8cc83b8d FV |
139 | else: |
140 | break | |
5c892b0b | 141 | |
e8ee972c PH |
142 | if is_playlist: |
143 | self.assertEqual(res_dict['_type'], 'playlist') | |
d6e6a422 | 144 | self.assertTrue('entries' in res_dict) |
e8ee972c | 145 | expect_info_dict(self, test_case.get('info_dict', {}), res_dict) |
d6e6a422 | 146 | |
e8ee972c | 147 | if 'playlist_mincount' in test_case: |
0990305d PH |
148 | assertGreaterEqual( |
149 | self, | |
e8ee972c PH |
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']))) | |
829476b8 PH |
155 | if 'playlist_count' in test_case: |
156 | self.assertEqual( | |
157 | len(res_dict['entries']), | |
158 | test_case['playlist_count'], | |
28570840 | 159 | 'Expected %d entries in playlist %s, but got %d.' % ( |
22a6f150 | 160 | test_case['playlist_count'], |
28570840 | 161 | test_case['url'], |
22a6f150 PH |
162 | len(res_dict['entries']), |
163 | )) | |
28570840 PH |
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) | |
e8ee972c | 168 | |
5c892b0b | 169 | for tc in test_cases: |
702665c0 | 170 | tc_filename = get_tc_filename(tc) |
511eda8e | 171 | if not test_case.get('params', {}).get('skip_download', False): |
702665c0 JMF |
172 | self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename) |
173 | self.assertTrue(tc_filename in finished_hook_called) | |
08a36c35 S |
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']) | |
4eb92208 PH |
187 | info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json' |
188 | self.assertTrue(os.path.exists(info_json_fn)) | |
4eb92208 | 189 | with io.open(info_json_fn, encoding='utf-8') as infof: |
5c892b0b | 190 | info_dict = json.load(infof) |
257cfebf PH |
191 | |
192 | expect_info_dict(self, tc.get('info_dict', {}), info_dict) | |
5c892b0b | 193 | finally: |
702665c0 | 194 | try_rm_tcs_files() |
d6e6a422 | 195 | if is_playlist and res_dict is not None and res_dict.get('entries'): |
28570840 PH |
196 | # Remove all other files that may have been extracted if the |
197 | # extractor returns full results even with extract_flat | |
198 | res_tcs = [{'info_dict': e} for e in res_dict['entries']] | |
199 | try_rm_tcs_files(res_tcs) | |
fd5ff020 | 200 | |
1535ac2a | 201 | return test_template |
fd5ff020 | 202 | |
5d01a647 | 203 | ### And add them to TestDownload |
f7ab6cbe | 204 | for n, test_case in enumerate(defs): |
5d01a647 | 205 | test_method = generator(test_case) |
2eb88d95 PH |
206 | tname = 'test_' + str(test_case['name']) |
207 | i = 1 | |
208 | while hasattr(TestDownload, tname): | |
41beccba | 209 | tname = 'test_' + str(test_case['name']) + '_' + str(i) |
2eb88d95 PH |
210 | i += 1 |
211 | test_method.__name__ = tname | |
fd5ff020 | 212 | setattr(TestDownload, test_method.__name__, test_method) |
5d01a647 | 213 | del test_method |
cdab8aa3 PH |
214 | |
215 | ||
216 | if __name__ == '__main__': | |
217 | unittest.main() |