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()
74 return 3 # NM_STATUS_CONNECTED
76 class TestDownload(BaseTest
):
80 stream
= tempfile
.TemporaryFile()
81 stream
.write(data
.thomas_key
)
83 gpg
.import_key(stream
)
86 trust
.trust_db
.watchers
= []
89 BaseTest
.tearDown(self
)
90 if self
.child
is not None:
91 os
.kill(self
.child
, signal
.SIGTERM
)
92 os
.waitpid(self
.child
, 0)
95 def testRejectKey(self
):
96 with
output_suppressed():
97 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
98 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
99 handler
= DummyHandler())
100 assert policy
.need_download()
101 sys
.stdin
= Reply("N\n")
103 policy
.download_and_execute(['Hello'])
105 except model
.SafeException
, ex
:
106 if "Can't find all required implementations" not in str(ex
):
108 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
111 def testRejectKeyXML(self
):
112 with
output_suppressed():
113 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
114 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False,
115 handler
= DummyHandler())
116 assert policy
.need_download()
117 sys
.stdin
= Reply("N\n")
119 policy
.download_and_execute(['Hello'])
121 except model
.SafeException
, ex
:
122 if "Can't find all required implementations" not in str(ex
):
124 if "Not signed with a trusted key" not in str(policy
.handler
.ex
):
127 def testImport(self
):
128 from zeroinstall
.injector
import cli
130 rootLogger
= getLogger()
131 rootLogger
.disabled
= True
134 cli
.main(['--import', '-v', 'NO-SUCH-FILE'])
136 except model
.SafeException
, ex
:
137 assert 'NO-SUCH-FILE' in str(ex
)
139 rootLogger
.disabled
= False
140 rootLogger
.setLevel(WARN
)
142 hello
= iface_cache
.iface_cache
.get_feed('http://localhost:8000/Hello')
143 self
.assertEquals(None, hello
)
145 with
output_suppressed():
146 self
.child
= server
.handle_requests('6FCF121BE2390E0B.gpg')
147 sys
.stdin
= Reply("Y\n")
149 assert not trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
150 cli
.main(['--import', 'Hello'])
151 assert trust
.trust_db
.is_trusted('DE937DD411906ACF7C263B396FCF121BE2390E0B')
153 # Check we imported the interface after trusting the key
154 hello
= iface_cache
.iface_cache
.get_feed('http://localhost:8000/Hello', force
= True)
155 self
.assertEquals(1, len(hello
.implementations
))
157 # Shouldn't need to prompt the second time
159 cli
.main(['--import', 'Hello'])
161 def testSelections(self
):
162 from zeroinstall
.injector
.cli
import _download_missing_selections
163 root
= qdom
.parse(file("selections.xml"))
164 sels
= selections
.Selections(root
)
165 class Options
: dry_run
= False
167 with
output_suppressed():
168 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
169 sys
.stdin
= Reply("Y\n")
170 _download_missing_selections(Options(), sels
)
171 path
= iface_cache
.iface_cache
.stores
.lookup_any(sels
.selections
['http://example.com:8000/Hello.xml'].digests
)
172 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
174 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
176 def testSelectionsWithFeed(self
):
177 from zeroinstall
.injector
.cli
import _download_missing_selections
178 root
= qdom
.parse(file("selections.xml"))
179 sels
= selections
.Selections(root
)
180 class Options
: dry_run
= False
182 with
output_suppressed():
183 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
184 sys
.stdin
= Reply("Y\n")
186 from zeroinstall
.injector
.handler
import Handler
188 fetcher
= fetch
.Fetcher(handler
)
189 handler
.wait_for_blocker(fetcher
.download_and_import_feed('http://example.com:8000/Hello.xml', iface_cache
.iface_cache
))
191 _download_missing_selections(Options(), sels
)
192 path
= iface_cache
.iface_cache
.stores
.lookup_any(sels
.selections
['http://example.com:8000/Hello.xml'].digests
)
193 assert os
.path
.exists(os
.path
.join(path
, 'HelloWorld', 'main'))
195 assert sels
.download_missing(iface_cache
.iface_cache
, None) is None
197 def testAcceptKey(self
):
198 with
output_suppressed():
199 self
.child
= server
.handle_requests('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
200 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello', download_only
= False,
201 handler
= DummyHandler())
202 assert policy
.need_download()
203 sys
.stdin
= Reply("Y\n")
205 policy
.download_and_execute(['Hello'], main
= 'Missing')
207 except model
.SafeException
, ex
:
208 if "HelloWorld/Missing" not in str(ex
):
211 def testDistro(self
):
212 with
output_suppressed():
213 native_url
= 'http://example.com:8000/Native.xml'
215 # Initially, we don't have the feed at all...
216 master_feed
= iface_cache
.iface_cache
.get_feed(native_url
)
217 assert master_feed
is None, master_feed
219 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
220 self
.child
= server
.handle_requests('Native.xml', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B')
222 policy
= autopolicy
.AutoPolicy(native_url
, download_only
= False, handler
= h
)
223 assert policy
.need_download()
225 solve
= policy
.solve_with_downloads()
226 h
.wait_for_blocker(solve
)
229 master_feed
= iface_cache
.iface_cache
.get_feed(native_url
)
230 assert master_feed
is not None
231 assert master_feed
.implementations
== {}
233 distro_feed_url
= master_feed
.get_distro_feed()
234 assert distro_feed_url
is not None
235 distro_feed
= iface_cache
.iface_cache
.get_feed(distro_feed_url
)
236 assert distro_feed
is not None
237 assert len(distro_feed
.implementations
) == 2, distro_feed
.implementations
239 def testWrongSize(self
):
240 with
output_suppressed():
241 self
.child
= server
.handle_requests('Hello-wrong-size', '6FCF121BE2390E0B.gpg',
242 '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
243 policy
= autopolicy
.AutoPolicy('http://localhost:8000/Hello-wrong-size', download_only
= False,
244 handler
= DummyHandler())
245 assert policy
.need_download()
246 sys
.stdin
= Reply("Y\n")
248 policy
.download_and_execute(['Hello'], main
= 'Missing')
250 except model
.SafeException
, ex
:
251 if "Downloaded archive has incorrect size" not in str(ex
):
254 def testRecipe(self
):
257 sys
.stdout
= StringIO()
258 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'dummy_1-1_all.deb'))
259 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False)
261 policy
.download_and_execute([])
263 except model
.SafeException
, ex
:
264 if "HelloWorld/Missing" not in str(ex
):
269 def testSymlink(self
):
272 sys
.stdout
= StringIO()
273 self
.child
= server
.handle_requests(('HelloWorld.tar.bz2', 'HelloSym.tgz'))
274 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('RecipeSymlink.xml'), download_only
= False,
275 handler
= DummyHandler())
277 policy
.download_and_execute([])
279 except model
.SafeException
, ex
:
280 if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex
):
282 self
.assertEquals(None, basedir
.load_first_cache('0install.net', 'implementations', 'main'))
286 def testAutopackage(self
):
289 sys
.stdout
= StringIO()
290 self
.child
= server
.handle_requests('HelloWorld.autopackage')
291 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Autopackage.xml'), download_only
= False)
293 policy
.download_and_execute([])
295 except model
.SafeException
, ex
:
296 if "HelloWorld/Missing" not in str(ex
):
301 def testRecipeFailure(self
):
304 sys
.stdout
= StringIO()
305 self
.child
= server
.handle_requests('*')
306 policy
= autopolicy
.AutoPolicy(os
.path
.abspath('Recipe.xml'), download_only
= False,
307 handler
= DummyHandler())
309 policy
.download_and_execute([])
311 except download
.DownloadError
, ex
:
312 if "Connection" not in str(ex
):
317 def testMirrors(self
):
320 sys
.stdout
= StringIO()
321 getLogger().setLevel(ERROR
)
322 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
323 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg')
324 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
325 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
327 refreshed
= policy
.solve_with_downloads()
328 policy
.handler
.wait_for_blocker(refreshed
)
333 def testReplay(self
):
336 sys
.stdout
= StringIO()
337 getLogger().setLevel(ERROR
)
338 iface
= iface_cache
.iface_cache
.get_interface('http://example.com:8000/Hello.xml')
339 mtime
= int(os
.stat('Hello-new.xml').st_mtime
)
340 iface_cache
.iface_cache
.update_feed_from_network(iface
.uri
, file('Hello-new.xml').read(), mtime
+ 10000)
342 trust
.trust_db
.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
343 self
.child
= server
.handle_requests(server
.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg', 'Hello.xml')
344 policy
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml', download_only
= False)
345 policy
.fetcher
.feed_mirror
= 'http://example.com:8000/0mirror'
347 # Update from mirror (should ignore out-of-date timestamp)
348 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
349 policy
.handler
.wait_for_blocker(refreshed
)
351 # Update from upstream (should report an error)
352 refreshed
= policy
.fetcher
.download_and_import_feed(iface
.uri
, iface_cache
.iface_cache
)
354 policy
.handler
.wait_for_blocker(refreshed
)
355 raise Exception("Should have been rejected!")
356 except model
.SafeException
, ex
:
357 assert "New feed's modification time is before old version" in str(ex
)
359 # Must finish with the newest version
360 self
.assertEquals(1235911552, iface_cache
.iface_cache
._get
_signature
_date
(iface
.uri
))
364 def testBackground(self
, verbose
= False):
365 p
= autopolicy
.AutoPolicy('http://example.com:8000/Hello.xml')
366 reader
.update(iface_cache
.iface_cache
.get_interface(p
.root
), 'Hello.xml')
368 p
.network_use
= model
.network_minimal
369 p
.solver
.solve(p
.root
, arch
.get_host_architecture())
373 def choose_download(registed_cb
, nid
, actions
):
375 assert actions
== ['download', 'Download'], actions
376 registed_cb(nid
, 'download')
379 traceback
.print_exc()
386 sys
.stdout
= StringIO()
387 self
.child
= server
.handle_requests('Hello.xml', '6FCF121BE2390E0B.gpg')
388 my_dbus
.system_services
= {"org.freedesktop.NetworkManager": {"/org/freedesktop/NetworkManager": NetworkManager()}}
389 my_dbus
.user_callback
= choose_download
393 # The background handler runs in the same process
394 # as the tests, so don't let it abort.
395 if os
.getpid() == pid
:
396 raise SystemExit(code
)
397 # But, child download processes are OK
399 key_info
= fetch
.DEFAULT_KEY_LOOKUP_SERVER
400 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= None
404 background
.spawn_background_update(p
, verbose
)
406 except SystemExit, ex
:
407 self
.assertEquals(1, ex
.code
)
410 fetch
.DEFAULT_KEY_LOOKUP_SERVER
= key_info
415 def testBackgroundVerbose(self
):
416 self
.testBackground(verbose
= True)
418 if __name__
== '__main__':