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, '..')
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
26 background
._detach
= lambda: False
27 background
._exec
_gui
= raise_gui
28 sys
.modules
['dbus'] = my_dbus
29 sys
.modules
['dbus.glib'] = my_dbus
30 my_dbus
.types
= my_dbus
31 sys
.modules
['dbus.types'] = my_dbus
34 def output_suppressed():
35 old_stdout
= sys
.stdout
36 old_stderr
= sys
.stderr
38 sys
.stdout
= StringIO()
39 sys
.stderr
= StringIO()
42 sys
.stdout
= old_stdout
43 sys
.stderr
= old_stderr
46 def __init__(self
, reply
):
52 class DummyHandler(handler
.Handler
):
53 __slots__
= ['ex', 'tb']
56 handler
.Handler
.__init
__(self
)
59 def wait_for_blocker(self
, blocker
):
61 handler
.Handler
.wait_for_blocker(self
, blocker
)
63 raise self
.ex
, None, self
.tb
65 def report_error(self
, ex
, tb
= None):
66 assert self
.ex
is None, self
.ex
71 #traceback.print_exc()
73 class TestDownload(BaseTest
):
77 stream
= tempfile
.TemporaryFile()
78 stream
.write(data
.thomas_key
)
80 gpg
.import_key(stream
)
83 trust
.trust_db
.watchers
= []
86 BaseTest
.tearDown(self
)
87 if self
.child
is not None:
88 os
.kill(self
.child
, signal
.SIGTERM
)
89 os
.waitpid(self
.child
, 0)
92 def testRejectKey(self
):
93 with
output_suppressed():
94 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg')
95 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
96 handler
= DummyHandler())
97 assert policy
.need_download()
98 sys
.stdin
= Reply("N\n")
100 policy
.download_and_execute(['Hello'])
102 except model
.SafeException
, ex
:
103 if "Can't find all required implementations" not in str(ex
):
105 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
108 def testRejectKeyXML(self
):
109 with
output_suppressed():
110 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
111 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False,
112 handler
= DummyHandler())
113 assert policy
.need_download()
114 sys
.stdin
= Reply("N\n")
116 policy
.download_and_execute(['Hello'])
118 except model
.SafeException
, ex
:
119 if "Can't find all required implementations" not in str(ex
):
121 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
124 def testImport(self
):
125 from zeroinstall
.injector
import cli
127 rootLogger
= getLogger()
128 rootLogger
.disabled
= True
131 cli
.main(['--import', '-v', 'NO-SUCH-FILE'])
133 except model
.SafeException
, ex
:
134 assert 'NO-SUCH-FILE' in str(ex
)
136 rootLogger
.disabled
= False
137 rootLogger
.setLevel(WARN
)
139 hello
= iface_cache
.iface_cache
.get_interface('http://localhost:8000/Hello')
140 self
.assertEquals(0, len(hello
.implementations
))
142 with
output_suppressed():
143 self
.child
= server
.handle_requests('6FCF121BE2390E0B.gpg')
144 sys
.stdin
= Reply("Y\n")
146 assert not trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
147 cli
.main(['--import', 'Hello'])
148 assert trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
150 # Check we imported the interface after trusting the key
151 reader
.update_from_cache(hello
)
152 self
.assertEquals(1, len(hello
.implementations
))
154 # Shouldn't need to prompt the second time
156 cli
.main(['--import', 'Hello'])
158 def testSelections(self
):
159 from zeroinstall
.injector
.cli
import _download_missing_selections
160 root
= qdom
.parse(file("selections.xml"))
161 sels
= selections
.Selections(root
)
162 class Options
: dry_run
= False
164 with
output_suppressed():
165 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', 'HelloWorld.tgz')
166 sys
.stdin
= Reply("Y\n")
167 _download_missing_selections(Options(), sels
)
168 path
= iface_cache
.iface_cache
.stores
.lookup(sels
.selections
['http://example.com:8000/Hello.xml'].id)
169 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
171 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
173 def testSelectionsWithFeed(self
):
174 from zeroinstall
.injector
.cli
import _download_missing_selections
175 root
= qdom
.parse(file("selections.xml"))
176 sels
= selections
.Selections(root
)
177 class Options
: dry_run
= False
179 with
output_suppressed():
180 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', 'HelloWorld.tgz')
181 sys
.stdin
= Reply("Y\n")
183 from zeroinstall
.injector
import fetch
184 from zeroinstall
.injector
.handler
import Handler
186 fetcher
= fetch
.Fetcher(handler
)
187 handler
.wait_for_blocker(fetcher
.download_and_import_feed('http://example.com:8000/Hello.xml', iface_cache
.iface_cache
))
189 _download_missing_selections(Options(), sels
)
190 path
= iface_cache
.iface_cache
.stores
.lookup(sels
.selections
['http://example.com:8000/Hello.xml'].id)
191 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
193 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
195 def testAcceptKey(self
):
196 with
output_suppressed():
197 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg', 'HelloWorld.tgz')
198 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
199 handler
= DummyHandler())
200 assert policy
.need_download()
201 sys
.stdin
= Reply("Y\n")
203 policy
.download_and_execute(['Hello'], main
= 'Missing')
205 except model
.SafeException
, ex
:
206 if "HelloWorld/Missing" not in str(ex
):
209 def testRecipe(self
):
212 sys
.stdout
= StringIO()
213 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'dummy_1-1_all.deb'))
214 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False)
216 policy
.download_and_execute([])
218 except model
.SafeException
, ex
:
219 if "HelloWorld/Missing" not in str(ex
):
224 def testSymlink(self
):
227 sys
.stdout
= StringIO()
228 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'HelloSym.tgz'))
229 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('RecipeSymlink.xml'), download_only
= False,
230 handler
= DummyHandler())
232 policy
.download_and_execute([])
234 except model
.SafeException
, ex
:
235 if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex
):
237 self
.assertEquals(None, basedir
.load_first_cache('0install.net', 'implementations', 'main'))
241 def testAutopackage(self
):
244 sys
.stdout
= StringIO()
245 self
.child
= server
.handle_requests('HelloWorld.autopackage')
246 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Autopackage.xml'), download_only
= False)
248 policy
.download_and_execute([])
250 except model
.SafeException
, ex
:
251 if "HelloWorld/Missing" not in str(ex
):
256 def testRecipeFailure(self
):
259 sys
.stdout
= StringIO()
260 self
.child
= server
.handle_requests('*')
261 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False,
262 handler
= DummyHandler())
264 policy
.download_and_execute([])
266 except download
.DownloadError
, ex
:
267 if "Connection" not in str(ex
):
272 def testMirrors(self
):
275 sys
.stdout
= StringIO()
276 getLogger().setLevel(ERROR
)
277 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
278 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg')
279 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
280 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
282 refreshed
= policy
.solve_with_downloads()
283 policy
.handler
.wait_for_blocker(refreshed
)
288 def testReplay(self
):
291 sys
.stdout
= StringIO()
292 getLogger().setLevel(ERROR
)
293 iface
= iface_cache
.iface_cache
.get_interface('http://example.com:8000/Hello.xml')
294 mtime
= int(os
.stat('Hello-new.xml').st_mtime
)
295 iface_cache
.iface_cache
.update_interface_from_network(iface
, file('Hello-new.xml').read(), mtime
+ 10000)
297 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
298 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg', 'Hello.xml')
299 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
300 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
302 # Update from mirror (should ignore out-of-date timestamp)
303 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
304 policy
.handler
.wait_for_blocker(refreshed
)
306 # Update from upstream (should report an error)
307 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
309 policy
.handler
.wait_for_blocker(refreshed
)
310 raise Exception("Should have been rejected!")
311 except model
.SafeException
, ex
:
312 assert "New interface's modification time is before old version" in str(ex
)
314 # Must finish with the newest version
315 self
.assertEquals(1235911552, iface_cache
.iface_cache
._get
_signature
_date
(iface
.uri
))
319 def testBackground(self
, verbose
= False):
320 p
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml')
321 reader
.update(iface_cache
.iface_cache
.get_interface(p
.root
), 'Hello.xml')
323 p
.network_use
= model
.network_minimal
324 p
.solver
.solve(p
.root
, arch
.get_host_architecture())
328 def choose_download(registed_cb
, nid
, actions
):
330 assert actions
== ['download', 'Download'], actions
331 registed_cb(nid
, 'download')
334 traceback
.print_exc()
341 sys
.stdout
= StringIO()
342 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
343 my_dbus
.user_callback
= choose_download
347 # The background handler runs in the same process
348 # as the tests, so don't let it abort.
349 if os
.getpid() == pid
:
350 raise SystemExit(code
)
351 # But, child download processes are OK
356 background
.spawn_background_update(p
, verbose
)
358 except SystemExit, ex
:
359 self
.assertEquals(1, ex
.code
)
366 def testBackgroundVerbose(self
):
367 self
.testBackground(verbose
= True)
369 suite
= unittest
.makeSuite(TestDownload
)
370 if __name__
== '__main__':
371 sys
.argv
.append('-v')