1 #!/usr/bin/env python2.5
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, '..')
11 os
.environ
['PYTHONPATH'] = os
.path
.abspath('..')
13 os
.environ
["http_proxy"] = "localhost:8000"
15 from zeroinstall
.injector
import model
, autopolicy
, gpg
, iface_cache
, download
, reader
, trust
, handler
, background
, arch
, selections
, qdom
16 from zeroinstall
.zerostore
import Store
; Store
._add
_with
_helper
= lambda *unused
: False
17 from zeroinstall
.support
import basedir
, tasks
27 background
._detach
= lambda: False
28 background
._exec
_gui
= raise_gui
29 sys
.modules
['dbus'] = my_dbus
30 sys
.modules
['dbus.glib'] = my_dbus
31 my_dbus
.types
= my_dbus
32 sys
.modules
['dbus.types'] = my_dbus
35 def output_suppressed():
36 old_stdout
= sys
.stdout
37 old_stderr
= sys
.stderr
39 sys
.stdout
= StringIO()
40 sys
.stderr
= StringIO()
43 sys
.stdout
= old_stdout
44 sys
.stderr
= old_stderr
47 def __init__(self
, reply
):
53 class DummyHandler(handler
.Handler
):
54 __slots__
= ['ex', 'tb']
57 handler
.Handler
.__init
__(self
)
60 def wait_for_blocker(self
, blocker
):
62 handler
.Handler
.wait_for_blocker(self
, blocker
)
64 raise self
.ex
, None, self
.tb
66 def report_error(self
, ex
, tb
= None):
67 assert self
.ex
is None, self
.ex
72 #traceback.print_exc()
74 class TestDownload(BaseTest
):
78 stream
= tempfile
.TemporaryFile()
79 stream
.write(data
.thomas_key
)
81 gpg
.import_key(stream
)
84 trust
.trust_db
.watchers
= []
87 BaseTest
.tearDown(self
)
88 if self
.child
is not None:
89 os
.kill(self
.child
, signal
.SIGTERM
)
90 os
.waitpid(self
.child
, 0)
93 def testRejectKey(self
):
94 with
output_suppressed():
95 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg')
96 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
97 handler
= DummyHandler())
98 assert policy
.need_download()
99 sys
.stdin
= Reply("N\n")
101 policy
.download_and_execute(['Hello'])
103 except model
.SafeException
, ex
:
104 if "Can't find all required implementations" not in str(ex
):
106 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
109 def testRejectKeyXML(self
):
110 with
output_suppressed():
111 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
112 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False,
113 handler
= DummyHandler())
114 assert policy
.need_download()
115 sys
.stdin
= Reply("N\n")
117 policy
.download_and_execute(['Hello'])
119 except model
.SafeException
, ex
:
120 if "Can't find all required implementations" not in str(ex
):
122 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
125 def testImport(self
):
126 from zeroinstall
.injector
import cli
128 rootLogger
= getLogger()
129 rootLogger
.disabled
= True
132 cli
.main(['--import', '-v', 'NO-SUCH-FILE'])
134 except model
.SafeException
, ex
:
135 assert 'NO-SUCH-FILE' in str(ex
)
137 rootLogger
.disabled
= False
138 rootLogger
.setLevel(WARN
)
140 hello
= iface_cache
.iface_cache
.get_interface('http://localhost:8000/Hello')
141 self
.assertEquals(0, len(hello
.implementations
))
143 with
output_suppressed():
144 self
.child
= server
.handle_requests('6FCF121BE2390E0B.gpg')
145 sys
.stdin
= Reply("Y\n")
147 assert not trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
148 cli
.main(['--import', 'Hello'])
149 assert trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
151 # Check we imported the interface after trusting the key
152 reader
.update_from_cache(hello
)
153 self
.assertEquals(1, len(hello
.implementations
))
155 # Shouldn't need to prompt the second time
157 cli
.main(['--import', 'Hello'])
159 def testSelections(self
):
160 from zeroinstall
.injector
.cli
import _download_missing_selections
161 root
= qdom
.parse(file("selections.xml"))
162 sels
= selections
.Selections(root
)
163 class Options
: dry_run
= False
165 with
output_suppressed():
166 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', 'HelloWorld.tgz')
167 sys
.stdin
= Reply("Y\n")
168 _download_missing_selections(Options(), sels
)
169 path
= iface_cache
.iface_cache
.stores
.lookup(sels
.selections
['http://example.com:8000/Hello.xml'].id)
170 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
172 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
174 def testSelectionsWithFeed(self
):
175 from zeroinstall
.injector
.cli
import _download_missing_selections
176 root
= qdom
.parse(file("selections.xml"))
177 sels
= selections
.Selections(root
)
178 class Options
: dry_run
= False
180 with
output_suppressed():
181 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', 'HelloWorld.tgz')
182 sys
.stdin
= Reply("Y\n")
184 from zeroinstall
.injector
import fetch
185 from zeroinstall
.injector
.handler
import Handler
187 fetcher
= fetch
.Fetcher(handler
)
188 handler
.wait_for_blocker(fetcher
.download_and_import_feed('http://example.com:8000/Hello.xml', iface_cache
.iface_cache
))
190 _download_missing_selections(Options(), sels
)
191 path
= iface_cache
.iface_cache
.stores
.lookup(sels
.selections
['http://example.com:8000/Hello.xml'].id)
192 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
194 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
196 def testAcceptKey(self
):
197 with
output_suppressed():
198 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg', 'HelloWorld.tgz')
199 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
200 handler
= DummyHandler())
201 assert policy
.need_download()
202 sys
.stdin
= Reply("Y\n")
204 policy
.download_and_execute(['Hello'], main
= 'Missing')
206 except model
.SafeException
, ex
:
207 if "HelloWorld/Missing" not in str(ex
):
210 def testRecipe(self
):
213 sys
.stdout
= StringIO()
214 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'dummy_1-1_all.deb'))
215 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False)
217 policy
.download_and_execute([])
219 except model
.SafeException
, ex
:
220 if "HelloWorld/Missing" not in str(ex
):
225 def testSymlink(self
):
228 sys
.stdout
= StringIO()
229 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'HelloSym.tgz'))
230 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('RecipeSymlink.xml'), download_only
= False,
231 handler
= DummyHandler())
233 policy
.download_and_execute([])
235 except model
.SafeException
, ex
:
236 if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex
):
238 self
.assertEquals(None, basedir
.load_first_cache('0install.net', 'implementations', 'main'))
242 def testAutopackage(self
):
245 sys
.stdout
= StringIO()
246 self
.child
= server
.handle_requests('HelloWorld.autopackage')
247 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Autopackage.xml'), download_only
= False)
249 policy
.download_and_execute([])
251 except model
.SafeException
, ex
:
252 if "HelloWorld/Missing" not in str(ex
):
257 def testRecipeFailure(self
):
260 sys
.stdout
= StringIO()
261 self
.child
= server
.handle_requests('*')
262 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False,
263 handler
= DummyHandler())
265 policy
.download_and_execute([])
267 except download
.DownloadError
, ex
:
268 if "Connection" not in str(ex
):
273 def testMirrors(self
):
276 sys
.stdout
= StringIO()
277 getLogger().setLevel(ERROR
)
278 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
279 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg')
280 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
281 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
283 refreshed
= policy
.solve_with_downloads()
284 policy
.handler
.wait_for_blocker(refreshed
)
289 def testReplay(self
):
292 sys
.stdout
= StringIO()
293 getLogger().setLevel(ERROR
)
294 iface
= iface_cache
.iface_cache
.get_interface('http://example.com:8000/Hello.xml')
295 mtime
= int(os
.stat('Hello-new.xml').st_mtime
)
296 iface_cache
.iface_cache
.update_interface_from_network(iface
, file('Hello-new.xml').read(), mtime
+ 10000)
298 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
299 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg', 'Hello.xml')
300 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
301 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
303 # Update from mirror (should ignore out-of-date timestamp)
304 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
305 policy
.handler
.wait_for_blocker(refreshed
)
307 # Update from upstream (should report an error)
308 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
310 policy
.handler
.wait_for_blocker(refreshed
)
311 raise Exception("Should have been rejected!")
312 except model
.SafeException
, ex
:
313 assert "New interface's modification time is before old version" in str(ex
)
315 # Must finish with the newest version
316 self
.assertEquals(1235911552, iface_cache
.iface_cache
._get
_signature
_date
(iface
.uri
))
320 def testBackground(self
, verbose
= False):
321 p
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml')
322 reader
.update(iface_cache
.iface_cache
.get_interface(p
.root
), 'Hello.xml')
324 p
.network_use
= model
.network_minimal
325 p
.solver
.solve(p
.root
, arch
.get_host_architecture())
329 def choose_download(registed_cb
, nid
, actions
):
331 assert actions
== ['download', 'Download'], actions
332 registed_cb(nid
, 'download')
335 traceback
.print_exc()
342 sys
.stdout
= StringIO()
343 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
344 my_dbus
.user_callback
= choose_download
348 # The background handler runs in the same process
349 # as the tests, so don't let it abort.
350 if os
.getpid() == pid
:
351 raise SystemExit(code
)
352 # But, child download processes are OK
357 background
.spawn_background_update(p
, verbose
)
359 except SystemExit, ex
:
360 self
.assertEquals(1, ex
.code
)
367 def testBackgroundVerbose(self
):
368 self
.testBackground(verbose
= True)
370 suite
= unittest
.makeSuite(TestDownload
)
371 if __name__
== '__main__':
372 sys
.argv
.append('-v')