]> jfr.im git - yt-dlp.git/blame - test/test_download.py
release 2014.08.29
[yt-dlp.git] / test / test_download.py
CommitLineData
fd5ff020
FV
1#!/usr/bin/env python
2
44a5f171
PH
3# Allow direct execution
4import os
5import sys
6import unittest
7sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
dd508b7c 9from test.helper import (
0990305d 10 assertGreaterEqual,
dd508b7c 11 get_params,
ff14fc49 12 gettestcases,
257cfebf 13 expect_info_dict,
257cfebf
PH
14 try_rm,
15 report_warning,
dd508b7c 16)
44a5f171
PH
17
18
efe8902f 19import hashlib
fd5ff020 20import io
7f60b5aa 21import json
6b3aef80 22import socket
cdab8aa3 23
8222d8de 24import youtube_dl.YoutubeDL
44a5f171 25from youtube_dl.utils import (
dcf3eec4 26 compat_http_client,
44a5f171 27 compat_urllib_error,
f6cc16f5 28 compat_HTTPError,
44a5f171
PH
29 DownloadError,
30 ExtractorError,
753727cd 31 format_bytes,
44a5f171
PH
32 UnavailableVideoError,
33)
9ee2b5f6 34from youtube_dl.extractor import get_info_extractor
fd5ff020 35
8cc83b8d
FV
36RETRIES = 3
37
8222d8de 38class YoutubeDL(youtube_dl.YoutubeDL):
fd5ff020 39 def __init__(self, *args, **kwargs):
fd5ff020 40 self.to_stderr = self.to_screen
0eaf520d 41 self.processed_info_dicts = []
8222d8de 42 super(YoutubeDL, self).__init__(*args, **kwargs)
476203d0 43 def report_warning(self, message):
be95cac1
FV
44 # Don't accept warnings during tests
45 raise ExtractorError(message)
0eaf520d
FV
46 def process_info(self, info_dict):
47 self.processed_info_dicts.append(info_dict)
8222d8de 48 return super(YoutubeDL, self).process_info(info_dict)
1535ac2a 49
fd5ff020
FV
50def _file_md5(fn):
51 with open(fn, 'rb') as f:
52 return hashlib.md5(f.read()).hexdigest()
53
ff14fc49 54defs = gettestcases()
6b47c7f2 55
0eaf520d 56
1535ac2a 57class TestDownload(unittest.TestCase):
744435f2 58 maxDiff = None
fd5ff020 59 def setUp(self):
fd5ff020
FV
60 self.defs = defs
61
911ee27e 62### Dynamically generate tests
5d01a647
PH
63def generator(test_case):
64
1535ac2a 65 def test_template(self):
d1cade5a 66 ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
9ee2b5f6 67 other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
e8ee972c
PH
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
bc2884af
JMF
72 def print_skipping(reason):
73 print('Skipping %s: %s' % (test_case['name'], reason))
9ee2b5f6 74 if not ie.working():
bc2884af 75 print_skipping('IE marked as not _WORKING')
fd5ff020 76 return
e8ee972c
PH
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')):
2437fbca 81 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
e8ee972c 82
fd5ff020 83 if 'skip' in test_case:
bc2884af 84 print_skipping(test_case['skip'])
fd5ff020 85 return
9ee2b5f6
JMF
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
0eaf520d 90
44a5f171 91 params = get_params(test_case.get('params', {}))
e8ee972c
PH
92 if is_playlist and 'playlist' not in test_case:
93 params.setdefault('extract_flat', True)
94 params.setdefault('skip_download', True)
0eaf520d 95
8222d8de 96 ydl = YoutubeDL(params)
023fa8c4 97 ydl.add_default_info_extractors()
bffbd5f0
PH
98 finished_hook_called = set()
99 def _hook(status):
100 if status['status'] == 'finished':
101 finished_hook_called.add(status['filename'])
933605d7 102 ydl.add_progress_hook(_hook)
5c892b0b 103
702665c0
JMF
104 def get_tc_filename(tc):
105 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
106
28570840
PH
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:
702665c0
JMF
112 tc_filename = get_tc_filename(tc)
113 try_rm(tc_filename)
114 try_rm(tc_filename + '.part')
4eb92208 115 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
702665c0 116 try_rm_tcs_files()
5c892b0b 117 try:
dd508b7c
FV
118 try_num = 1
119 while True:
8cc83b8d 120 try:
e8ee972c
PH
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'])
8cc83b8d 125 except (DownloadError, ExtractorError) as err:
8cc83b8d 126 # Check if the exception is not a network related one
dcf3eec4 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):
8cc83b8d
FV
128 raise
129
dd508b7c
FV
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
8cc83b8d
FV
137 else:
138 break
5c892b0b 139
e8ee972c
PH
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:
0990305d
PH
144 assertGreaterEqual(
145 self,
e8ee972c
PH
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'])))
829476b8
PH
151 if 'playlist_count' in test_case:
152 self.assertEqual(
153 len(res_dict['entries']),
154 test_case['playlist_count'],
28570840 155 'Expected %d entries in playlist %s, but got %d.' % (
22a6f150 156 test_case['playlist_count'],
28570840 157 test_case['url'],
22a6f150
PH
158 len(res_dict['entries']),
159 ))
28570840
PH
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)
e8ee972c 164
5c892b0b 165 for tc in test_cases:
702665c0 166 tc_filename = get_tc_filename(tc)
511eda8e 167 if not test_case.get('params', {}).get('skip_download', False):
702665c0
JMF
168 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
169 self.assertTrue(tc_filename in finished_hook_called)
4eb92208
PH
170 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
171 self.assertTrue(os.path.exists(info_json_fn))
5c892b0b 172 if 'md5' in tc:
702665c0 173 md5_for_file = _file_md5(tc_filename)
5c892b0b 174 self.assertEqual(md5_for_file, tc['md5'])
753727cd
PH
175 expected_minsize = tc.get('file_minsize', 10000)
176 if expected_minsize is not None:
177 if params.get('test'):
178 expected_minsize = max(expected_minsize, 10000)
179 got_fsize = os.path.getsize(tc_filename)
180 assertGreaterEqual(
181 self, got_fsize, expected_minsize,
182 'Expected %s to be at least %s, but it\'s only %s ' %
183 (tc_filename, format_bytes(expected_minsize),
184 format_bytes(got_fsize)))
4eb92208 185 with io.open(info_json_fn, encoding='utf-8') as infof:
5c892b0b 186 info_dict = json.load(infof)
257cfebf
PH
187
188 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
5c892b0b 189 finally:
702665c0 190 try_rm_tcs_files()
28570840
PH
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)
fd5ff020 196
1535ac2a 197 return test_template
fd5ff020 198
5d01a647 199### And add them to TestDownload
f7ab6cbe 200for n, test_case in enumerate(defs):
5d01a647 201 test_method = generator(test_case)
2eb88d95
PH
202 tname = 'test_' + str(test_case['name'])
203 i = 1
204 while hasattr(TestDownload, tname):
41beccba 205 tname = 'test_' + str(test_case['name']) + '_' + str(i)
2eb88d95
PH
206 i += 1
207 test_method.__name__ = tname
fd5ff020 208 setattr(TestDownload, test_method.__name__, test_method)
5d01a647 209 del test_method
cdab8aa3
PH
210
211
212if __name__ == '__main__':
213 unittest.main()