]> jfr.im git - yt-dlp.git/blame - test/test_download.py
Merge remote-tracking branch 'akirk/ellentv'
[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', [])]
bc2884af
JMF
66 def print_skipping(reason):
67 print('Skipping %s: %s' % (test_case['name'], reason))
9ee2b5f6 68 if not ie.working():
bc2884af 69 print_skipping('IE marked as not _WORKING')
fd5ff020 70 return
702665c0
JMF
71 if 'playlist' not in test_case:
72 info_dict = test_case.get('info_dict', {})
73 if not test_case.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
2437fbca 74 raise Exception('Test definition incorrect. The output file cannot be known. Are both \'id\' and \'ext\' keys present?')
fd5ff020 75 if 'skip' in test_case:
bc2884af 76 print_skipping(test_case['skip'])
fd5ff020 77 return
9ee2b5f6
JMF
78 for other_ie in other_ies:
79 if not other_ie.working():
80 print_skipping(u'test depends on %sIE, marked as not WORKING' % other_ie.ie_key())
81 return
0eaf520d 82
44a5f171 83 params = get_params(test_case.get('params', {}))
0eaf520d 84
8222d8de 85 ydl = YoutubeDL(params)
023fa8c4 86 ydl.add_default_info_extractors()
bffbd5f0
PH
87 finished_hook_called = set()
88 def _hook(status):
89 if status['status'] == 'finished':
90 finished_hook_called.add(status['filename'])
933605d7 91 ydl.add_progress_hook(_hook)
5c892b0b 92
702665c0
JMF
93 def get_tc_filename(tc):
94 return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
95
5c892b0b 96 test_cases = test_case.get('playlist', [test_case])
702665c0
JMF
97 def try_rm_tcs_files():
98 for tc in test_cases:
99 tc_filename = get_tc_filename(tc)
100 try_rm(tc_filename)
101 try_rm(tc_filename + '.part')
4eb92208 102 try_rm(os.path.splitext(tc_filename)[0] + '.info.json')
702665c0 103 try_rm_tcs_files()
5c892b0b 104 try:
dd508b7c
FV
105 try_num = 1
106 while True:
8cc83b8d 107 try:
8222d8de 108 ydl.download([test_case['url']])
8cc83b8d 109 except (DownloadError, ExtractorError) as err:
8cc83b8d 110 # Check if the exception is not a network related one
dcf3eec4 111 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
112 raise
113
dd508b7c
FV
114 if try_num == RETRIES:
115 report_warning(u'Failed due to network errors, skipping...')
116 return
117
118 print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
119
120 try_num += 1
8cc83b8d
FV
121 else:
122 break
5c892b0b
PH
123
124 for tc in test_cases:
702665c0 125 tc_filename = get_tc_filename(tc)
511eda8e 126 if not test_case.get('params', {}).get('skip_download', False):
702665c0
JMF
127 self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
128 self.assertTrue(tc_filename in finished_hook_called)
4eb92208
PH
129 info_json_fn = os.path.splitext(tc_filename)[0] + '.info.json'
130 self.assertTrue(os.path.exists(info_json_fn))
5c892b0b 131 if 'md5' in tc:
702665c0 132 md5_for_file = _file_md5(tc_filename)
5c892b0b 133 self.assertEqual(md5_for_file, tc['md5'])
4eb92208 134 with io.open(info_json_fn, encoding='utf-8') as infof:
5c892b0b 135 info_dict = json.load(infof)
257cfebf
PH
136
137 expect_info_dict(self, tc.get('info_dict', {}), info_dict)
5c892b0b 138 finally:
702665c0 139 try_rm_tcs_files()
fd5ff020 140
1535ac2a 141 return test_template
fd5ff020 142
5d01a647 143### And add them to TestDownload
f7ab6cbe 144for n, test_case in enumerate(defs):
5d01a647 145 test_method = generator(test_case)
2eb88d95
PH
146 tname = 'test_' + str(test_case['name'])
147 i = 1
148 while hasattr(TestDownload, tname):
41beccba 149 tname = 'test_' + str(test_case['name']) + '_' + str(i)
2eb88d95
PH
150 i += 1
151 test_method.__name__ = tname
fd5ff020 152 setattr(TestDownload, test_method.__name__, test_method)
5d01a647 153 del test_method
cdab8aa3
PH
154
155
156if __name__ == '__main__':
157 unittest.main()