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
21 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= 'http://localhost:3333/key-info'
29 background
._detach
= lambda: False
30 background
._exec
_gui
= raise_gui
33 def output_suppressed():
34 old_stdout
= sys
.stdout
35 old_stderr
= sys
.stderr
37 sys
.stdout
= StringIO()
38 sys
.stderr
= StringIO()
43 except BaseException
, ex
:
44 # Don't abort unit-tests if someone raises SystemExit
45 raise Exception(str(type(ex
)) + " " + str(ex
))
47 sys
.stdout
= old_stdout
48 sys
.stderr
= old_stderr
51 def __init__(self
, reply
):
57 class DummyHandler(handler
.Handler
):
58 __slots__
= ['ex', 'tb']
61 handler
.Handler
.__init
__(self
)
64 def wait_for_blocker(self
, blocker
):
66 handler
.Handler
.wait_for_blocker(self
, blocker
)
68 raise self
.ex
, None, self
.tb
70 def report_error(self
, ex
, tb
= None):
71 assert self
.ex
is None, self
.ex
76 #traceback.print_exc()
80 return 3 # NM_STATUS_CONNECTED
82 class TestDownload(BaseTest
):
86 stream
= tempfile
.TemporaryFile()
87 stream
.write(data
.thomas_key
)
89 gpg
.import_key(stream
)
92 trust
.trust_db
.watchers
= []
95 BaseTest
.tearDown(self
)
96 if self
.child
is not None:
97 os
.kill(self
.child
, signal
.SIGTERM
)
98 os
.waitpid(self
.child
, 0)
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")
109 policy
.download_and_execute(['Hello'])
111 except model
.SafeException
, ex
:
112 if "has no usable implementations" not in str(ex
):
114 if "Not signed with a trusted key" not in str(policy
.handler
.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")
125 policy
.download_and_execute(['Hello'])
127 except model
.SafeException
, ex
:
128 if "has no usable implementations" not in str(ex
):
130 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
133 def testImport(self
):
134 from zeroinstall
.injector
import cli
136 rootLogger
= getLogger()
137 rootLogger
.disabled
= True
140 cli
.main(['--import', '-v', 'NO-SUCH-FILE'])
142 except model
.SafeException
, ex
:
143 assert 'NO-SUCH-FILE' in str(ex
)
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
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
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")
211 policy
.download_and_execute(['Hello'], main
= 'Missing')
213 except model
.SafeException
, ex
:
214 if "HelloWorld/Missing" not in str(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')
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
)
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")
254 policy
.download_and_execute(['Hello'], main
= 'Missing')
256 except model
.SafeException
, ex
:
257 if "Downloaded archive has incorrect size" not in str(ex
):
260 def testRecipe(self
):
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)
267 policy
.download_and_execute([])
269 except model
.SafeException
, ex
:
270 if "HelloWorld/Missing" not in str(ex
):
275 def testSymlink(self
):
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())
283 policy
.download_and_execute([])
285 except model
.SafeException
, ex
:
286 if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex
):
288 self
.assertEquals(None, basedir
.load_first_cache('0install.net', 'implementations', 'main'))
292 def testAutopackage(self
):
295 sys
.stdout
= StringIO()
296 self
.child
= server
.handle_requests('HelloWorld.autopackage')
297 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Autopackage.xml'), download_only
= False)
299 policy
.download_and_execute([])
301 except model
.SafeException
, ex
:
302 if "HelloWorld/Missing" not in str(ex
):
307 def testRecipeFailure(self
):
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())
315 policy
.download_and_execute([])
317 except download
.DownloadError
, ex
:
318 if "Connection" not in str(ex
):
323 def testMirrors(self
):
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
)
339 def testReplay(self
):
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
)
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
))
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')
374 p
.network_use
= model
.network_minimal
375 p
.solver
.solve(p
.root
, arch
.get_host_architecture())
379 def choose_download(registed_cb
, nid
, actions
):
381 assert actions
== ['download', 'Download'], actions
382 registed_cb(nid
, 'download')
385 traceback
.print_exc()
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
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
405 key_info
= fetch
.DEFAULT_KEY_LOOKUP_SERVER
406 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= None
410 background
.spawn_background_update(p
, verbose
)
412 except SystemExit, ex
:
413 self
.assertEquals(1, ex
.code
)
416 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= key_info
421 def testBackgroundVerbose(self
):
422 self
.testBackground(verbose
= True)
424 if __name__
== '__main__':