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