Ejemplo n.º 1
0
 def run_0launch(self, args):
     old_stdout = sys.stdout
     old_stderr = sys.stderr
     try:
         sys.stdout = StringIO()
         sys.stderr = StringIO()
         ex = None
         try:
             cli.main(args)
             print("Finished")
         except NameError:
             raise
         except SystemExit:
             pass
         except TypeError:
             raise
         except AttributeError:
             raise
         except AssertionError:
             raise
         except Exception as ex2:
             ex = ex2  # Python 3
         out = sys.stdout.getvalue()
         err = sys.stderr.getvalue()
         if ex is not None:
             err += str(ex.__class__)
     finally:
         sys.stdout = old_stdout
         sys.stderr = old_stderr
     return (out, err)
Ejemplo n.º 2
0
    def testAbsMain(self):
        p = Driver(requirements=Requirements(command_feed), config=self.config)
        self.config.handler.wait_for_blocker(p.solve_with_downloads())

        old_stdout = sys.stdout
        try:
            sys.stdout = StringIO()
            run.execute_selections(p.solver.selections, [],
                                   main='/runnable/runner',
                                   dry_run=True,
                                   stores=self.config.stores)
        finally:
            sys.stdout = old_stdout

        try:
            old_stdout = sys.stdout
            try:
                sys.stdout = StringIO()
                run.execute_selections(p.solver.selections, [],
                                       main='/runnable/not-there',
                                       dry_run=True,
                                       stores=self.config.stores)
            finally:
                sys.stdout = old_stdout
        except SafeException as ex:
            assert 'not-there' in unicode(ex)
Ejemplo n.º 3
0
 def run_0install(self, args):
     old_stdout = sys.stdout
     old_stderr = sys.stderr
     try:
         sys.stdout = StringIO()
         sys.stderr = StringIO()
         ex = None
         try:
             cmd.main(args, config=self.config)
         except NameError:
             raise
         except SystemExit:
             pass
         except TypeError:
             raise
         except AttributeError:
             raise
         except AssertionError:
             raise
         except ValueError:
             raise
         except Exception as ex2:
             ex = ex2  # Python 3
             raise
         out = sys.stdout.getvalue()
         err = sys.stderr.getvalue()
         if ex is not None:
             err += str(ex.__class__)
     finally:
         sys.stdout = old_stdout
         sys.stderr = old_stderr
     return (out, err)
Ejemplo n.º 4
0
    def testOptimise(self):
        sample = os.path.join(self.tmp, 'sample')
        os.mkdir(sample)
        self.populate_sample(sample)
        self.store.add_dir_to_cache(
            'sha1new=7e3eb25a072988f164bae24d33af69c1814eb99a',
            sample,
            try_helper=False)
        subfile = os.path.join(sample, 'My Dir', '!a file!.exe')
        mtime = os.stat(subfile).st_mtime
        os.chmod(subfile, 0o755)
        stream = open(subfile, 'w')
        stream.write('Extra!\n')
        stream.close()
        os.utime(subfile, (mtime, mtime))
        self.store.add_dir_to_cache(
            'sha1new=40861a33dba4e7c26d37505bd9693511808c0c35',
            sample,
            try_helper=False)

        impl_a = self.store.lookup(
            'sha1new=7e3eb25a072988f164bae24d33af69c1814eb99a')
        impl_b = self.store.lookup(
            'sha1new=40861a33dba4e7c26d37505bd9693511808c0c35')

        def same_inode(name):
            info_a = os.lstat(os.path.join(impl_a, name))
            info_b = os.lstat(os.path.join(impl_b, name))
            return info_a.st_ino == info_b.st_ino

        assert not same_inode('My Dir/!a file!')
        assert not same_inode('My Dir/!a file!.exe')

        old_stdout = sys.stdout
        sys.stdout = StringIO()
        try:
            cli.do_optimise([self.store.dir])
            got = sys.stdout.getvalue()
        finally:
            sys.stdout = old_stdout
        assert 'Space freed up : 15 bytes' in got

        old_stdout = sys.stdout
        sys.stdout = StringIO()
        try:
            cli.do_optimise([self.store.dir])
            got = sys.stdout.getvalue()
        finally:
            sys.stdout = old_stdout
        assert 'No duplicates found; no changes made.' in got

        assert same_inode('My Dir/!a file!')
        assert not same_inode('My Dir/!a file!.exe')
Ejemplo n.º 5
0
def output_suppressed():
    old_stdout = sys.stdout
    old_stderr = sys.stderr
    try:
        sys.stdout = StringIO()
        sys.stderr = StringIO()
        try:
            yield
        except Exception:
            raise
        except BaseException as ex:
            # Don't abort unit-tests if someone raises SystemExit
            raise Exception(str(type(ex)) + " " + str(ex))
    finally:
        sys.stdout = old_stdout
        sys.stderr = old_stderr
Ejemplo n.º 6
0
	def testReplay(self):
		with resourcewarnings_suppressed():
			old_out = sys.stdout
			try:
				sys.stdout = StringIO()
				getLogger().setLevel(ERROR)
				iface = self.config.iface_cache.get_interface('http://example.com:8000/Hello.xml')
				mtime = int(os.stat('Hello-new.xml').st_mtime)
				with open('Hello-new.xml', 'rb') as stream:
					self.config.iface_cache.update_feed_from_network(iface.uri, stream.read(), mtime + 10000)

				trust.trust_db.trust_key('DE937DD411906ACF7C263B396FCF121BE2390E0B', 'example.com:8000')
				run_server(server.Give404('/Hello.xml'), 'latest.xml', '/0mirror/keys/6FCF121BE2390E0B.gpg', 'Hello.xml')
				self.config.mirror = 'http://example.com:8000/0mirror'

				# Update from mirror (should ignore out-of-date timestamp)
				refreshed = self.config.fetcher.download_and_import_feed(iface.uri, self.config.iface_cache)
				tasks.wait_for_blocker(refreshed)

				# Update from upstream (should report an error)
				refreshed = self.config.fetcher.download_and_import_feed(iface.uri, self.config.iface_cache)
				try:
					tasks.wait_for_blocker(refreshed)
					raise Exception("Should have been rejected!")
				except model.SafeException as ex:
					assert "New feed's modification time is before old version" in str(ex)

				# Must finish with the newest version
				self.assertEqual(1342285569, self.config.iface_cache._get_signature_date(iface.uri))
			finally:
				sys.stdout = old_out
Ejemplo n.º 7
0
 def get_value(name):
     old_stdout = sys.stdout
     sys.stdout = StringIO()
     try:
         cmd.config.handle(file_config, None, [name])
         cmd_output = sys.stdout.getvalue()
     finally:
         sys.stdout = old_stdout
     return cmd_output
Ejemplo n.º 8
0
    def testList(self):
        cli.init_stores()

        old_stdout = sys.stdout
        sys.stdout = StringIO()
        cli.do_list([])
        result = sys.stdout.getvalue()
        assert 'User store' in result

        sys.stdout = old_stdout
Ejemplo n.º 9
0
 def testArgs(self):
     p = Driver(requirements=Requirements(runnable), config=self.config)
     self.config.handler.wait_for_blocker(p.solve_with_downloads())
     old_stdout = sys.stdout
     try:
         sys.stdout = StringIO()
         run.execute_selections(p.solver.selections, [],
                                dry_run=True,
                                stores=self.config.stores)
         out = sys.stdout.getvalue()
     finally:
         sys.stdout = old_stdout
     assert 'runner-arg' in out, out
Ejemplo n.º 10
0
	def testAutopackage(self):
		old_out = sys.stdout
		try:
			sys.stdout = StringIO()
			run_server('HelloWorld.autopackage')
			driver = Driver(requirements = Requirements(os.path.abspath('Autopackage.xml')), config = self.config)
			try:
				download_and_execute(driver, [])
				assert False
			except model.SafeException as ex:
				if "HelloWorld/Missing" not in str(ex):
					raise
		finally:
			sys.stdout = old_out
Ejemplo n.º 11
0
	def testRecipe(self):
		old_out = sys.stdout
		try:
			sys.stdout = StringIO()
			run_server(('HelloWorld.tar.bz2', 'redirect/dummy_1-1_all.deb', 'dummy_1-1_all.deb'))
			driver = Driver(requirements = Requirements(os.path.abspath('Recipe.xml')), config = self.config)
			try:
				download_and_execute(driver, [])
				assert False
			except model.SafeException as ex:
				if "HelloWorld/Missing" not in str(ex):
					raise ex
		finally:
			sys.stdout = old_out
Ejemplo n.º 12
0
 def testArgList(self):
     d = Driver(requirements=Requirements(arglist), config=self.config)
     self.config.handler.wait_for_blocker(d.solve_with_downloads())
     old_stdout = sys.stdout
     try:
         sys.stdout = StringIO()
         run.execute_selections(d.solver.selections, [],
                                dry_run=True,
                                stores=self.config.stores)
         out = sys.stdout.getvalue()
     finally:
         sys.stdout = old_stdout
     assert 'arg-for-runner -X ra1 -X ra2' in out, out
     assert 'command-arg ca1 ca2' in out, out
Ejemplo n.º 13
0
	def testDryRun(self):
		with output_suppressed():
			run_server('Hello', '6FCF121BE2390E0B.gpg', '/key-info/key/DE937DD411906ACF7C263B396FCF121BE2390E0B', 'HelloWorld.tgz')
			self.config.handler.dry_run = True
			driver = Driver(requirements = Requirements('http://localhost:8000/Hello'), config = self.config)
			assert driver.need_download()
			sys.stdin = Reply("Y\n")
			sys.stdout = StringIO()
			download_and_execute(driver, ['Hello'], main = 'Missing', dry_run = True)

			out = sys.stdout.getvalue()
			assert '[dry-run] would trust key DE937DD411906ACF7C263B396FCF121BE2390E0B for localhost:8000' in out, out
			assert '[dry-run] would cache feed http://localhost:8000/Hello as ' in out, out
			assert '[dry-run] would store implementation as ' in out, out
			assert '[dry-run] would execute:' in out, out
Ejemplo n.º 14
0
	def testSymlink(self):
		old_out = sys.stdout
		try:
			sys.stdout = StringIO()
			run_server(('HelloWorld.tar.bz2', 'HelloSym.tgz'))
			driver = Driver(requirements = Requirements(os.path.abspath('RecipeSymlink.xml')), config = self.config)
			try:
				download_and_execute(driver, [])
				assert False
			except model.SafeException as ex:
				if 'Attempt to unpack dir over symlink "HelloWorld"' not in str(ex):
					raise
			self.assertEqual(None, basedir.load_first_cache('0install.net', 'implementations', 'main'))
		finally:
			sys.stdout = old_out
Ejemplo n.º 15
0
    def testCommandBindings(self):
        if 'SELF_COMMAND' in os.environ:
            del os.environ['SELF_COMMAND']

        p = Driver(requirements=Requirements(command_feed), config=self.config)
        tasks.wait_for_blocker(p.solve_with_downloads())
        old_stdout = sys.stdout
        try:
            sys.stdout = StringIO()
            run.execute_selections(p.solver.selections, [],
                                   main='runnable/go.sh',
                                   dry_run=True,
                                   stores=self.config.stores)
        finally:
            sys.stdout = old_stdout
        assert 'local' in os.environ['LOCAL'], os.environ['LOCAL']
        assert 'SELF_COMMAND' in os.environ
Ejemplo n.º 16
0
	def testWrite(self):
		buf = StringIO()
		alias.write_script(buf, 'http://example.com/foo.xml', None)
		self.assertEqual(expected_script, buf.getvalue())

		buf = StringIO()
		alias.write_script(buf, 'http://example.com/foo.xml', 'a\'\'\\test')
		self.assertEqual(expected_script_main, buf.getvalue())

		buf = StringIO()
		alias.write_script(buf, 'http://example.com/foo.xml', command = 'a\'\'\\test')
		self.assertEqual(expected_script_command, buf.getvalue())
Ejemplo n.º 17
0
    def testBackground(self, verbose=False):
        r = Requirements('http://example.com:8000/Hello.xml')
        d = Driver(requirements=r, config=self.config)
        self.import_feed(r.interface_uri, 'Hello.xml')
        self.config.freshness = 0
        self.config.network_use = model.network_minimal
        d.solver.solve(r.interface_uri, arch.get_host_architecture())
        assert d.solver.ready, d.solver.get_failure_reason()

        @tasks. async
        def choose_download(registed_cb, nid, actions):
            try:
                assert actions == ['download', 'Download'], actions
                registed_cb(nid, 'download')
            except:
                import traceback
                traceback.print_exc()
            yield None

        global ran_gui
        ran_gui = False
        os.environ['DISPLAY'] = 'dummy'
        old_out = sys.stdout
        try:
            sys.stdout = StringIO()
            run_server('Hello.xml', '6FCF121BE2390E0B.gpg')
            my_dbus.system_services = {
                "org.freedesktop.NetworkManager": {
                    "/org/freedesktop/NetworkManager": NetworkManager()
                }
            }
            my_dbus.user_callback = choose_download

            with trapped_exit(1):
                from zeroinstall.injector import config
                key_info = config.DEFAULT_KEY_LOOKUP_SERVER
                config.DEFAULT_KEY_LOOKUP_SERVER = None
                try:
                    background.spawn_background_update(d, verbose)
                finally:
                    config.DEFAULT_KEY_LOOKUP_SERVER = key_info
        finally:
            sys.stdout = old_out
        assert ran_gui
Ejemplo n.º 18
0
	def testDownload(self):
		tmp = tempfile.NamedTemporaryFile(mode = 'wt')
		tmp.write(
"""<?xml version="1.0" ?>
<interface
 main='ThisBetterNotExist'
 xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
  <name>Foo</name>
  <summary>Foo</summary>
  <description>Foo</description>
  <implementation version='1.0' id='/bin'/>
</interface>""")
		tmp.flush()
		driver = Driver(requirements = Requirements(tmp.name), config = self.config)
		old, sys.stdout = sys.stdout, StringIO()
		try:
			download_and_execute(driver, ['Hello'])
			out = sys.stdout.getvalue()
		finally:
			sys.stdout = old
		assert "[dry-run] would execute: /bin/ThisBetterNotExist Hello\n" == out, out
		tmp.close()
Ejemplo n.º 19
0
    def testExecutables(self):
        # Check top-level scripts are readable (detects white-space errors)
        for script in ['0launch', '0alias', '0store', '0desktop', '0install']:
            path = os.path.join('..', script)

            old_stdout = sys.stdout
            old_stderr = sys.stderr
            old_argv = sys.argv
            try:
                sys.argv = [script, '--help']
                sys.stderr = sys.stdout = StringIO()

                imp.load_source(script, path)
            except SystemExit as ex:
                out = sys.stdout.getvalue()
                assert 'Usage: ' in out, (script, out)
            else:
                assert False
            finally:
                sys.stdout = old_stdout
                sys.stderr = old_stderr
                sys.argv = old_argv
Ejemplo n.º 20
0
	def testBinding(self):
		local_impl = os.path.dirname(os.path.abspath(__file__))
		tmp = tempfile.NamedTemporaryFile(mode = 'wt')
		tmp.write(
"""<?xml version="1.0" ?>
<interface
 main='testdriver.py'
 xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
  <name>Bar</name>
  <summary>Bar</summary>
  <description>Bar</description>
  <group>
    <requires interface='%s'>
      <environment name='FOO_PATH' insert='.'/>
      <environment name='BAR_PATH' insert='.' default='/a:/b'/>
      <environment name='NO_PATH' value='val'/>
      <environment name='XDG_DATA_DIRS' insert='.'/>
    </requires>
    <environment name='SELF_GROUP' insert='group' mode='replace'/>
    <implementation version='1.0' id='%s'>
      <environment name='SELF_IMPL' insert='impl' mode='replace'/>
    </implementation>
  </group>
</interface>""" % (foo_iface_uri, local_impl))
		tmp.flush()
		self.cache_iface(foo_iface_uri,
"""<?xml version="1.0" ?>
<interface last-modified="0"
 uri="%s"
 xmlns="http://zero-install.sourceforge.net/2004/injector/interface">
  <name>Foo</name>
  <summary>Foo</summary>
  <description>Foo</description>
  <implementation version='1.0' id='sha1=123'/>
</interface>""" % foo_iface_uri)
		cached_impl = basedir.save_cache_path('0install.net',
							'implementations',
							'sha1=123')
		driver = Driver(requirements = Requirements(tmp.name), config = self.config)
		self.config.network_use = model.network_offline
		os.environ['FOO_PATH'] = "old"
		old, sys.stdout = sys.stdout, StringIO()
		try:
			download_and_execute(driver, ['Hello'])
		finally:
			sys.stdout = old
		self.assertEqual(cached_impl + '/.:old',
				os.environ['FOO_PATH'])
		self.assertEqual(cached_impl + '/.:/a:/b',
				os.environ['BAR_PATH'])
		self.assertEqual('val', os.environ['NO_PATH'])
		
		self.assertEqual(os.path.join(local_impl, 'group'), os.environ['SELF_GROUP'])
		self.assertEqual(os.path.join(local_impl, 'impl'), os.environ['SELF_IMPL'])

		del os.environ['FOO_PATH']
		if 'XDG_DATA_DIRS' in os.environ:
			del os.environ['XDG_DATA_DIRS']
		os.environ['BAR_PATH'] = '/old'
		old, sys.stdout = sys.stdout, StringIO()
		try:
			download_and_execute(driver, ['Hello'])
		finally:
			sys.stdout = old
		self.assertEqual(cached_impl + '/.',
				os.environ['FOO_PATH'])
		self.assertEqual(cached_impl + '/.:/old',
				os.environ['BAR_PATH'])
		self.assertEqual(cached_impl + '/.:/usr/local/share:/usr/share',
				os.environ['XDG_DATA_DIRS'])
Ejemplo n.º 21
0
    def testAdd(self):
        sample = os.path.join(self.tmp, 'sample')
        os.mkdir(sample)
        self.populate_sample(sample)
        cli.init_stores()
        digest = 'sha1new=7e3eb25a072988f164bae24d33af69c1814eb99a'
        try:
            cli.stores.lookup(digest)
            assert False
        except NotStored:
            pass

        logger.setLevel(logging.ERROR)
        try:
            cli.do_add([digest + "b", sample])
            assert False
        except BadDigest:
            pass
        logger.setLevel(logging.WARN)

        old_stdout = sys.stdout

        cli.do_add([digest, sample])
        sys.stdout = StringIO()
        try:
            cli.do_find([digest])
            assert False
        except SystemExit as ex:
            assert ex.code == 0
        cached = sys.stdout.getvalue().strip()
        assert cached == cli.stores.lookup(digest)

        for alg in [[], ['sha1new']]:
            sys.stdout = StringIO()
            try:
                cli.do_manifest([cached] + alg)
                assert False
            except SystemExit as ex:
                assert ex.code == 0
            result = sys.stdout.getvalue()
            assert 'MyFile' in result
            assert result.split('\n')[-2] == digest

        # Verify...
        sys.stdout = StringIO()
        cli.do_verify([cached, digest])
        cli.do_verify([cached])
        cli.do_verify([digest])

        # Full audit
        cli.do_audit([os.path.dirname(cached)])

        # Corrupt it...
        os.chmod(cached, 0o700)
        open(os.path.join(cached, 'hacked'), 'w').close()

        # Verify again...
        sys.stdout = StringIO()
        try:
            cli.do_verify([cached, digest])
            assert False
        except SystemExit as ex:
            assert ex.code == 1
            result = sys.stdout.getvalue()
            sys.stdout = old_stdout
            assert 'Cached item does NOT verify' in result

        # Full audit
        sys.stdout = StringIO()
        try:
            cli.do_audit([os.path.dirname(cached)])
        except SystemExit as ex:
            assert ex.code == 1
            result = sys.stdout.getvalue()
            sys.stdout = old_stdout
            assert 'Cached item does NOT verify' in result
Ejemplo n.º 22
0
    def testXMLupdate(self):
        iface_cache = self.config.iface_cache
        trust.trust_db.trust_key('92429807C9853C0744A68B9AAE07828059A53CC1')
        with tempfile.TemporaryFile() as stream:
            stream.write(data.thomas_key)
            stream.seek(0)
            gpg.import_key(stream)

        iface = iface_cache.get_interface('http://foo')
        with tempfile.TemporaryFile() as src:
            src.write(data.foo_signed_xml)
            src.seek(0)
            pending = PendingFeed(iface.uri, src)
            assert iface_cache.update_feed_if_trusted(iface.uri, pending.sigs,
                                                      pending.new_xml)

        iface_cache.__init__()
        feed = iface_cache.get_feed('http://foo')
        assert feed.last_modified == 1154850229

        # mtimes are unreliable because copying often changes them -
        # check that we extract the time from the signature when upgrading
        upstream_dir = basedir.save_cache_path(config_site, 'interfaces')
        cached = os.path.join(upstream_dir, model.escape(feed.url))
        os.utime(cached, None)

        iface_cache.__init__()
        feed = iface_cache.get_feed('http://foo')
        assert feed.last_modified > 1154850229

        with tempfile.TemporaryFile() as src:
            src.write(data.new_foo_signed_xml)
            src.seek(0)

            pending = PendingFeed(feed.url, src)

            old_stdout = sys.stdout
            sys.stdout = StringIO()
            try:
                assert iface_cache.update_feed_if_trusted(feed.url,
                                                          pending.sigs,
                                                          pending.new_xml,
                                                          dry_run=True)
            finally:
                sys.stdout = old_stdout

            assert iface_cache.update_feed_if_trusted(feed.url, pending.sigs,
                                                      pending.new_xml)

        # Can't 'update' to an older copy
        with tempfile.TemporaryFile() as src:
            src.write(data.foo_signed_xml)
            src.seek(0)
            try:
                pending = PendingFeed(feed.url, src)
                assert iface_cache.update_feed_if_trusted(
                    feed.url, pending.sigs, pending.new_xml)

                assert 0
            except model.SafeException:
                pass