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