Add function add_default_info_extractors to YoutubeDL
[youtube-dl] / test / test_download.py
1 #!/usr/bin/env python
2
3 import errno
4 import hashlib
5 import io
6 import os
7 import json
8 import unittest
9 import sys
10 import socket
11 import binascii
12
13 # Allow direct execution
14 sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
15
16 import youtube_dl.YoutubeDL
17 from youtube_dl.utils import *
18
19 PARAMETERS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "parameters.json")
20
21 RETRIES = 3
22
23 # General configuration (from __init__, not very elegant...)
24 jar = compat_cookiejar.CookieJar()
25 cookie_processor = compat_urllib_request.HTTPCookieProcessor(jar)
26 proxy_handler = compat_urllib_request.ProxyHandler()
27 opener = compat_urllib_request.build_opener(proxy_handler, cookie_processor, YoutubeDLHandler())
28 compat_urllib_request.install_opener(opener)
29 socket.setdefaulttimeout(10)
30
31 def _try_rm(filename):
32     """ Remove a file if it exists """
33     try:
34         os.remove(filename)
35     except OSError as ose:
36         if ose.errno != errno.ENOENT:
37             raise
38
39 md5 = lambda s: hashlib.md5(s.encode('utf-8')).hexdigest()
40
41 class YoutubeDL(youtube_dl.YoutubeDL):
42     def __init__(self, *args, **kwargs):
43         self.to_stderr = self.to_screen
44         self.processed_info_dicts = []
45         super(YoutubeDL, self).__init__(*args, **kwargs)
46     def report_warning(self, message):
47         # Don't accept warnings during tests
48         raise ExtractorError(message)
49     def process_info(self, info_dict):
50         self.processed_info_dicts.append(info_dict)
51         return super(YoutubeDL, self).process_info(info_dict)
52
53 def _file_md5(fn):
54     with open(fn, 'rb') as f:
55         return hashlib.md5(f.read()).hexdigest()
56
57 from helper import get_testcases
58 defs = get_testcases()
59
60 with io.open(PARAMETERS_FILE, encoding='utf-8') as pf:
61     parameters = json.load(pf)
62
63
64 class TestDownload(unittest.TestCase):
65     maxDiff = None
66     def setUp(self):
67         self.parameters = parameters
68         self.defs = defs
69
70 ### Dynamically generate tests
71 def generator(test_case):
72
73     def test_template(self):
74         ie = youtube_dl.extractor.get_info_extractor(test_case['name'])
75         if not ie._WORKING:
76             print('Skipping: IE marked as not _WORKING')
77             return
78         if 'playlist' not in test_case and not test_case['file']:
79             print('Skipping: No output file specified')
80             return
81         if 'skip' in test_case:
82             print('Skipping: {0}'.format(test_case['skip']))
83             return
84
85         params = self.parameters.copy()
86         params.update(test_case.get('params', {}))
87
88         ydl = YoutubeDL(params)
89         ydl.add_default_info_extractors()
90         finished_hook_called = set()
91         def _hook(status):
92             if status['status'] == 'finished':
93                 finished_hook_called.add(status['filename'])
94         ydl.fd.add_progress_hook(_hook)
95
96         test_cases = test_case.get('playlist', [test_case])
97         for tc in test_cases:
98             _try_rm(tc['file'])
99             _try_rm(tc['file'] + '.part')
100             _try_rm(tc['file'] + '.info.json')
101         try:
102             for retry in range(1, RETRIES + 1):
103                 try:
104                     ydl.download([test_case['url']])
105                 except (DownloadError, ExtractorError) as err:
106                     if retry == RETRIES: raise
107
108                     # Check if the exception is not a network related one
109                     if not err.exc_info[0] in (compat_urllib_error.URLError, socket.timeout, UnavailableVideoError):
110                         raise
111
112                     print('Retrying: {0} failed tries\n\n##########\n\n'.format(retry))
113                 else:
114                     break
115
116             for tc in test_cases:
117                 if not test_case.get('params', {}).get('skip_download', False):
118                     self.assertTrue(os.path.exists(tc['file']), msg='Missing file ' + tc['file'])
119                     self.assertTrue(tc['file'] in finished_hook_called)
120                 self.assertTrue(os.path.exists(tc['file'] + '.info.json'))
121                 if 'md5' in tc:
122                     md5_for_file = _file_md5(tc['file'])
123                     self.assertEqual(md5_for_file, tc['md5'])
124                 with io.open(tc['file'] + '.info.json', encoding='utf-8') as infof:
125                     info_dict = json.load(infof)
126                 for (info_field, expected) in tc.get('info_dict', {}).items():
127                     if isinstance(expected, compat_str) and expected.startswith('md5:'):
128                         self.assertEqual(expected, 'md5:' + md5(info_dict.get(info_field)))
129                     else:
130                         got = info_dict.get(info_field)
131                         self.assertEqual(
132                             expected, got,
133                             u'invalid value for field %s, expected %r, got %r' % (info_field, expected, got))
134
135                 # If checkable fields are missing from the test case, print the info_dict
136                 test_info_dict = dict((key, value if not isinstance(value, compat_str) or len(value) < 250 else 'md5:' + md5(value))
137                     for key, value in info_dict.items()
138                     if value and key in ('title', 'description', 'uploader', 'upload_date', 'uploader_id', 'location'))
139                 if not all(key in tc.get('info_dict', {}).keys() for key in test_info_dict.keys()):
140                     sys.stderr.write(u'\n"info_dict": ' + json.dumps(test_info_dict, ensure_ascii=False, indent=2) + u'\n')
141
142                 # Check for the presence of mandatory fields
143                 for key in ('id', 'url', 'title', 'ext'):
144                     self.assertTrue(key in info_dict.keys() and info_dict[key])
145         finally:
146             for tc in test_cases:
147                 _try_rm(tc['file'])
148                 _try_rm(tc['file'] + '.part')
149                 _try_rm(tc['file'] + '.info.json')
150
151     return test_template
152
153 ### And add them to TestDownload
154 for n, test_case in enumerate(defs):
155     test_method = generator(test_case)
156     tname = 'test_' + str(test_case['name'])
157     i = 1
158     while hasattr(TestDownload, tname):
159         tname = 'test_'  + str(test_case['name']) + '_' + str(i)
160         i += 1
161     test_method.__name__ = tname
162     setattr(TestDownload, test_method.__name__, test_method)
163     del test_method
164
165
166 if __name__ == '__main__':
167     unittest.main()