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()
41 sys
.stdout
= old_stdout
42 sys
.stderr
= old_stderr
45 def __init__(self
, reply
):
51 class DummyHandler(handler
.Handler
):
52 __slots__
= ['ex', 'tb']
55 handler
.Handler
.__init
__(self
)
58 def wait_for_blocker(self
, blocker
):
60 handler
.Handler
.wait_for_blocker(self
, blocker
)
62 raise self
.ex
, None, self
.tb
64 def report_error(self
, ex
, tb
= None):
65 assert self
.ex
is None, self
.ex
70 #traceback.print_exc()
72 class TestDownload(BaseTest
):
76 stream
= tempfile
.TemporaryFile()
77 stream
.write(data
.thomas_key
)
79 gpg
.import_key(stream
)
82 trust
.trust_db
.watchers
= []
85 BaseTest
.tearDown(self
)
86 if self
.child
is not None:
87 os
.kill(self
.child
, signal
.SIGTERM
)
88 os
.waitpid(self
.child
, 0)
91 def testRejectKey(self
):
92 with
output_suppressed():
93 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
94 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
95 handler
= DummyHandler())
96 assert policy
.need_download()
97 sys
.stdin
= Reply("N\n")
99 policy
.download_and_execute(['Hello'])
101 except model
.SafeException
, ex
:
102 if "Can't find all required implementations" not in str(ex
):
104 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
107 def testRejectKeyXML(self
):
108 with
output_suppressed():
109 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
110 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False,
111 handler
= DummyHandler())
112 assert policy
.need_download()
113 sys
.stdin
= Reply("N\n")
115 policy
.download_and_execute(['Hello'])
117 except model
.SafeException
, ex
:
118 if "Can't find all required implementations" not in str(ex
):
120 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
123 def testImport(self
):
124 from zeroinstall
.injector
import cli
126 rootLogger
= getLogger()
127 rootLogger
.disabled
= True
130 cli
.main(['--import', '-v', 'NO-SUCH-FILE'])
132 except model
.SafeException
, ex
:
133 assert 'NO-SUCH-FILE' in str(ex
)
135 rootLogger
.disabled
= False
136 rootLogger
.setLevel(WARN
)
138 hello
= iface_cache
.iface_cache
.get_feed('http://localhost:8000/Hello')
139 self
.assertEquals(None, hello
)
141 with
output_suppressed():
142 self
.child
= server
.handle_requests('6FCF121BE2390E0B.gpg')
143 sys
.stdin
= Reply("Y\n")
145 assert not trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
146 cli
.main(['--import', 'Hello'])
147 assert trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
149 # Check we imported the interface after trusting the key
150 hello
= iface_cache
.iface_cache
.get_feed('http://localhost:8000/Hello', force
= True)
151 self
.assertEquals(1, len(hello
.implementations
))
153 # Shouldn't need to prompt the second time
155 cli
.main(['--import', 'Hello'])
157 def testSelections(self
):
158 from zeroinstall
.injector
.cli
import _download_missing_selections
159 root
= qdom
.parse(file("selections.xml"))
160 sels
= selections
.Selections(root
)
161 class Options
: dry_run
= False
163 with
output_suppressed():
164 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
165 sys
.stdin
= Reply("Y\n")
166 _download_missing_selections(Options(), sels
)
167 path
= iface_cache
.iface_cache
.stores
.lookup_any(sels
.selections
['http://example.com:8000/Hello.xml'].digests
)
168 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
170 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
172 def testSelectionsWithFeed(self
):
173 from zeroinstall
.injector
.cli
import _download_missing_selections
174 root
= qdom
.parse(file("selections.xml"))
175 sels
= selections
.Selections(root
)
176 class Options
: dry_run
= False
178 with
output_suppressed():
179 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
180 sys
.stdin
= Reply("Y\n")
182 from zeroinstall
.injector
.handler
import Handler
184 fetcher
= fetch
.Fetcher(handler
)
185 handler
.wait_for_blocker(fetcher
.download_and_import_feed('http://example.com:8000/Hello.xml', iface_cache
.iface_cache
))
187 _download_missing_selections(Options(), sels
)
188 path
= iface_cache
.iface_cache
.stores
.lookup_any(sels
.selections
['http://example.com:8000/Hello.xml'].digests
)
189 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
191 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
193 def testAcceptKey(self
):
194 with
output_suppressed():
195 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
196 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
197 handler
= DummyHandler())
198 assert policy
.need_download()
199 sys
.stdin
= Reply("Y\n")
201 policy
.download_and_execute(['Hello'], main
= 'Missing')
203 except model
.SafeException
, ex
:
204 if "HelloWorld/Missing" not in str(ex
):
207 def testDistro(self
):
208 with
output_suppressed():
209 native_url
= 'http://example.com:8000/Native.xml'
211 # Initially, we don't have the feed at all...
212 master_feed
= iface_cache
.iface_cache
.get_feed(native_url
)
213 assert master_feed
is None, master_feed
215 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
216 self
.child
= server
.handle_requests('Native.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
218 policy
= autopolicy
.AutoPolicy(native_url
, download_only
= False, handler
= h
)
219 assert policy
.need_download()
221 solve
= policy
.solve_with_downloads()
222 h
.wait_for_blocker(solve
)
225 master_feed
= iface_cache
.iface_cache
.get_feed(native_url
)
226 assert master_feed
is not None
227 assert master_feed
.implementations
== {}
229 distro_feed_url
= master_feed
.get_distro_feed()
230 assert distro_feed_url
is not None
231 distro_feed
= iface_cache
.iface_cache
.get_feed(distro_feed_url
)
232 assert distro_feed
is not None
233 assert len(distro_feed
.implementations
) == 2, distro_feed
.implementations
235 def testWrongSize(self
):
236 with
output_suppressed():
237 self
.child
= server
.handle_requests('Hello-wrong-size', '6FCF121BE2390E0B.gpg',
238 '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
239 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello-wrong-size', download_only
= False,
240 handler
= DummyHandler())
241 assert policy
.need_download()
242 sys
.stdin
= Reply("Y\n")
244 policy
.download_and_execute(['Hello'], main
= 'Missing')
246 except model
.SafeException
, ex
:
247 if "Downloaded archive has incorrect size" not in str(ex
):
250 def testRecipe(self
):
253 sys
.stdout
= StringIO()
254 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'dummy_1-1_all.deb'))
255 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False)
257 policy
.download_and_execute([])
259 except model
.SafeException
, ex
:
260 if "HelloWorld/Missing" not in str(ex
):
265 def testSymlink(self
):
268 sys
.stdout
= StringIO()
269 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'HelloSym.tgz'))
270 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('RecipeSymlink.xml'), download_only
= False,
271 handler
= DummyHandler())
273 policy
.download_and_execute([])
275 except model
.SafeException
, ex
:
276 if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex
):
278 self
.assertEquals(None, basedir
.load_first_cache('0install.net', 'implementations', 'main'))
282 def testAutopackage(self
):
285 sys
.stdout
= StringIO()
286 self
.child
= server
.handle_requests('HelloWorld.autopackage')
287 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Autopackage.xml'), download_only
= False)
289 policy
.download_and_execute([])
291 except model
.SafeException
, ex
:
292 if "HelloWorld/Missing" not in str(ex
):
297 def testRecipeFailure(self
):
300 sys
.stdout
= StringIO()
301 self
.child
= server
.handle_requests('*')
302 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False,
303 handler
= DummyHandler())
305 policy
.download_and_execute([])
307 except download
.DownloadError
, ex
:
308 if "Connection" not in str(ex
):
313 def testMirrors(self
):
316 sys
.stdout
= StringIO()
317 getLogger().setLevel(ERROR
)
318 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
319 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg')
320 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
321 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
323 refreshed
= policy
.solve_with_downloads()
324 policy
.handler
.wait_for_blocker(refreshed
)
329 def testReplay(self
):
332 sys
.stdout
= StringIO()
333 getLogger().setLevel(ERROR
)
334 iface
= iface_cache
.iface_cache
.get_interface('http://example.com:8000/Hello.xml')
335 mtime
= int(os
.stat('Hello-new.xml').st_mtime
)
336 iface_cache
.iface_cache
.update_feed_from_network(iface
.uri
, file('Hello-new.xml').read(), mtime
+ 10000)
338 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
339 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg', 'Hello.xml')
340 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
341 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
343 # Update from mirror (should ignore out-of-date timestamp)
344 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
345 policy
.handler
.wait_for_blocker(refreshed
)
347 # Update from upstream (should report an error)
348 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
350 policy
.handler
.wait_for_blocker(refreshed
)
351 raise Exception("Should have been rejected!")
352 except model
.SafeException
, ex
:
353 assert "New feed's modification time is before old version" in str(ex
)
355 # Must finish with the newest version
356 self
.assertEquals(1235911552, iface_cache
.iface_cache
._get
_signature
_date
(iface
.uri
))
360 def testBackground(self
, verbose
= False):
361 p
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml')
362 reader
.update(iface_cache
.iface_cache
.get_interface(p
.root
), 'Hello.xml')
364 p
.network_use
= model
.network_minimal
365 p
.solver
.solve(p
.root
, arch
.get_host_architecture())
369 def choose_download(registed_cb
, nid
, actions
):
371 assert actions
== ['download', 'Download'], actions
372 registed_cb(nid
, 'download')
375 traceback
.print_exc()
382 sys
.stdout
= StringIO()
383 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
384 my_dbus
.user_callback
= choose_download
388 # The background handler runs in the same process
389 # as the tests, so don't let it abort.
390 if os
.getpid() == pid
:
391 raise SystemExit(code
)
392 # But, child download processes are OK
394 key_info
= fetch
.DEFAULT_KEY_LOOKUP_SERVER
395 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= None
399 background
.spawn_background_update(p
, verbose
)
401 except SystemExit, ex
:
402 self
.assertEquals(1, ex
.code
)
405 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= key_info
410 def testBackgroundVerbose(self
):
411 self
.testBackground(verbose
= True)
413 if __name__
== '__main__':