]> jfr.im git - yt-dlp.git/blame - test/test_download.py
release 2014.08.25.2
[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
FV
9from test.helper import (
10 get_params,
ff14fc49 11 gettestcases,
257cfebf 12 expect_info_dict,
257cfebf
PH
13 try_rm,
14 report_warning,
dd508b7c 15)
44a5f171
PH
16
17
efe8902f 18import hashlib
fd5ff020 19import io
7f60b5aa 20import json
6b3aef80 21import socket
cdab8aa3 22
8222d8de 23import youtube_dl.YoutubeDL
44a5f171 24from youtube_dl.utils import (
dcf3eec4 25 compat_http_client,
44a5f171 26 compat_urllib_error,
f6cc16f5 27 compat_HTTPError,
44a5f171
PH
28 DownloadError,
29 ExtractorError,
30 UnavailableVideoError,
31)
9ee2b5f6 32from youtube_dl.extractor import get_info_extractor
fd5ff020 33
8cc83b8d
FV
34RETRIES = 3
35
8222d8de 36class YoutubeDL(youtube_dl.YoutubeDL):
fd5ff020 37 def __init__(self, *args, **kwargs):
fd5ff020 38 self.to_stderr = self.to_screen
0eaf520d 39 self.processed_info_dicts = []
8222d8de 40 super(YoutubeDL, self).__init__(*args, **kwargs)
476203d0 41 def report_warning(self, message):
be95cac1
FV
42 # Don't accept warnings during tests
43 raise ExtractorError(message)
0eaf520d
FV
44 def process_info(self, info_dict):
45 self.processed_info_dicts.append(info_dict)
8222d8de 46 return super(YoutubeDL, self).process_info(info_dict)
1535ac2a 47
fd5ff020
FV
48def _file_md5(fn):
49 with open(fn, 'rb') as f:
50 return hashlib.md5(f.read()).hexdigest()
51
ff14fc49 52defs = gettestcases()
6b47c7f2 53
0eaf520d 54
1535ac2a 55class TestDownload(unittest.TestCase):
744435f2 56 maxDiff = None
fd5ff020 57 def setUp(self):
fd5ff020
FV
58 self.defs = defs
59
911ee27e 60### Dynamically generate tests
5d01a647
PH
61def generator(test_case):
62
1535ac2a 63 def test_template(self):
d1cade5a 64 ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
9ee2b5f6 65 other_ies = [get_info_extractor(ie_key) for ie_key in test_case.get('add_ie', [])]
e8ee972c
PH
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
bc2884af
JMF
70 def print_skipping(reason):
71 print('Skipping %s: %s' % (test_case['name'], reason))
9ee2b5f6 72 if not ie.working():
bc2884af 73 print_skipping('IE marked as not _WORKING')
fd5ff020 74 return
e8ee972c
PH
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')):
2437fbca 79 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
e8ee972c 80
fd5ff020 81 if 'skip' in test_case:
bc2884af 82 print_skipping(test_case['skip'])
fd5ff020 83 return
9ee2b5f6
JMF
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
0eaf520d 88
44a5f171 89 params = get_params(test_case.get('params', {}))
e8ee972c
PH
90 if is_playlist and 'playlist' not in test_case:
91 params.setdefault('extract_flat', True)
92 params.setdefault('skip_download', True)
0eaf520d 93
8222d8de 94 ydl = YoutubeDL(params)
023fa8c4 95 ydl.add_default_info_extractors()
bffbd5f0
PH
96 finished_hook_called = set()
97 def _hook(status):
98 if status['status'] == 'finished':
99 finished_hook_called.add(status['filename'])
933605d7 100 ydl.add_progress_hook(_hook)
5c892b0b 101
702665c0
JMF
102 def get_tc_filename(tc):
103 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
104
702665c0
JMF
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')
4eb92208 110 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
702665c0 111 try_rm_tcs_files()
5c892b0b 112 try:
dd508b7c
FV
113 try_num = 1
114 while True:
8cc83b8d 115 try:
e8ee972c
PH
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'])
8cc83b8d 120 except (DownloadError, ExtractorError) as err:
8cc83b8d 121 # Check if the exception is not a network related one
dcf3eec4 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):
8cc83b8d
FV
123 raise
124
dd508b7c
FV
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
8cc83b8d
FV
132 else:
133 break
5c892b0b 134
e8ee972c
PH
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
5c892b0b 146 for tc in test_cases:
702665c0 147 tc_filename = get_tc_filename(tc)
511eda8e 148 if not test_case.get('params', {}).get('skip_download', False):
702665c0
JMF
149 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
150 self.assertTrue(tc_filename in finished_hook_called)
4eb92208
PH
151 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
152 self.assertTrue(os.path.exists(info_json_fn))
5c892b0b 153 if 'md5' in tc:
702665c0 154 md5_for_file = _file_md5(tc_filename)
5c892b0b 155 self.assertEqual(md5_for_file, tc['md5'])
4eb92208 156 with io.open(info_json_fn, encoding='utf-8') as infof:
5c892b0b 157 info_dict = json.load(infof)
257cfebf
PH
158
159 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
5c892b0b 160 finally:
702665c0 161 try_rm_tcs_files()
fd5ff020 162
1535ac2a 163 return test_template
fd5ff020 164
5d01a647 165### And add them to TestDownload
f7ab6cbe 166for n, test_case in enumerate(defs):
5d01a647 167 test_method = generator(test_case)
2eb88d95
PH
168 tname = 'test_' + str(test_case['name'])
169 i = 1
170 while hasattr(TestDownload, tname):
41beccba 171 tname = 'test_' + str(test_case['name']) + '_' + str(i)
2eb88d95
PH
172 i += 1
173 test_method.__name__ = tname
fd5ff020 174 setattr(TestDownload, test_method.__name__, test_method)
5d01a647 175 del test_method
cdab8aa3
PH
176
177
178if __name__ == '__main__':
179 unittest.main()