Debian Codegraph @

third_party/python/dlmanager/tests/test_manager.py

raw
1 try:
2 import unittest2 as unittest # python < 2.7 compat
3 except ImportError:
4 import unittest
5 import tempfile
6 import shutil
7 import os
8 import time
9 import six
10 from mock import Mock
11
12 from dlmanager import manager as download_manager
13
14
15 def mock_session():
16 response = Mock()
17 session = Mock(get=Mock(return_value=response))
18 return session, response
19
20
21 def mock_response(response, data, wait=0):
22 data = six.b(data)
23
24 def iter_content(chunk_size=4):
25 rest = data
26 while rest:
27 time.sleep(wait)
28 chunk = rest[:chunk_size]
29 rest = rest[chunk_size:]
30 yield chunk
31
32 response.headers = {'Content-length': str(len(data))}
33 response.iter_content = iter_content
34
35
36 class TestDownload(unittest.TestCase):
37 def setUp(self):
38 self.tempdir = tempfile.mkdtemp()
39 self.addCleanup(shutil.rmtree, self.tempdir)
40 self.finished = Mock()
41 self.session, self.session_response = mock_session()
42 self.tempfile = os.path.join(self.tempdir, 'dest')
43 self.dl = download_manager.Download('http://url', self.tempfile,
44 finished_callback=self.finished,
45 chunk_size=4,
46 session=self.session)
47
48 def test_creation(self):
49 self.assertFalse(self.dl.is_canceled())
50 self.assertFalse(self.dl.is_running())
51 self.assertIsNone(self.dl.error())
52 self.assertEquals(self.dl.get_url(), 'http://url')
53 self.assertEquals(self.dl.get_dest(), self.tempfile)
54
55 def create_response(self, data, wait=0):
56 mock_response(self.session_response, data, wait)
57
58 def test_download(self):
59 self.create_response('1234' * 4, 0.01)
60
61 # no file present yet
62 self.assertFalse(os.path.exists(self.tempfile))
63
64 self.dl.start()
65 self.assertTrue(self.dl.is_running())
66 self.dl.wait()
67
68 self.assertFalse(self.dl.is_running())
69 self.finished.assert_called_with(self.dl)
70 # file has been downloaded
71 with open(self.tempfile) as f:
72 self.assertEquals(f.read(), '1234' * 4)
73
74 def test_download_cancel(self):
75 self.create_response('1234' * 1000, wait=0.01)
76
77 start = time.time()
78 self.dl.start()
79 time.sleep(0.1)
80 self.dl.cancel()
81
82 with self.assertRaises(download_manager.DownloadInterrupt):
83 self.dl.wait()
84
85 self.assertTrue(self.dl.is_canceled())
86
87 # response generation should have taken 1000 * 0.01 = 10 seconds.
88 # since we canceled, this must be lower.
89 self.assertTrue((time.time() - start) < 1.0)
90
91 # file was deleted
92 self.assertFalse(os.path.exists(self.tempfile))
93 # finished callback was called
94 self.finished.assert_called_with(self.dl)
95
96 def test_download_with_progress(self):
97 data = []
98
99 def update_progress(_dl, current, total):
100 data.append((_dl, current, total))
101
102 self.create_response('1234' * 4)
103
104 self.dl.set_progress(update_progress)
105 self.dl.start()
106 self.dl.wait()
107
108 self.assertEquals(data, [
109 (self.dl, 0, 16),
110 (self.dl, 4, 16),
111 (self.dl, 8, 16),
112 (self.dl, 12, 16),
113 (self.dl, 16, 16),
114 ])
115 # file has been downloaded
116 with open(self.tempfile) as f:
117 self.assertEquals(f.read(), '1234' * 4)
118 # finished callback was called
119 self.finished.assert_called_with(self.dl)
120
121 def test_download_error_in_thread(self):
122 self.session_response.headers = {'Content-length': '24'}
123 self.session_response.iter_content.side_effect = IOError
124
125 self.dl.start()
126 with self.assertRaises(IOError):
127 self.dl.wait()
128
129 self.assertEquals(self.dl.error()[0], IOError)
130 # finished callback was called
131 self.finished.assert_called_with(self.dl)
132
133 def test_wait_does_not_block_on_exception(self):
134 # this test the case when a user may hit CTRL-C for example
135 # during a dl.wait() call.
136 self.create_response('1234' * 1000, wait=0.01)
137
138 original_join = self.dl.thread.join
139 it = iter('123')
140
141 def join(timeout=None):
142 next(it) # will throw StopIteration after a few calls
143 original_join(timeout)
144
145 self.dl.thread.join = join
146
147 start = time.time()
148 self.dl.start()
149
150 with self.assertRaises(StopIteration):
151 self.dl.wait()
152
153 self.assertTrue(self.dl.is_canceled())
154 # wait for the thread to finish
155 original_join()
156
157 # response generation should have taken 1000 * 0.01 = 10 seconds.
158 # since we got an error, this must be lower.
159 self.assertTrue((time.time() - start) < 1.0)
160
161 # file was deleted
162 self.assertFalse(os.path.exists(self.tempfile))
163 # finished callback was called
164 self.finished.assert_called_with(self.dl)
165
166
167 class TestDownloadManager(unittest.TestCase):
168 def setUp(self):
169 self.tempdir = tempfile.mkdtemp()
170 self.addCleanup(shutil.rmtree, self.tempdir)
171
172 self.dl_manager = download_manager.DownloadManager(self.tempdir)
173
174 def do_download(self, url, fname, data, wait=0):
175 session, response = mock_session()
176 mock_response(response, data, wait)
177 # patch the session, so the download will use that
178 self.dl_manager.session = session
179 return self.dl_manager.download(url, fname)
180
181 def test_download(self):
182 dl1 = self.do_download('http://foo', 'foo', 'hello' * 4, wait=0.02)
183 self.assertIsInstance(dl1, download_manager.Download)
184 self.assertTrue(dl1.is_running())
185
186 # with the same fname, no new download is started. The same instance
187 # is returned since the download is running.
188 dl2 = self.do_download('http://bar', 'foo', 'hello2' * 4, wait=0.02)
189 self.assertEquals(dl1, dl2)
190
191 # starting a download with another fname will trigger a new download
192 dl3 = self.do_download('http://bar', 'foo2', 'hello you' * 4)
193 self.assertIsInstance(dl3, download_manager.Download)
194 self.assertNotEquals(dl3, dl1)
195
196 # let's wait for the downloads to finish
197 dl3.wait()
198 dl1.wait()
199
200 # now if we try to download a fname that exists, None is returned
201 dl4 = self.do_download('http://bar', 'foo', 'hello2' * 4, wait=0.02)
202 self.assertIsNone(dl4)
203
204 # downloaded files are what is expected
205 def content(fname):
206 with open(os.path.join(self.tempdir, fname)) as f:
207 return f.read()
208 self.assertEquals(content('foo'), 'hello' * 4)
209 self.assertEquals(content('foo2'), 'hello you' * 4)
210
211 # download instances are removed from the manager (internal test)
212 self.assertEquals(self.dl_manager._downloads, {})
213
214 def test_cancel(self):
215 dl1 = self.do_download('http://foo', 'foo', 'foo' * 50000, wait=0.02)
216 dl2 = self.do_download('http://foo', 'bar', 'bar' * 50000, wait=0.02)
217 dl3 = self.do_download('http://foo', 'foobar', 'foobar' * 4)
218
219 # let's cancel only one
220 def cancel_if(dl):
221 if os.path.basename(dl.get_dest()) == 'foo':
222 return True
223 self.dl_manager.cancel(cancel_if=cancel_if)
224
225 self.assertTrue(dl1.is_canceled())
226 self.assertFalse(dl2.is_canceled())
227 self.assertFalse(dl3.is_canceled())
228
229 # wait for dl3
230 dl3.wait()
231
232 # cancel everything
233 self.dl_manager.cancel()
234
235 self.assertTrue(dl1.is_canceled())
236 self.assertTrue(dl2.is_canceled())
237 # dl3 is not canceled since it finished before
238 self.assertFalse(dl3.is_canceled())
239
240 # wait for the completion of dl1 and dl2 threads
241 dl1.wait(raise_if_error=False)
242 dl2.wait(raise_if_error=False)
243
244 # at the end, only dl3 has been downloaded
245 self.assertEquals(os.listdir(self.tempdir), ["foobar"])
246
247 with open(os.path.join(self.tempdir, 'foobar')) as f:
248 self.assertEquals(f.read(), 'foobar' * 4)
249
250 # download instances are removed from the manager (internal test)
251 self.assertEquals(self.dl_manager._downloads, {})