]> git.bitcoin.ninja Git - youtube-dl/blob - test/test_download.py
[test_compat] Ignore unicode_literals
[youtube-dl] / 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.compat import (
27     compat_http_client,
28     compat_urllib_error,
29     compat_HTTPError,
30 )
31 from youtube_dl.utils import (
32     DownloadError,
33     ExtractorError,
34     format_bytes,
35     UnavailableVideoError,
36 )
37 from youtube_dl.extractor import get_info_extractor
38
39 RETRIES = 3
40
41 class YoutubeDL(youtube_dl.YoutubeDL):
42     def __init__(self, *args, **kwargs):
43         self.to_stderr = self.to_screen
44         self.processed_info_dicts = []
45         super(YoutubeDL, self).__init__(*args, **kwargs)
46     def report_warning(self, message):
47         # Don't accept warnings during tests
48         raise ExtractorError(message)
49     def process_info(self, info_dict):
50         self.processed_info_dicts.append(info_dict)
51         return super(YoutubeDL, self).process_info(info_dict)
52
53 def _file_md5(fn):
54     with open(fn, 'rb') as f:
55         return hashlib.md5(f.read()).hexdigest()
56
57 defs = gettestcases()
58
59
60 class TestDownload(unittest.TestCase):
61     maxDiff = None
62     def setUp(self):
63         self.defs = defs
64
65 ### Dynamically generate tests
66 def generator(test_case):
67
68     def test_template(self):
69         ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
70         other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
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
75         def print_skipping(reason):
76             print('Skipping %s: %s' % (test_case['name'], reason))
77         if not ie.working():
78             print_skipping('IE marked as not _WORKING')
79             return
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')):
84                 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
85
86         if 'skip' in test_case:
87             print_skipping(test_case['skip'])
88             return
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
93
94         params = get_params(test_case.get('params', {}))
95         if is_playlist and 'playlist' not in test_case:
96             params.setdefault('extract_flat', True)
97             params.setdefault('skip_download', True)
98
99         ydl = YoutubeDL(params, auto_init=False)
100         ydl.add_default_info_extractors()
101         finished_hook_called = set()
102         def _hook(status):
103             if status['status'] == 'finished':
104                 finished_hook_called.add(status['filename'])
105         ydl.add_progress_hook(_hook)
106         expect_warnings(ydl, test_case.get('expected_warnings', []))
107
108         def get_tc_filename(tc):
109             return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
110
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:
116                 tc_filename = get_tc_filename(tc)
117                 try_rm(tc_filename)
118                 try_rm(tc_filename + '.part')
119                 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
120         try_rm_tcs_files()
121         try:
122             try_num = 1
123             while True:
124                 try:
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'])
129                 except (DownloadError, ExtractorError) as err:
130                     # Check if the exception is not a network related one
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):
132                         raise
133
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
141                 else:
142                     break
143
144             if is_playlist:
145                 self.assertEqual(res_dict['_type'], 'playlist')
146                 self.assertTrue('entries' in res_dict)
147                 expect_info_dict(self, test_case.get('info_dict', {}), res_dict)
148
149             if 'playlist_mincount' in test_case:
150                 assertGreaterEqual(
151                     self,
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'])))
157             if 'playlist_count' in test_case:
158                 self.assertEqual(
159                     len(res_dict['entries']),
160                     test_case['playlist_count'],
161                     'Expected %d entries in playlist %s, but got %d.' % (
162                         test_case['playlist_count'],
163                         test_case['url'],
164                         len(res_dict['entries']),
165                     ))
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)
170
171             for tc in test_cases:
172                 tc_filename = get_tc_filename(tc)
173                 if not test_case.get('params', {}).get('skip_download', False):
174                     self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
175                     self.assertTrue(tc_filename in finished_hook_called)
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'])
189                 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
190                 self.assertTrue(
191                     os.path.exists(info_json_fn),
192                     'Missing info file %s' % info_json_fn)
193                 with io.open(info_json_fn, encoding='utf-8') as infof:
194                     info_dict = json.load(infof)
195
196                 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
197         finally:
198             try_rm_tcs_files()
199             if is_playlist and res_dict is not None and res_dict.get('entries'):
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)
204
205     return test_template
206
207 ### And add them to TestDownload
208 for n, test_case in enumerate(defs):
209     test_method = generator(test_case)
210     tname = 'test_' + str(test_case['name'])
211     i = 1
212     while hasattr(TestDownload, tname):
213         tname = 'test_'  + str(test_case['name']) + '_' + str(i)
214         i += 1
215     test_method.__name__ = tname
216     setattr(TestDownload, test_method.__name__, test_method)
217     del test_method
218
219
220 if __name__ == '__main__':
221     unittest.main()