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