예제 #1
0
    def test_preserve(self):
        """
        L{util.InsensitiveDict} preserves the case of keys if constructed with
        C{preserve=True}.
        """
        dct = util.InsensitiveDict({"Foo": "bar", 1: 2, "fnz": {1: 2}}, preserve=1)
        self.assertEqual(dct["fnz"], {1: 2})
        self.assertEqual(dct["foo"], "bar")
        self.assertEqual(dct.copy(), dct)
        self.assertEqual(dct["foo"], dct.get("Foo"))
        self.assertIn(1, dct)
        self.assertIn("foo", dct)

        result = eval(
            repr(dct),
            {
                "dct": dct,
                "InsensitiveDict": util.InsensitiveDict,
            },
        )
        self.assertEqual(result, dct)

        keys = ["Foo", "fnz", 1]
        for x in keys:
            self.assertIn(x, dct.keys())
            self.assertIn((x, dct[x]), dct.items())
        self.assertEqual(len(keys), len(dct))
        del dct[1]
        del dct["foo"]
        self.assertEqual(dct.keys(), ["fnz"])
예제 #2
0
    def test_preserve(self):
        """
        L{util.InsensitiveDict} preserves the case of keys if constructed with
        C{preserve=True}.
        """
        dct = util.InsensitiveDict({
            'Foo': 'bar',
            1: 2,
            'fnz': {
                1: 2
            }
        },
                                   preserve=1)
        self.assertEqual(dct['fnz'], {1: 2})
        self.assertEqual(dct['foo'], 'bar')
        self.assertEqual(dct.copy(), dct)
        self.assertEqual(dct['foo'], dct.get('Foo'))
        self.assertIn(1, dct)
        self.assertIn('foo', dct)

        result = eval(repr(dct), {
            'dct': dct,
            'InsensitiveDict': util.InsensitiveDict,
        })
        self.assertEqual(result, dct)

        keys = ['Foo', 'fnz', 1]
        for x in keys:
            self.assertIn(x, dct.keys())
            self.assertIn((x, dct[x]), dct.items())
        self.assertEqual(len(keys), len(dct))
        del dct[1]
        del dct['foo']
        self.assertEqual(dct.keys(), ['fnz'])
예제 #3
0
    def callRemote(self, method, *params, **kwargs):
        if not set(['headers', 'receive_headers']).issuperset(
                kwargs.iterkeys()):
            raise ValueError()

        headers = util.InsensitiveDict({
            'Content-Type': 'application/json',
        })
        headers.update(self.headers)
        if 'headers' in kwargs:
            headers.update(kwargs['headers'])

        try:
            data, response_headers = yield getPageAndHeaders(
                url=self.url,
                method='POST',
                agent=headers.get('User-Agent', 'Twisted JSON-RPC client'),
                headers=headers,
                postdata=json.dumps({
                    'jsonrpc': '2.0',
                    'method': method,
                    'params': params,
                    'id': 0,
                }),
                timeout=self.timeout,
            )
        except error.Error, e:
            try:
                resp = json.loads(e.response)
            except:
                raise e
            if 'error' in resp and resp['error'] is not None:
                raise Error(**resp['error'])
            raise e
예제 #4
0
 def test_bytes(self):
     """
     Bytes keys are case insensitive.
     """
     d = util.InsensitiveDict(preserve=False)
     d[b"Foo"] = 1
     self.assertEqual(d[b"FOO"], 1)
     self.assertEqual(d.keys(), [b"foo"])
예제 #5
0
 def test_unicode(self):
     """
     Unicode keys are case insensitive.
     """
     d = util.InsensitiveDict(preserve=False)
     d[u"Foo"] = 1
     self.assertEqual(d[u"FOO"], 1)
     self.assertEqual(d.keys(), [u"foo"])
예제 #6
0
파일: Bots.py 프로젝트: scanlime/cia-vc
    def emptyChannels(self):
        """Called when we know we're not in any channels and we shouldn't
           be trying to join any yet.
           """
        # Map from channel name to ChannelInfo instance. This only holds
        # channels we're actually in, not those we've been asked to join
        # but aren't in yet.
        self.channels = util.InsensitiveDict()

        # clear stale timers
        if hasattr(self, 'requestedChannels'):
            for timer in self.requestedChannels.itervalues():
                if timer.active():
                    timer.cancel()

        # A map from channel name to a DelayedCall instance representing its timeout
        self.requestedChannels = util.InsensitiveDict()
예제 #7
0
 def test_abc(self):
     """
     L{util.InsensitiveDict} implements L{typing.MutableMapping}.
     """
     dct = util.InsensitiveDict()
     self.assertTrue(isinstance(dct, Iterable))
     self.assertTrue(isinstance(dct, Mapping))
     self.assertTrue(isinstance(dct, MutableMapping))
     self.assertFalse(isinstance(dct, Sequence))  # not Reversible
예제 #8
0
 def test_noPreserve(self):
     """
     L{util.InsensitiveDict} does not preserves the case of keys if
     constructed with C{preserve=False}.
     """
     dct = util.InsensitiveDict({'Foo':'bar', 1:2, 'fnz':{1:2}}, preserve=0)
     keys=['foo', 'fnz', 1]
     for x in keys:
         self.assertIn(x, dct.keys())
         self.assertIn((x, dct[x]), dct.items())
     self.assertEqual(len(keys), len(dct))
     del dct[1]
     del dct['foo']
     self.assertEqual(dct.keys(), ['fnz'])
예제 #9
0
 def test_noPreserve(self):
     """
     L{util.InsensitiveDict} does not preserves the case of keys if
     constructed with C{preserve=False}.
     """
     dct = util.InsensitiveDict({"Foo": "bar", 1: 2, "fnz": {1: 2}}, preserve=0)
     keys = ["foo", "fnz", 1]
     for x in keys:
         self.assertIn(x, dct.keys())
         self.assertIn((x, dct[x]), dct.items())
     self.assertEqual(len(keys), len(dct))
     del dct[1]
     del dct["foo"]
     self.assertEqual(dct.keys(), ["fnz"])
예제 #10
0
                    'params': params,
                    'id': 0,
                }),
                timeout=self.timeout,
            )
        except error.Error, e:
            try:
                resp = json.loads(e.response)
            except:
                raise e
            if 'error' in resp and resp['error'] is not None:
                raise Error(**resp['error'])
            raise e
        else:
            resp = json.loads(data)
            if 'error' in resp and resp['error'] is not None:
                raise Error(**resp['error'])
            if kwargs.get('receive_headers', False):
                defer.returnValue(
                    (resp['result'], util.InsensitiveDict(response_headers)))
            else:
                defer.returnValue(resp['result'])

    def __getattr__(self, attr):
        prefix = 'rpc_'
        if attr.startswith(prefix):
            return lambda *args, **kwargs: self.callRemote(
                attr[len(prefix):], *args, **kwargs)
        raise AttributeError('%r object has no attribute %r' %
                             (self.__class__.__name__, attr))
예제 #11
0
파일: Bots.py 프로젝트: scanlime/cia-vc
    def checkBots(self):
        """Search for unfulfilled requests, trying to satisfy them, then search
           for unused bots and channels, deleting them or scheduling them for deletion.
           """
        # Scan through all requests, trying to satisfy those that aren't.
        # Make note of which bots and which channels are actually being used.
        # activeBots is a map from Bot instance to a map of channels that are being used.
        usedBots = {}
        for request in self.requests:
            request.findBots()

            if not request.isFulfilled():
                # This request isn't fulfilled, try to change that
                self.tryToFulfill(request)

            for reqBot in request.bots:
                # Make note of the bots and channels this request needs,
                # and if the bot is already marked as inactive, cancel that.
                usedBots.setdefault(
                    reqBot, util.InsensitiveDict())[request.channel] = True

                # Make sure that any referenced bots are no longer marked inactive
                if reqBot in self.inactiveBots:
                    timer = self.inactiveBots[reqBot]
                    if timer.active():
                        timer.cancel()
                    del self.inactiveBots[reqBot]

        # Now look for unused bots and/or channels
        for network in self.networks.itervalues():
            for bot in network:
                if bot in usedBots:
                    usedChannels = usedBots[bot]

                    # We need this bot.. but are all the channels necessary?
                    for channel in bot.channels.iterkeys():
                        if channel not in usedChannels:
                            bot.part(channel)

                    # Since we need this bot, make sure it's still responsive. If its lag
                    # is too high, force it to give up. IF we have to disconnect the bot,
                    # give up this checkBots() and start over when botDisconnected() calls
                    # us again.
                    if bot.getLag() > self.maximumLag:
                        bot.quit()
                        self.botDisconnected(bot)
                        return

                else:
                    # We don't need this bot. Tell it to part all of its channels,
                    # and if it isn't already, schedule it for deletion.
                    for channel in bot.channels.iterkeys():
                        bot.part(channel)
                    if bot not in self.inactiveBots:
                        self.inactiveBots[bot] = reactor.callLater(
                            self.botInactivityTimeout,
                            self.botInactivityCallback, bot)

        # Set up the next round of bot checking
        if self.botCheckTimer and self.botCheckTimer.active():
            self.botCheckTimer.cancel()
        self.botCheckTimer = reactor.callLater(self.botCheckInterval,
                                               self.checkBots)