Added support for <command> element
[zeroinstall.git] / tests / testdownload.py
blob598185a1018c3631cb168061646161548e39b483
1 #!/usr/bin/env python
2 from __future__ import with_statement
3 from basetest import BaseTest
4 import sys, tempfile, os
5 from StringIO import StringIO
6 import unittest, signal
7 from logging import getLogger, WARN, ERROR
8 from contextlib import contextmanager
10 sys.path.insert(0, '..')
12 os.environ["http_proxy"] = "localhost:8000"
14 from zeroinstall.injector import model, autopolicy, gpg, iface_cache, download, reader, trust, handler, background, arch, selections, qdom
15 from zeroinstall.zerostore import Store; Store._add_with_helper = lambda *unused: False
16 from zeroinstall.support import basedir, tasks
17 from zeroinstall.injector import fetch
18 import data
19 import my_dbus
21 fetch.DEFAULT_KEY_LOOKUP_SERVER = 'http://localhost:3333/key-info'
23 import server
25 ran_gui = False
26 def raise_gui(*args):
27 global ran_gui
28 ran_gui = True
29 background._detach = lambda: False
30 background._exec_gui = raise_gui
32 @contextmanager
33 def output_suppressed():
34 old_stdout = sys.stdout
35 old_stderr = sys.stderr
36 try:
37 sys.stdout = StringIO()
38 sys.stderr = StringIO()
39 try:
40 yield
41 except Exception:
42 raise
43 except BaseException, ex:
44 # Don't abort unit-tests if someone raises SystemExit
45 raise Exception(str(type(ex)) + " " + str(ex))
46 finally:
47 sys.stdout = old_stdout
48 sys.stderr = old_stderr
50 class Reply:
51 def __init__(self, reply):
52 self.reply = reply
54 def readline(self):
55 return self.reply
57 class DummyHandler(handler.Handler):
58 __slots__ = ['ex', 'tb']
60 def __init__(self):
61 handler.Handler.__init__(self)
62 self.ex = None
64 def wait_for_blocker(self, blocker):
65 self.ex = None
66 handler.Handler.wait_for_blocker(self, blocker)
67 if self.ex:
68 raise self.ex, None, self.tb
70 def report_error(self, ex, tb = None):
71 assert self.ex is None, self.ex
72 self.ex = ex
73 self.tb = tb
75 #import traceback
76 #traceback.print_exc()
78 class NetworkManager:
79 def state(self):
80 return 3 # NM_STATUS_CONNECTED
82 class TestDownload(BaseTest):
83 def setUp(self):
84 BaseTest.setUp(self)
86 stream = tempfile.TemporaryFile()
87 stream.write(data.thomas_key)
88 stream.seek(0)
89 gpg.import_key(stream)
90 self.child = None
92 trust.trust_db.watchers = []
94 def tearDown(self):
95 BaseTest.tearDown(self)
96 if self.child is not None:
97 os.kill(self.child, signal.SIGTERM)
98 os.waitpid(self.child, 0)
99 self.child = None
101 def testRejectKey(self):
102 with output_suppressed():
103 self.child = server.handle_requests('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
104 policy = autopolicy.AutoPolicy('http://localhost:8000/Hello', download_only = False,
105 handler = DummyHandler())
106 assert policy.need_download()
107 sys.stdin = Reply("N\n")
108 try:
109 policy.download_and_execute(['Hello'])
110 assert 0
111 except model.SafeException, ex:
112 if "has no usable implementations" not in str(ex):
113 raise ex
114 if "Not signed with a trusted key" not in str(policy.handler.ex):
115 raise ex
117 def testRejectKeyXML(self):
118 with output_suppressed():
119 self.child = server.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
120 policy = autopolicy.AutoPolicy('http://example.com:8000/Hello.xml', download_only = False,
121 handler = DummyHandler())
122 assert policy.need_download()
123 sys.stdin = Reply("N\n")
124 try:
125 policy.download_and_execute(['Hello'])
126 assert 0
127 except model.SafeException, ex:
128 if "has no usable implementations" not in str(ex):
129 raise ex
130 if "Not signed with a trusted key" not in str(policy.handler.ex):
131 raise
133 def testImport(self):
134 from zeroinstall.injector import cli
136 rootLogger = getLogger()
137 rootLogger.disabled = True
138 try:
139 try:
140 cli.main(['--import', '-v', 'NO-SUCH-FILE'])
141 assert 0
142 except model.SafeException, ex:
143 assert 'NO-SUCH-FILE' in str(ex)
144 finally:
145 rootLogger.disabled = False
146 rootLogger.setLevel(WARN)
148 hello = iface_cache.iface_cache.get_feed('http://localhost:8000/Hello')
149 self.assertEquals(None, hello)
151 with output_suppressed():
152 self.child = server.handle_requests('6FCF121BE2390E0B.gpg')
153 sys.stdin = Reply("Y\n")
155 assert not trust.trust_db.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
156 cli.main(['--import', 'Hello'])
157 assert trust.trust_db.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
159 # Check we imported the interface after trusting the key
160 hello = iface_cache.iface_cache.get_feed('http://localhost:8000/Hello', force = True)
161 self.assertEquals(1, len(hello.implementations))
163 # Shouldn't need to prompt the second time
164 sys.stdin = None
165 cli.main(['--import', 'Hello'])
167 def testSelections(self):
168 from zeroinstall.injector.cli import _download_missing_selections
169 root = qdom.parse(file("selections.xml"))
170 sels = selections.Selections(root)
171 class Options: dry_run = False
173 with output_suppressed():
174 self.child = server.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
175 sys.stdin = Reply("Y\n")
176 _download_missing_selections(Options(), sels)
177 path = iface_cache.iface_cache.stores.lookup_any(sels.selections['http://example.com:8000/Hello.xml'].digests)
178 assert os.path.exists(os.path.join(path, 'HelloWorld', 'main'))
180 assert sels.download_missing(iface_cache.iface_cache, None) is None
182 def testSelectionsWithFeed(self):
183 from zeroinstall.injector.cli import _download_missing_selections
184 root = qdom.parse(file("selections.xml"))
185 sels = selections.Selections(root)
186 class Options: dry_run = False
188 with output_suppressed():
189 self.child = server.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
190 sys.stdin = Reply("Y\n")
192 from zeroinstall.injector.handler import Handler
193 handler = Handler()
194 fetcher = fetch.Fetcher(handler)
195 handler.wait_for_blocker(fetcher.download_and_import_feed('http://example.com:8000/Hello.xml', iface_cache.iface_cache))
197 _download_missing_selections(Options(), sels)
198 path = iface_cache.iface_cache.stores.lookup_any(sels.selections['http://example.com:8000/Hello.xml'].digests)
199 assert os.path.exists(os.path.join(path, 'HelloWorld', 'main'))
201 assert sels.download_missing(iface_cache.iface_cache, None) is None
203 def testAcceptKey(self):
204 with output_suppressed():
205 self.child = server.handle_requests('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
206 policy = autopolicy.AutoPolicy('http://localhost:8000/Hello', download_only = False,
207 handler = DummyHandler())
208 assert policy.need_download()
209 sys.stdin = Reply("Y\n")
210 try:
211 policy.download_and_execute(['Hello'], main = 'Missing')
212 assert 0
213 except model.SafeException, ex:
214 if "HelloWorld/Missing" not in str(ex):
215 raise ex
217 def testDistro(self):
218 with output_suppressed():
219 native_url = 'http://example.com:8000/Native.xml'
221 # Initially, we don't have the feed at all...
222 master_feed = iface_cache.iface_cache.get_feed(native_url)
223 assert master_feed is None, master_feed
225 trust.trust_db.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
226 self.child = server.handle_requests('Native.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
227 h = DummyHandler()
228 policy = autopolicy.AutoPolicy(native_url, download_only = False, handler = h)
229 assert policy.need_download()
231 solve = policy.solve_with_downloads()
232 h.wait_for_blocker(solve)
233 tasks.check(solve)
235 master_feed = iface_cache.iface_cache.get_feed(native_url)
236 assert master_feed is not None
237 assert master_feed.implementations == {}
239 distro_feed_url = master_feed.get_distro_feed()
240 assert distro_feed_url is not None
241 distro_feed = iface_cache.iface_cache.get_feed(distro_feed_url)
242 assert distro_feed is not None
243 assert len(distro_feed.implementations) == 2, distro_feed.implementations
245 def testWrongSize(self):
246 with output_suppressed():
247 self.child = server.handle_requests('Hello-wrong-size', '6FCF121BE2390E0B.gpg',
248 '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
249 policy = autopolicy.AutoPolicy('http://localhost:8000/Hello-wrong-size', download_only = False,
250 handler = DummyHandler())
251 assert policy.need_download()
252 sys.stdin = Reply("Y\n")
253 try:
254 policy.download_and_execute(['Hello'], main = 'Missing')
255 assert 0
256 except model.SafeException, ex:
257 if "Downloaded archive has incorrect size" not in str(ex):
258 raise ex
260 def testRecipe(self):
261 old_out = sys.stdout
262 try:
263 sys.stdout = StringIO()
264 self.child = server.handle_requests(('HelloWorld.tar.bz2', 'dummy_1-1_all.deb'))
265 policy = autopolicy.AutoPolicy(os.path.abspath('Recipe.xml'), download_only = False)
266 try:
267 policy.download_and_execute([])
268 assert False
269 except model.SafeException, ex:
270 if "HelloWorld/Missing" not in str(ex):
271 raise ex
272 finally:
273 sys.stdout = old_out
275 def testSymlink(self):
276 old_out = sys.stdout
277 try:
278 sys.stdout = StringIO()
279 self.child = server.handle_requests(('HelloWorld.tar.bz2', 'HelloSym.tgz'))
280 policy = autopolicy.AutoPolicy(os.path.abspath('RecipeSymlink.xml'), download_only = False,
281 handler = DummyHandler())
282 try:
283 policy.download_and_execute([])
284 assert False
285 except model.SafeException, ex:
286 if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex):
287 raise
288 self.assertEquals(None, basedir.load_first_cache('0install.net', 'implementations', 'main'))
289 finally:
290 sys.stdout = old_out
292 def testAutopackage(self):
293 old_out = sys.stdout
294 try:
295 sys.stdout = StringIO()
296 self.child = server.handle_requests('HelloWorld.autopackage')
297 policy = autopolicy.AutoPolicy(os.path.abspath('Autopackage.xml'), download_only = False)
298 try:
299 policy.download_and_execute([])
300 assert False
301 except model.SafeException, ex:
302 if "HelloWorld/Missing" not in str(ex):
303 raise
304 finally:
305 sys.stdout = old_out
307 def testRecipeFailure(self):
308 old_out = sys.stdout
309 try:
310 sys.stdout = StringIO()
311 self.child = server.handle_requests('*')
312 policy = autopolicy.AutoPolicy(os.path.abspath('Recipe.xml'), download_only = False,
313 handler = DummyHandler())
314 try:
315 policy.download_and_execute([])
316 assert False
317 except download.DownloadError, ex:
318 if "Connection" not in str(ex):
319 raise
320 finally:
321 sys.stdout = old_out
323 def testMirrors(self):
324 old_out = sys.stdout
325 try:
326 sys.stdout = StringIO()
327 getLogger().setLevel(ERROR)
328 trust.trust_db.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
329 self.child = server.handle_requests(server.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg')
330 policy = autopolicy.AutoPolicy('http://example.com:8000/Hello.xml', download_only = False)
331 policy.fetcher.feed_mirror = 'http://example.com:8000/0mirror'
333 refreshed = policy.solve_with_downloads()
334 policy.handler.wait_for_blocker(refreshed)
335 assert policy.ready
336 finally:
337 sys.stdout = old_out
339 def testReplay(self):
340 old_out = sys.stdout
341 try:
342 sys.stdout = StringIO()
343 getLogger().setLevel(ERROR)
344 iface = iface_cache.iface_cache.get_interface('http://example.com:8000/Hello.xml')
345 mtime = int(os.stat('Hello-new.xml').st_mtime)
346 iface_cache.iface_cache.update_feed_from_network(iface.uri, file('Hello-new.xml').read(), mtime + 10000)
348 trust.trust_db.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
349 self.child = server.handle_requests(server.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg', 'Hello.xml')
350 policy = autopolicy.AutoPolicy('http://example.com:8000/Hello.xml', download_only = False)
351 policy.fetcher.feed_mirror = 'http://example.com:8000/0mirror'
353 # Update from mirror (should ignore out-of-date timestamp)
354 refreshed = policy.fetcher.download_and_import_feed(iface.uri, iface_cache.iface_cache)
355 policy.handler.wait_for_blocker(refreshed)
357 # Update from upstream (should report an error)
358 refreshed = policy.fetcher.download_and_import_feed(iface.uri, iface_cache.iface_cache)
359 try:
360 policy.handler.wait_for_blocker(refreshed)
361 raise Exception("Should have been rejected!")
362 except model.SafeException, ex:
363 assert "New feed's modification time is before old version" in str(ex)
365 # Must finish with the newest version
366 self.assertEquals(1235911552, iface_cache.iface_cache._get_signature_date(iface.uri))
367 finally:
368 sys.stdout = old_out
370 def testBackground(self, verbose = False):
371 p = autopolicy.AutoPolicy('http://example.com:8000/Hello.xml')
372 reader.update(iface_cache.iface_cache.get_interface(p.root), 'Hello.xml')
373 p.freshness = 0
374 p.network_use = model.network_minimal
375 p.solver.solve(p.root, arch.get_host_architecture())
376 assert p.ready
378 @tasks.async
379 def choose_download(registed_cb, nid, actions):
380 try:
381 assert actions == ['download', 'Download'], actions
382 registed_cb(nid, 'download')
383 except:
384 import traceback
385 traceback.print_exc()
386 yield None
388 global ran_gui
389 ran_gui = False
390 old_out = sys.stdout
391 try:
392 sys.stdout = StringIO()
393 self.child = server.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
394 my_dbus.system_services = {"org.freedesktop.NetworkManager": {"/org/freedesktop/NetworkManager": NetworkManager()}}
395 my_dbus.user_callback = choose_download
396 pid = os.getpid()
397 old_exit = os._exit
398 def my_exit(code):
399 # The background handler runs in the same process
400 # as the tests, so don't let it abort.
401 if os.getpid() == pid:
402 raise SystemExit(code)
403 # But, child download processes are OK
404 old_exit(code)
405 key_info = fetch.DEFAULT_KEY_LOOKUP_SERVER
406 fetch.DEFAULT_KEY_LOOKUP_SERVER = None
407 try:
408 try:
409 os._exit = my_exit
410 background.spawn_background_update(p, verbose)
411 assert False
412 except SystemExit, ex:
413 self.assertEquals(1, ex.code)
414 finally:
415 os._exit = old_exit
416 fetch.DEFAULT_KEY_LOOKUP_SERVER = key_info
417 finally:
418 sys.stdout = old_out
419 assert ran_gui
421 def testBackgroundVerbose(self):
422 self.testBackground(verbose = True)
424 if __name__ == '__main__':
425 unittest.main()