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