Ejemplo n.º 1
0
    def setUpUpgradeTest(self):
        # set up the "real" db if desired
        if self.use_real_db:
            # note this changes self.db_url
            yield self.setUpRealDatabase(sqlite_memory=False)

        self.basedir = None

        if self.source_tarball:
            tarball = util.sibpath(__file__, self.source_tarball)
            if not os.path.exists(tarball):
                raise unittest.SkipTest("'{}' not found (normal when not building from Git)".format(
                        tarball))

            tf = tarfile.open(tarball)
            prefixes = set()
            for inf in tf:
                tf.extract(inf)
                prefixes.add(inf.name.split('/', 1)[0])
            tf.close()
            # (note that tf.extractall isn't available in py2.4)

            # get the top-level dir from the tarball
            assert len(prefixes) == 1, "tarball has multiple top-level dirs!"
            self.basedir = prefixes.pop()
        else:
            if not os.path.exists("basedir"):
                os.makedirs("basedir")
            self.basedir = os.path.abspath("basedir")

        self.master = master = fakemaster.make_master(self)
        master.config.db['db_url'] = self.db_url
        self.db = connector.DBConnector(self.basedir)
        yield self.db.setServiceParent(master)
        yield self.db.setup(check_version=False)

        self._sql_log_handler = querylog.start_log_queries()
Ejemplo n.º 2
0
    def test_isIdentifier(self):
        os_encoding = locale.getpreferredencoding()
        try:
            u'\N{SNOWMAN}'.encode(os_encoding)
        except UnicodeEncodeError:
            # Default encoding of Windows console is 'cp1252'
            # which cannot encode the snowman.
            raise(unittest.SkipTest("Cannot encode weird unicode "
                "on this platform with {}".format(os_encoding)))

        good = [
            u"linux", u"Linux", u"abc123", u"a" * 50, u'\N{SNOWMAN}'
        ]
        for g in good:
            log.msg('expect %r to be good' % (g,))
            self.assertTrue(identifiers.isIdentifier(50, g))
        bad = [
            None, u'', b'linux', u'a/b', u"a.b.c.d",
            u"a-b_c.d9", 'spaces not allowed', u"a" * 51,
            u"123 no initial digits", u'\N{SNOWMAN}.\N{SNOWMAN}',
        ]
        for b in bad:
            log.msg('expect %r to be bad' % (b,))
            self.assertFalse(identifiers.isIdentifier(50, b))
Ejemplo n.º 3
0
 def test_unreadable_config(self):
     if sys.platform == "win32":
         # if somebody knows a clever way to do this (cause
         # EnvironmentError when reading a file that really exists), on
         # windows, please fix this
         raise unittest.SkipTest("can't make unreadable files on windows")
     basedir = "test_client.Basic.test_unreadable_config"
     os.mkdir(basedir)
     fn = os.path.join(basedir, "tahoe.cfg")
     fileutil.write(fn, BASECONFIG)
     old_mode = os.stat(fn).st_mode
     os.chmod(fn, 0)
     try:
         e = self.assertRaises(
             EnvironmentError,
             read_config,
             basedir,
             "client.port",
             _valid_config_sections=client._valid_config_sections,
         )
         self.assertIn("Permission denied", str(e))
     finally:
         # don't leave undeleteable junk lying around
         os.chmod(fn, old_mode)
Ejemplo n.º 4
0
    def setUp(self):
        if requests is None:
            raise unittest.SkipTest("Need to install requests to test oauth2")

        self.patch(requests, 'request', mock.Mock(spec=requests.request))
        self.patch(requests, 'post', mock.Mock(spec=requests.post))
        self.patch(requests, 'get', mock.Mock(spec=requests.get))

        self.googleAuth = oauth2.GoogleAuth("ggclientID", "clientSECRET")
        self.githubAuth = oauth2.GitHubAuth("ghclientID", "clientSECRET")
        self.githubAuth_v4 = oauth2.GitHubAuth(
            "ghclientID", "clientSECRET", apiVersion=4)
        self.githubAuth_v4_teams = oauth2.GitHubAuth(
            "ghclientID", "clientSECRET", apiVersion=4, getTeamsMembership=True)
        self.githubAuthEnt = oauth2.GitHubAuth(
            "ghclientID", "clientSECRET", serverURL="https://git.corp.fakecorp.com")
        self.gitlabAuth = oauth2.GitLabAuth(
            "https://gitlab.test/", "glclientID", "clientSECRET")
        self.bitbucketAuth = oauth2.BitbucketAuth("bbclientID", "clientSECRET")

        for auth in [self.googleAuth, self.githubAuth, self.githubAuth_v4, self.githubAuth_v4_teams,
                     self.githubAuthEnt, self.gitlabAuth, self.bitbucketAuth]:
            self._master = master = self.make_master(url='h:/a/b/', auth=auth)
            auth.reconfigAuth(master, master.config)
Ejemplo n.º 5
0
    def test_timeDeltaToHumanReadable(self):
        """
        It will return a human readable time difference.
        """
        try:
            datetime.datetime.fromtimestamp(1)
        except OSError as e:
            raise unittest.SkipTest(
                "Python 3.6 bug on Windows: "
                "https://bugs.python.org/issue29097") from e
        result = util.human_readable_delta(1, 1)
        self.assertEqual('super fast', result)

        result = util.human_readable_delta(1, 2)
        self.assertEqual('1 seconds', result)

        result = util.human_readable_delta(1, 61)
        self.assertEqual('1 minutes', result)

        result = util.human_readable_delta(1, 62)
        self.assertEqual('1 minutes, 1 seconds', result)

        result = util.human_readable_delta(1, 60 * 60 + 1)
        self.assertEqual('1 hours', result)

        result = util.human_readable_delta(1, 60 * 60 + 61)
        self.assertEqual('1 hours, 1 minutes', result)

        result = util.human_readable_delta(1, 60 * 60 + 62)
        self.assertEqual('1 hours, 1 minutes, 1 seconds', result)

        result = util.human_readable_delta(1, 24 * 60 * 60 + 1)
        self.assertEqual('1 days', result)

        result = util.human_readable_delta(1, 24 * 60 * 60 + 2)
        self.assertEqual('1 days, 1 seconds', result)
Ejemplo n.º 6
0
    def test_unknown(self):
        self.cfg.what = filename = "unknown"
        send_dir = self.mktemp()
        os.mkdir(send_dir)
        abs_filename = os.path.abspath(os.path.join(send_dir, filename))
        self.cfg.cwd = send_dir

        try:
            os.mkfifo(abs_filename)
        except AttributeError:
            raise unittest.SkipTest("is mkfifo supported on this platform?")

        # Delete the named pipe for the sake of users who might run "pip
        # wheel ." in this directory later. That command wants to copy
        # everything into a tempdir before building a wheel, and the
        # shutil.copy_tree() is uses can't handle the named pipe.
        self._things_to_delete.append(abs_filename)

        self.assertFalse(os.path.isfile(abs_filename))
        self.assertFalse(os.path.isdir(abs_filename))

        e = self.assertRaises(TypeError, build_offer, self.cfg)
        self.assertEqual(str(e),
                         "'%s' is neither file nor directory" % filename)
Ejemplo n.º 7
0
    def test_listdir_unicode(self):
        if 'dirlist' not in dir(self):
            return

        try:
            u"test".encode(self.filesystem_encoding)
        except (LookupError, AttributeError):
            raise unittest.SkipTest(
                "This platform does not support the '%s' filesystem encoding "
                "that we are testing for the benefit of a different platform."
                % (self.filesystem_encoding, ))

        def call_os_listdir(path):
            if PY2:
                return self.dirlist
            else:
                # Python 3 always lists unicode filenames:
                return [
                    d.decode(self.filesystem_encoding)
                    if isinstance(d, bytes) else d for d in self.dirlist
                ]

        self.patch(os, 'listdir', call_os_listdir)

        def call_sys_getfilesystemencoding():
            return self.filesystem_encoding

        self.patch(sys, 'getfilesystemencoding',
                   call_sys_getfilesystemencoding)

        _reload()
        filenames = listdir_unicode(u'/dummy')

        self.failUnlessEqual(
            set([encodingutil.normalize(fname) for fname in filenames]),
            set(TEST_FILENAMES))
Ejemplo n.º 8
0
    def test_ignore_symlinks(self):
        if not hasattr(os, 'symlink'):
            raise unittest.SkipTest(
                "Symlinks are not supported by Python on this platform.")

        self.basedir = os.path.dirname(self.mktemp())
        self.set_up_grid(oneshare=True)

        source = os.path.join(self.basedir, "home")
        self.writeto("foo.txt", "foo")
        os.symlink(os.path.join(source, "foo.txt"),
                   os.path.join(source, "foo2.txt"))

        d = self.do_cli("create-alias", "tahoe")
        d.addCallback(lambda res: self.do_cli("backup", "--verbose", source,
                                              "tahoe:test"))

        def _check((rc, out, err)):
            self.failUnlessReallyEqual(rc, 2)
            foo2 = os.path.join(source, "foo2.txt")
            self.failUnlessIn("WARNING: cannot backup symlink ", err)
            self.failUnlessIn(foo2, err)

            fu, fr, fs, dc, dr, ds = self.count_output(out)
            # foo.txt
            self.failUnlessReallyEqual(fu, 1)
            self.failUnlessReallyEqual(fr, 0)
            # foo2.txt
            self.failUnlessReallyEqual(fs, 1)
            # home
            self.failUnlessReallyEqual(dc, 1)
            self.failUnlessReallyEqual(dr, 0)
            self.failUnlessReallyEqual(ds, 0)

        d.addCallback(_check)
        return d
Ejemplo n.º 9
0
    def setUp(self):
        if not ssh:
            raise unittest.SkipTest("Crypto requirements missing, can't run historic recvline tests over ssh")

        u, p = 'testuser', 'testpass'
        rlm = TerminalRealm()
        rlm.userFactory = TestUser
        rlm.chainedProtocolFactory = lambda: insultsServer

        ptl = portal.Portal(
            rlm,
            [checkers.InMemoryUsernamePasswordDatabaseDontUse(**{u: p})])
        sshFactory = ConchFactory(ptl)
        sshFactory.serverProtocol = self.serverProtocol
        sshFactory.startFactory()

        recvlineServer = self.serverProtocol()
        insultsServer = insults.ServerProtocol(lambda: recvlineServer)
        sshServer = sshFactory.buildProtocol(None)
        clientTransport = LoopbackRelay(sshServer)

        recvlineClient = NotifyingExpectableBuffer()
        insultsClient = insults.ClientProtocol(lambda: recvlineClient)
        sshClient = TestTransport(lambda: insultsClient, (), {}, u, p, self.WIDTH, self.HEIGHT)
        serverTransport = LoopbackRelay(sshClient)

        sshClient.makeConnection(clientTransport)
        sshServer.makeConnection(serverTransport)

        self.recvlineClient = recvlineClient
        self.sshClient = sshClient
        self.sshServer = sshServer
        self.clientTransport = clientTransport
        self.serverTransport = serverTransport

        return recvlineClient.onConnection
Ejemplo n.º 10
0
    def get_commons_for_dump(self):
        import sys
        sys.path.append('../mamba/test/dummy_app')
        mgr = ModelManager()
        if GNU_LINUX:
            self.addCleanup(mgr.notifier.loseConnection)

        from mamba import Model
        from mamba.test.test_model import DummyThreadPool, DatabaseModuleError
        try:
            threadpool = DummyThreadPool()
            database = Database(threadpool, True)
            Model.database = database

            store = database.store()
            store.execute('CREATE TABLE IF NOT EXISTS `dummy` ('
                          '    id INTEGER PRIMARY KEY, name TEXT'
                          ')')
            store.execute('CREATE TABLE IF NOT EXISTS `stubing` ('
                          '   id INTEGER PRIMARY KEY, name TEXT'
                          ')')
            store.commit()
        except DatabaseModuleError, error:
            raise unittest.SkipTest(error)
Ejemplo n.º 11
0
 def testIRC(self):
     if not words:
         raise unittest.SkipTest("Twisted Words package is not installed")
     master = self.buildmaster
     master.loadChanges()
     d = master.loadConfig(emptyCfg)
     e1 = {}
     d.addCallback(lambda res: self.checkIRC(master, e1))
     d.addCallback(lambda res: master.loadConfig(ircCfg1))
     e2 = {'irc.us.freenode.net': ('buildbot', ['twisted'])}
     d.addCallback(lambda res: self.checkIRC(master, e2))
     d.addCallback(lambda res: master.loadConfig(ircCfg2))
     e3 = {
         'irc.us.freenode.net': ('buildbot', ['twisted']),
         'irc.example.com': ('otherbot', ['chan1', 'chan2'])
     }
     d.addCallback(lambda res: self.checkIRC(master, e3))
     d.addCallback(lambda res: master.loadConfig(ircCfg3))
     e4 = {'irc.us.freenode.net': ('buildbot', ['knotted'])}
     d.addCallback(lambda res: self.checkIRC(master, e4))
     d.addCallback(lambda res: master.loadConfig(ircCfg1))
     e5 = {'irc.us.freenode.net': ('buildbot', ['twisted'])}
     d.addCallback(lambda res: self.checkIRC(master, e5))
     return d
Ejemplo n.º 12
0
    def test_router_session_goodbye_onLeave_error(self):
        """
        Reason should be propagated properly from Goodbye message
        """
        raise unittest.SkipTest('FIXME: Adjust unit test mocks #1567')

        from crossbar.router.session import RouterApplicationSession
        session = mock.Mock()
        the_exception = RuntimeError("onLeave fails")

        def boom(*args, **kw):
            raise the_exception
        session.onLeave = mock.Mock(side_effect=boom)
        session._realm = u'realm'
        router_factory = mock.Mock()
        rap = RouterApplicationSession(session, router_factory)

        rap.send(message.Hello(u'realm', {u'caller': role.RoleCallerFeatures()}))
        session.reset_mock()
        rap.send(message.Goodbye(u'wamp.reason.logout', u'some custom message'))

        errors = self.flushLoggedErrors()
        self.assertEqual(1, len(errors))
        self.assertEqual(the_exception, errors[0].value)
Ejemplo n.º 13
0
    def testShared(self):
        if not crypto:
            raise unittest.SkipTest("crypto not available, shared ports "
                                    "require TubIDs and thus crypto")
        s1, s2, s3 = self.services
        # s1 and s2 will share a Listener
        l1 = s1.listenOn("tcp:0:interface=127.0.0.1")
        s1.setLocation("localhost:%d" % l1.getPortnum())
        s2.listenOn(l1)
        s2.setLocation("localhost:%d" % l1.getPortnum())

        t1 = Target("one")
        t2 = Target("two")
        self.targets = [t1, t2]
        url1 = s1.registerReference(t1, "target")
        url2 = s2.registerReference(t2, "target")
        self.urls = [url1, url2]

        d = s3.getReference(url1)
        d.addCallback(lambda ref: ref.callRemote('add', a=1, b=1))
        d.addCallback(lambda res: s3.getReference(url2))
        d.addCallback(lambda ref: ref.callRemote('add', a=2, b=2))
        d.addCallback(self._testShared_1)
        return d
Ejemplo n.º 14
0
    def setUp(self):
        self.setUpTestReactor()
        if requests is None:
            raise unittest.SkipTest("Need to install requests to test oauth2")

        self.patch(requests, 'request', mock.Mock(spec=requests.request))
        self.patch(requests, 'post', mock.Mock(spec=requests.post))
        self.patch(requests, 'get', mock.Mock(spec=requests.get))

        self.googleAuth = oauth2.GoogleAuth("ggclientID", "clientSECRET")
        self.githubAuth = oauth2.GitHubAuth("ghclientID", "clientSECRET")
        self.githubAuth_v4 = oauth2.GitHubAuth(
            "ghclientID", "clientSECRET", apiVersion=4)
        self.githubAuth_v4_teams = oauth2.GitHubAuth(
            "ghclientID", "clientSECRET", apiVersion=4, getTeamsMembership=True)
        self.githubAuthEnt = oauth2.GitHubAuth(
            "ghclientID", "clientSECRET", serverURL="https://git.corp.fakecorp.com")
        self.gitlabAuth = oauth2.GitLabAuth(
            "https://gitlab.test/", "glclientID", "clientSECRET")
        self.bitbucketAuth = oauth2.BitbucketAuth("bbclientID", "clientSECRET")

        for auth in [self.googleAuth, self.githubAuth, self.githubAuth_v4, self.githubAuth_v4_teams,
                     self.githubAuthEnt, self.gitlabAuth, self.bitbucketAuth]:
            self._master = master = self.make_master(url='h:/a/b/', auth=auth)
            auth.reconfigAuth(master, master.config)

        self.githubAuth_secret = oauth2.GitHubAuth(
            Secret("client-id"), Secret("client-secret"), apiVersion=4)
        self._master = master = self.make_master(url='h:/a/b/', auth=auth)
        fake_storage_service = FakeSecretStorage()
        fake_storage_service.reconfigService(secretdict={"client-id": "secretClientId",
                                                         "client-secret": "secretClientSecret"})
        secret_service = SecretManager()
        secret_service.services = [fake_storage_service]
        secret_service.setServiceParent(self._master)
        self.githubAuth_secret.reconfigAuth(master, master.config)
Ejemplo n.º 15
0
    def setUp(self):
        self.d = tempfile.mkdtemp()
        self.bcp = BravoConfigParser()

        self.bcp.add_section("world unittest")
        self.bcp.set("world unittest", "url", "file://%s" % self.d)
        self.bcp.set("world unittest", "serializer", "alpha")

        self.w = World(self.bcp, "unittest")
        self.w.pipeline = []
        self.w.start()

        self.f = GrassMockFactory()
        self.f.world = self.w
        self.w.factory = self.f

        pp = {"factory": self.f}

        plugins = retrieve_plugins(IAutomaton, parameters=pp)

        if "grass" not in plugins:
            raise unittest.SkipTest("Plugin not present")

        self.hook = plugins["grass"]
Ejemplo n.º 16
0
    def _copyDescFilesHere(self, authdirs, files):
        """Copy all the **files** to the _trial_tmp/ directory.

        :param list authdirs: A list of strings representing the directories
            from BridgeAuthorities, as in the BRIDGE_AUTHORITY_DIRECTORIES
            config option.
        :param list files: A list of strings representing the paths to
            descriptor files. This should probably be taken from a
            ``bridgedb.persistent.Conf`` object which has parsed the
            ``bridgedb.conf`` file in the top-level directory of this repo.
        :rtype: list
        :returns: A list of the new paths (in the ``_trial_tmp`` directory) to
            the copied descriptor files. This should be used to update the
            ``bridgedb.persistent.Conf`` object.
        """
        updatedPaths = []

        for d in authdirs:
            for f in files:
                base = os.path.basename(f)
                src = os.path.join(CI_RUNDIR, d, base)
                if os.path.isfile(src):
                    dstdir = os.path.join(HERE, d)
                    if not os.path.isdir(dstdir):
                        os.mkdir(dstdir)
                        self._directories_created.append(dstdir)
                    dst = os.path.join(dstdir, base)
                    shutil.copy(src, dst)
                    updatedPaths.append(dst)
                else:
                    self.skip = True
                    raise unittest.SkipTest(
                        "Can't find mock descriptor files in %s directory" %
                        CI_RUNDIR)

        return updatedPaths
Ejemplo n.º 17
0
    def test_store(self):
        try:
            from google.cloud.storage import Client  # noqa
        except ImportError:
            raise unittest.SkipTest(
                "GCSFeedStorage requires google-cloud-storage")

        uri = 'gs://mybucket/export.csv'
        project_id = 'myproject-123'
        acl = 'publicRead'
        (client_mock, bucket_mock, blob_mock) = mock_google_cloud_storage()
        with mock.patch('google.cloud.storage.Client') as m:
            m.return_value = client_mock

            f = mock.Mock()
            storage = GCSFeedStorage(uri, project_id, acl)
            yield storage.store(f)

            f.seek.assert_called_once_with(0)
            m.assert_called_once_with(project=project_id)
            client_mock.get_bucket.assert_called_once_with('mybucket')
            bucket_mock.blob.assert_called_once_with('export.csv')
            blob_mock.upload_from_file.assert_called_once_with(
                f, predefined_acl=acl)
Ejemplo n.º 18
0
    def testLoadUnimportedPlainItem(self):
        """
        Test that an Item in the database can be loaded out of the
        database, even if the module defining its Python class has not
        been imported, as long as its class definition has not moved
        since it was added to the database.
        """
        storePath = self.mktemp()
        st = store.Store(storePath)
        itemID = itemtest.PlainItem(store=st, plain=u'Hello, world!!!').storeID
        st.close()

        e = os.environ.copy()
        # Kind of a heuristic - hmmm
        e['PYTHONPATH'] = os.pathsep.join(
            sys.path
        )  # os.pathsep.join([dir for dir in sys.path if not dir.startswith(sys.prefix)])
        d = defer.Deferred()
        p = ProcessOutputCollector(d)
        try:
            reactor.spawnProcess(p, sys.executable, [
                "python", '-Wignore',
                itemtestmain.__file__.rstrip('co'), storePath,
                str(itemID)
            ], e)
        except NotImplementedError:
            raise unittest.SkipTest("Implement processes here")

        def cbOutput(output):
            self.assertEquals(''.join(output).strip(), 'Hello, world!!!')

        def ebBlah(err):
            log.err(err)
            self.fail(''.join(err.value.args[0].error))

        return d.addCallbacks(cbOutput, ebBlah)
Ejemplo n.º 19
0
 def test_persist(self):
     assert_gcs_environ()
     uri = os.environ.get('GCS_TEST_FILE_URI')
     if not uri:
         raise unittest.SkipTest("No GCS URI available for testing")
     data = b"TestGCSFilesStore: \xe2\x98\x83"
     buf = BytesIO(data)
     meta = {'foo': 'bar'}
     path = 'full/filename'
     store = GCSFilesStore(uri)
     store.POLICY = 'authenticatedRead'
     expected_policy = {'role': 'READER', 'entity': 'allAuthenticatedUsers'}
     yield store.persist_file(path, buf, info=None, meta=meta, headers=None)
     s = yield store.stat_file(path, info=None)
     self.assertIn('last_modified', s)
     self.assertIn('checksum', s)
     self.assertEqual(s['checksum'], 'zc2oVgXkbQr2EQdSdw3OPA==')
     u = urlparse(uri)
     content, acl, blob = get_gcs_content_and_delete(u.hostname, u.path[1:] + path)
     self.assertEqual(content, data)
     self.assertEqual(blob.metadata, {'foo': 'bar'})
     self.assertEqual(blob.cache_control, GCSFilesStore.CACHE_CONTROL)
     self.assertEqual(blob.content_type, 'application/octet-stream')
     self.assertIn(expected_policy, acl)
Ejemplo n.º 20
0
    def test_download_gzip_response(self):
        crawler = get_crawler(SingleRequestSpider)
        body = b'1' * 100  # PayloadResource requires body length to be 100
        request = Request(self.mockserver.url('/payload'),
                          method='POST',
                          body=body,
                          meta={'download_maxsize': 50})
        yield crawler.crawl(seed=request)
        failure = crawler.spider.meta['failure']
        # download_maxsize < 100, hence the CancelledError
        self.assertIsInstance(failure.value, defer.CancelledError)

        if six.PY2:
            request.headers.setdefault(b'Accept-Encoding', b'gzip,deflate')
            request = request.replace(url=self.mockserver.url('/xpayload'))
            yield crawler.crawl(seed=request)
            # download_maxsize = 50 is enough for the gzipped response
            failure = crawler.spider.meta.get('failure')
            self.assertTrue(failure == None)
            reason = crawler.spider.meta['close_reason']
            self.assertTrue(reason, 'finished')
        else:
            # See issue https://twistedmatrix.com/trac/ticket/8175
            raise unittest.SkipTest("xpayload only enabled for PY2")
Ejemplo n.º 21
0
    def test_decorating(self):
        import sys
        if sys.version_info < (2, 4):
            raise unittest.SkipTest(
                'decorators only available on 2.4 and later')
        ae = self.assertEquals
        ar = self.assertRaises

        # Has to be elsewhere to avoid SyntaxErrors :-(
        from shtoom.test.py24tests import Dectest

        # XXX actually test the stupid things?!
        d = Dectest()
        ae(d.foo.cache_inProgressOnly, False)
        ae(d.foo.cache_inProgressOnly, False)
        ae(d.foo2.cache_inProgressOnly, True)
        ae(d.foo3.cache_inProgressOnly, True)
        ae(d.foo3.cache_hashableArgs, False)
        ar(TypeError, d.foo2, {})
        s = Saver()
        d = d.foo(1, 2, 3)
        d.addCallback(s.save)
        util.wait(d)
        ae(s.val, (1, 2, 3))
Ejemplo n.º 22
0
    def test_router_session_internal_error_onAuthenticate(self):
        """
        similar to above, but during _RouterSession's onMessage handling,
        where it calls self.onAuthenticate)
        """
        raise unittest.SkipTest('FIXME: Adjust unit test mocks #1567')

        # setup
        transport = mock.MagicMock()
        transport.transport_details = TransportDetails(
            channel_id={'tls-unique': b'deadbeef'})
        the_exception = RuntimeError("kerblam")

        def boom(*args, **kw):
            raise the_exception

        session = self.session_factory(
        )  # __call__ on the _RouterSessionFactory
        session.onAuthenticate = boom
        session.onOpen(transport)
        msg = message.Authenticate('bogus signature')

        # XXX think: why isn't this using _RouterSession.log?
        from crossbar.router.session import RouterSession
        with mock.patch.object(RouterSession, 'log') as logger:
            # do the test; should call onHello which is now "boom", above
            session.onMessage(msg)

            # check we got the right log.failure() call
            self.assertTrue(len(logger.method_calls) > 0)
            call = logger.method_calls[0]
            # for a MagicMock call-object, 0th thing is the method-name, 1st
            # thing is the arg-tuple, 2nd thing is the kwargs.
            self.assertEqual(call[0], 'failure')
            self.assertTrue('failure' in call[2])
            self.assertEqual(call[2]['failure'].value, the_exception)
Ejemplo n.º 23
0
 def requireCrypto(self):
     if not crypto_available:
         raise unittest.SkipTest("crypto not available")
Ejemplo n.º 24
0
 def setUp(self):
     super().setUp()
     if boto3 is None:
         raise unittest.SkipTest("moto not found")
Ejemplo n.º 25
0
 def _skipCheck(self):
     if not self.redis_2_8_9:
         skipMsg = "Redis version < 2.8.9 (found version: %s)"
         raise unittest.SkipTest(skipMsg % self.redis_version)
 def test_download_with_proxy_https_noconnect(self):
     raise unittest.SkipTest(
         'noconnect is not supported in HTTP10DownloadHandler')
Ejemplo n.º 27
0
 def delete_test_env():
     try:
         rm_db_and_blob_dir(self.db_dir, self.blob_dir)
         rm_db_and_blob_dir(self.server_db_dir, self.server_blob_dir)
     except:
         raise unittest.SkipTest("TODO: fix this for windows")
Ejemplo n.º 28
0
def skip_if_cannot_represent_argv(u):
    precondition(isinstance(u, unicode))
    try:
        u.encode(get_io_encoding())
    except UnicodeEncodeError:
        raise unittest.SkipTest("A non-ASCII argv could not be encoded on this platform.")
Ejemplo n.º 29
0
 def test_runspider_unable_to_load(self):
     raise unittest.SkipTest("Already Tested in 'RunSpiderCommandTest' ")
Ejemplo n.º 30
0
def skipCase(testcase):
    for skipped_module in modules_to_skip:
        tc_mod_path = testcase.__module__.split('.')
        mod_target = skipped_module.split('.')[-1]
        if mod_target in tc_mod_path:
            raise unittest.SkipTest('TestCase excluded by: %s' % skipped_module)