]>
Raphaƫl G. Git Repositories - youtubedl/blob - test/test_download.py
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
.utils
import (
33 UnavailableVideoError
,
35 from youtube_dl
.extractor
import get_info_extractor
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
)
52 with open(fn
, 'rb') as f
:
53 return hashlib
.md5(f
.read()).hexdigest()
58 class TestDownload(unittest
.TestCase
):
63 ### Dynamically generate tests
64 def generator(test_case
):
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
])
73 def print_skipping(reason
):
74 print('Skipping %s: %s' % (test_case
['name'], reason
))
76 print_skipping('IE marked as not _WORKING')
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?')
84 if 'skip' in test_case
:
85 print_skipping(test_case
['skip'])
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())
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)
97 ydl
= YoutubeDL(params
)
98 ydl
.add_default_info_extractors()
99 finished_hook_called
= set()
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', []))
106 def get_tc_filename(tc
):
107 return tc
.get('file') or ydl
.prepare_filename(tc
.get('info_dict', {}))
110 def try_rm_tcs_files(tcs
=None):
114 tc_filename
= get_tc_filename(tc
)
116 try_rm(tc_filename
+ '.part')
117 try_rm(os
.path
.splitext(tc_filename
)[0] + '.info.json')
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):
132 if try_num
== RETRIES
:
133 report_warning(u
'Failed due to network errors, skipping...')
136 print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num
))
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
)
147 if 'playlist_mincount' in test_case
:
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
:
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'],
162 len(res_dict
['entries']),
164 if 'playlist_duration_sum' in test_case
:
165 got_duration
= sum(e
['duration'] for e
in res_dict
['entries'])
167 test_case
['playlist_duration_sum'], got_duration
)
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
)
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
)))
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'
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
)
194 expect_info_dict(self
, tc
.get('info_dict', {}), info_dict
)
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
)
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'])
210 while hasattr(TestDownload
, tname
):
211 tname
= 'test_' + str(test_case
['name']) + '_' + str(i
)
213 test_method
.__name
__ = tname
214 setattr(TestDownload
, test_method
.__name
__, test_method
)
218 if __name__
== '__main__':