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