565afa1b5f9fea031c74f86274695c90410ffcc1
[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     get_testcases,
12     global_setup,
13     try_rm,
14     md5,
15     report_warning
16 )
17 global_setup()
18
19
20 import hashlib
21 import io
22 import json
23 import socket
24
25 import youtube_dl.YoutubeDL
26 from youtube_dl.utils import (
27     compat_str,
28     compat_urllib_error,
29     DownloadError,
30     ExtractorError,
31     UnavailableVideoError,
32 )
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 = get_testcases()
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         def print_skipping(reason):
66             print('Skipping %s: %s' % (test_case['name'], reason))
67         if not ie._WORKING:
68             print_skipping('IE marked as not _WORKING')
69             return
70         if 'playlist' not in test_case:
71             info_dict = test_case.get('info_dict', {})
72             if not test_case.get('file') and not (info_dict.get('id') and info_dict.get('ext')):
73                 print_skipping('The output file cannot be know, the "file" '
74                     'key is missing or the info_dict is incomplete')
75                 return
76         if 'skip' in test_case:
77             print_skipping(test_case['skip'])
78             return
79
80         params = get_params(test_case.get('params', {}))
81
82         ydl = YoutubeDL(params)
83         ydl.add_default_info_extractors()
84         finished_hook_called = set()
85         def _hook(status):
86             if status['status'] == 'finished':
87                 finished_hook_called.add(status['filename'])
88         ydl.fd.add_progress_hook(_hook)
89
90         def get_tc_filename(tc):
91             return tc.get('file') or ydl.prepare_filename(tc.get('info_dict', {}))
92
93         test_cases = test_case.get('playlist', [test_case])
94         def try_rm_tcs_files():
95             for tc in test_cases:
96                 tc_filename = get_tc_filename(tc)
97                 try_rm(tc_filename)
98                 try_rm(tc_filename + '.part')
99                 try_rm(tc_filename + '.info.json')
100         try_rm_tcs_files()
101         try:
102             try_num = 1
103             while True:
104                 try:
105                     ydl.download([test_case['url']])
106                 except (DownloadError, ExtractorError) as err:
107                     # Check if the exception is not a network related one
108                     if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
109                         raise
110
111                     if try_num == RETRIES:
112                         report_warning(u'Failed due to network errors, skipping...')
113                         return
114
115                     print('Retrying: {0} failed tries\n\n##########\n\n'.format(try_num))
116
117                     try_num += 1
118                 else:
119                     break
120
121             for tc in test_cases:
122                 tc_filename = get_tc_filename(tc)
123                 if not test_case.get('params', {}).get('skip_download', False):
124                     self.assertTrue(os.path.exists(tc_filename), msg='Missing file ' + tc_filename)
125                     self.assertTrue(tc_filename in finished_hook_called)
126                 self.assertTrue(os.path.exists(tc_filename + '.info.json'))
127                 if 'md5' in tc:
128                     md5_for_file = _file_md5(tc_filename)
129                     self.assertEqual(md5_for_file, tc['md5'])
130                 with io.open(tc_filename + '.info.json', encoding='utf-8') as infof:
131                     info_dict = json.load(infof)
132                 for (info_field, expected) in tc.get('info_dict', {}).items():
133                     if isinstance(expected, compat_str) and expected.startswith('md5:'):
134                         got = 'md5:' + md5(info_dict.get(info_field))
135                     else:
136                         got = info_dict.get(info_field)
137                     self.assertEqual(expected, got,
138                         u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
139
140                 # If checkable fields are missing from the test case, print the info_dict
141                 test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
142                     for key, value in info_dict.items()
143                     if value and key in ('title', 'description', 'uploader', 'upload_date', 'uploader_id', 'location'))
144                 if not all(key in tc.get('info_dict', {}).keys() for key in test_info_dict.keys()):
145                     sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=2) + u'\n')
146
147                 # Check for the presence of mandatory fields
148                 for key in ('id', 'url', 'title', 'ext'):
149                     self.assertTrue(key in info_dict.keys() and info_dict[key])
150         finally:
151             try_rm_tcs_files()
152
153     return test_template
154
155 ### And add them to TestDownload
156 for n, test_case in enumerate(defs):
157     test_method = generator(test_case)
158     tname = 'test_' + str(test_case['name'])
159     i = 1
160     while hasattr(TestDownload, tname):
161         tname = 'test_'  + str(test_case['name']) + '_' + str(i)
162         i += 1
163     test_method.__name__ = tname
164     setattr(TestDownload, test_method.__name__, test_method)
165     del test_method
166
167
168 if __name__ == '__main__':
169     unittest.main()