twisted.python.compat.set

Here are the examples of the python api twisted.python.compat.set taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

55 Examples 7

Page 1 Selected Page 2

Example 1

Project: SubliminalCollaborator Source File: test_zipstream.py
Function: test_unzipiterchunky
    def test_unzipIterChunky(self):
        """
        L{twisted.python.zipstream.unzipIterChunky} returns an iterator which
        must be exhausted to completely unzip the input archive.
        """
        numfiles = 10
        contents = ['This is test file %d!' % i for i in range(numfiles)]
        zpfilename = self.makeZipFile(contents)
        list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))
        self.assertEqual(
            set(self.unzipdir.listdir()),
            set(map(str, range(numfiles))))

        for child in self.unzipdir.children():
            num = int(child.basename())
            self.assertEqual(child.getContent(), contents[num])

Example 2

Project: SubliminalCollaborator Source File: test_http_headers.py
Function: test_iteration
    def test_iteration(self):
        """
        L{_DictHeaders.__iter__} returns an iterator the elements of which
        are the lowercase name of each header present.
        """
        headers, wrapper = self.headers(foo=["lemur", "panda"], bar=["baz"])
        self.assertEqual(set(list(wrapper)), set(["foo", "bar"]))

Example 3

Project: mythbox Source File: test_paths.py
    def test_walkObeysDescend(self):
        """
        Verify that when the supplied C{descend} predicate returns C{False},
        the target is not traversed.
        """
        self.createLinks()
        def noSymLinks(path):
            return not path.islink()
        x = [foo.path for foo in self.path.walk(descend=noSymLinks)]
        self.assertEquals(set(x), set(self.all))

Example 4

Project: SubliminalCollaborator Source File: maildir.py
    def undeleteMessages(self):
        """
        Reset deletion tracking, undeleting any messages which have been
        deleted since the last call to C{sync}.
        """
        self._delete = set()

Example 5

Project: mythbox Source File: runner.py
    def loadByNames(self, names, recurse=False):
        """
        Construct a TestSuite containing all the tests found in 'names', where
        names is a list of fully qualified python names and/or filenames. The
        suite returned will have no duplicate tests, even if the same object
        is named twice.
        """
        things = []
        errors = []
        for name in names:
            try:
                things.append(self.findByName(name))
            except:
                errors.append(ErrorHolder(name, failure.Failure()))
        suites = [self.loadAnything(thing, recurse)
                  for thing in set(things)]
        suites.extend(errors)
        return self.suiteFactory(suites)

Example 6

Project: mythbox Source File: test_jelly.py
    def test_setSecurity(self):
        """
        By default, C{set} objects should be allowed by
        L{jelly.SecurityOptions}. If not allowed, L{jelly.unjelly} should raise
        L{jelly.InsecureJelly} when trying to unjelly it.
        """
        inputList = [set([1, 2, 3])]
        self._testSecurity(inputList, "set")

Example 7

Project: SubliminalCollaborator Source File: test_jelly.py
Function: test_set
    def test_set(self):
        """
        Check that a C{set} can contain a circular reference and be serialized
        and unserialized without losing the reference.
        """
        s = set()
        a = SimpleJellyTest(s, None)
        s.add(a)
        res = jelly.unjelly(jelly.jelly(a))
        self.assertIsInstance(res.x, set)
        self.assertEqual(list(res.x), [res])

Example 8

Project: SubliminalCollaborator Source File: test_http_headers.py
    def test_getAllRawHeaders(self):
        """
        L{Headers.getAllRawHeaders} returns an iterable of (k, v) pairs, where
        C{k} is the canonicalized representation of the header name, and C{v}
        is a sequence of values.
        """
        h = Headers()
        h.setRawHeaders("test", ["lemurs"])
        h.setRawHeaders("www-authenticate", ["basic aksljdlk="])

        allHeaders = set([(k, tuple(v)) for k, v in h.getAllRawHeaders()])

        self.assertEqual(allHeaders,
                          set([("WWW-Authenticate", ("basic aksljdlk=",)),
                               ("Test", ("lemurs",))]))

Example 9

Project: SubliminalCollaborator Source File: test_http_headers.py
Function: test_items
    def test_items(self, _method='items', _requireList=True):
        """
        L{_DictHeaders.items} will return a list of all present header names
        and values as tuples, returning only the last value for headers with
        more than one.
        """
        headers, wrapper = self.headers(foo=["lemur"], bar=["marmot", "panda"])
        items = getattr(wrapper, _method)()
        if _requireList:
            self.assertIsInstance(items, list)
        self.assertEqual(set(items), set([("foo", "lemur"), ("bar", "panda")]))

Example 10

Project: mythbox Source File: test_zipstream.py
Function: test_unzipiterchunkydirectory
    def test_unzipIterChunkyDirectory(self):
        """
        The path to which a file is extracted by L{zipstream.unzipIterChunky}
        is determined by joining the C{directory} argument to C{unzip} with the
        path within the archive of the file being extracted.
        """
        numfiles = 10
        contents = ['This is test file %d!' % i for i in range(numfiles)]
        zpfilename = self.makeZipFile(contents, 'foo')
        list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))
        self.assertEquals(
            set(self.unzipdir.child('foo').listdir()),
            set(map(str, range(numfiles))))

        for child in self.unzipdir.child('foo').children():
            num = int(child.basename())
            self.assertEquals(child.getContent(), contents[num])

Example 11

Project: SubliminalCollaborator Source File: test_jelly.py
Function: test_oldsets
    def test_oldSets(self):
        """
        Test jellying C{sets.Set}: it should serialize to the same thing as
        C{set} jelly, and be unjellied as C{set} if available.
        """
        inputList = [jelly._sets.Set([1, 2, 3])]
        inputJelly = jelly.jelly(inputList)
        self.assertEqual(inputJelly, jelly.jelly([set([1, 2, 3])]))
        output = jelly.unjelly(inputJelly)
        # Even if the class is different, it should coerce to the same list
        self.assertEqual(list(inputList[0]), list(output[0]))
        if set is jelly._sets.Set:
            self.assertIsInstance(output[0], jelly._sets.Set)
        else:
            self.assertIsInstance(output[0], set)

Example 12

Project: mythbox Source File: test_zipstream.py
Function: test_unzip
    def test_unzip(self):
        """
        L{twisted.python.zipstream.unzip} should extract all files from a zip
        archive
        """
        numfiles = 3
        zpfilename = self.makeZipFile([str(i) for i in range(numfiles)])
        zipstream.unzip(zpfilename, self.unzipdir.path)
        self.assertEqual(
            set(self.unzipdir.listdir()),
            set(map(str, range(numfiles))))
        for i in range(numfiles):
            self.assertEqual(self.unzipdir.child(str(i)).getContent(), str(i))

Example 13

Project: mythbox Source File: test_tap.py
    def test_checkersPamAuth(self):
        """
        The L{OpenSSHFactory} built by L{tap.makeService} has a portal with
        L{IPluggableAuthenticationModules}, L{ISSHPrivateKey} and
        L{IUsernamePassword} interfaces registered as checkers if C{pamauth} is
        available.
        """
        # Fake the presence of pamauth, even if PyPAM is not installed
        self.patch(tap, "pamauth", object())
        config = tap.Options()
        service = tap.makeService(config)
        portal = service.args[1].portal
        self.assertEquals(
            set(portal.checkers.keys()),
            set([IPluggableAuthenticationModules, ISSHPrivateKey,
                 IUsernamePassword]))

Example 14

Project: mythbox Source File: test_jelly.py
Function: test_set
    def test_set(self):
        """
        Jellying C{set} instances and then unjellying the result
        should produce objects which represent the values of the original
        inputs.
        """
        inputList = [set([1, 2, 3])]
        output = jelly.unjelly(jelly.jelly(inputList))
        self.assertEquals(inputList, output)
        self.assertNotIdentical(inputList, output)

Example 15

Project: SubliminalCollaborator Source File: test_client.py
    def test_disallowedPort(self):
        """
        If a port number is initially selected which cannot be bound, the
        L{CannotListenError} is handled and another port number is attempted.
        """
        ports = []

        class FakeReactor(object):
            def listenUDP(self, port, *args):
                ports.append(port)
                if len(ports) == 1:
                    raise error.CannotListenError(None, port, None)

        resolver = client.Resolver(servers=[('example.com', 53)])
        resolver._reactor = FakeReactor()

        proto = resolver._connectedProtocol()
        self.assertEqual(len(set(ports)), 2)

Example 16

Project: SubliminalCollaborator Source File: test_jelly.py
Function: test_set
    def test_set(self):
        """
        Jellying C{set} instances and then unjellying the result
        should produce objects which represent the values of the original
        inputs.
        """
        inputList = [set([1, 2, 3])]
        output = jelly.unjelly(jelly.jelly(inputList))
        self.assertEqual(inputList, output)
        self.assertNotIdentical(inputList, output)

Example 17

Project: mythbox Source File: test_jelly.py
Function: test_set
    def test_set(self):
        """
        Check that a C{set} can contain a circular reference and be serialized
        and unserialized without losing the reference.
        """
        s = set()
        a = SimpleJellyTest(s, None)
        s.add(a)
        res = jelly.unjelly(jelly.jelly(a))
        self.assertIsInstance(res.x, set)
        self.assertEquals(list(res.x), [res])

Example 18

Project: SubliminalCollaborator Source File: runner.py
    def _uniqueTests(self, things):
        """
        Gather unique suite objects from loaded things. This will guarantee
        uniqueness of inherited methods on TestCases which would otherwise hash
        to same value and collapse to one test unexpectedly if using simpler
        means: e.g. set().
        """
        entries = []
        for thing in things:
            if isinstance(thing, types.MethodType):
                entries.append((thing, thing.im_class))
            else:
                entries.append((thing,))
        return [entry[0] for entry in set(entries)]

Example 19

Project: SubliminalCollaborator Source File: test_task.py
Function: test_getdelayedcalls
    def test_getDelayedCalls(self):
        """
        Test that we can get a list of all delayed calls
        """
        c = task.Clock()
        call = c.callLater(1, lambda x: None)
        call2 = c.callLater(2, lambda x: None)

        calls = c.getDelayedCalls()

        self.assertEqual(set([call, call2]), set(calls))

Example 20

Project: SubliminalCollaborator Source File: test_http_headers.py
Function: test_value_s
    def test_values(self, _method='values', _requireList=True):
        """
        L{_DictHeaders.values} will return a list of all present header values,
        returning only the last value for headers with more than one.
        """
        headers, wrapper = self.headers(foo=["lemur"], bar=["marmot", "panda"])
        values = getattr(wrapper, _method)()
        if _requireList:
            self.assertIsInstance(values, list)
        self.assertEqual(set(values), set(["lemur", "panda"]))

Example 21

Project: mythbox Source File: reporter.py
Function: init
    def __init__(self, stream=sys.stdout, tbformat='default', realtime=False,
                 publisher=None):
        super(Reporter, self).__init__()
        self._stream = SafeStream(stream)
        self.tbformat = tbformat
        self.realtime = realtime
        self._startTime = None
        self._warningCache = set()

        # Start observing log events so as to be able to report warnings.
        self._publisher = publisher
        if publisher is not None:
            publisher.addObserver(self._observeWarnings)

Example 22

Project: mythbox Source File: reporter.py
Function: start_test
    def startTest(self, test):
        """
        Called when a test begins to run. Records the time when it was first
        called and resets the warning cache.

        @param test: L{ITestCase}
        """
        super(Reporter, self).startTest(test)
        if self._startTime is None:
            self._startTime = self._getTime()
        self._warningCache = set()

Example 23

Project: mythbox Source File: test_task.py
Function: test_getdelayedcalls
    def test_getDelayedCalls(self):
        """
        Test that we can get a list of all delayed calls
        """
        c = task.Clock()
        call = c.callLater(1, lambda x: None)
        call2 = c.callLater(2, lambda x: None)

        calls = c.getDelayedCalls()

        self.assertEquals(set([call, call2]), set(calls))

Example 24

Project: mythbox Source File: test_tap.py
    def test_checkersWithoutPamAuth(self):
        """
        The L{OpenSSHFactory} built by L{tap.makeService} has a portal with
        L{ISSHPrivateKey} and L{IUsernamePassword} interfaces registered as
        checkers if C{pamauth} is not available.
        """
        # Fake the absence of pamauth, even if PyPAM is installed
        self.patch(tap, "pamauth", None)
        config = tap.Options()
        service = tap.makeService(config)
        portal = service.args[1].portal
        self.assertEquals(
            set(portal.checkers.keys()),
            set([ISSHPrivateKey, IUsernamePassword]))

Example 25

Project: mythbox Source File: test_openssh_compat.py
Function: test_get_private_keys
    def test_getPrivateKeys(self):
        """
        L{OpenSSHFactory.getPrivateKeys} should return the available private
        keys in the data directory.
        """
        keys = self.factory.getPrivateKeys()
        self.assertEquals(len(keys), 2)
        keyTypes = keys.keys()
        self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
        self.assertEquals(self.mockos.seteuidCalls, [])
        self.assertEquals(self.mockos.setegidCalls, [])

Example 26

Project: SubliminalCollaborator Source File: test_tap.py
    def test_checkersWithoutPamAuth(self):
        """
        The L{OpenSSHFactory} built by L{tap.makeService} has a portal with
        L{ISSHPrivateKey} and L{IUsernamePassword} interfaces registered as
        checkers if C{pamauth} is not available.
        """
        # Fake the absence of pamauth, even if PyPAM is installed
        self.patch(tap, "pamauth", None)
        config = tap.Options()
        service = tap.makeService(config)
        portal = service.factory.portal
        self.assertEqual(
            set(portal.checkers.keys()),
            set([ISSHPrivateKey, IUsernamePassword]))

Example 27

Project: SubliminalCollaborator Source File: test_openssh_compat.py
Function: test_get_private_keys
    def test_getPrivateKeys(self):
        """
        L{OpenSSHFactory.getPrivateKeys} should return the available private
        keys in the data directory.
        """
        keys = self.factory.getPrivateKeys()
        self.assertEqual(len(keys), 2)
        keyTypes = keys.keys()
        self.assertEqual(set(keyTypes), set(['ssh-rsa', 'ssh-dss']))
        self.assertEqual(self.mockos.seteuidCalls, [])
        self.assertEqual(self.mockos.setegidCalls, [])

Example 28

Project: mythbox Source File: test_jelly.py
Function: test_oldsets
    def test_oldSets(self):
        """
        Test jellying C{sets.Set}: it should serialize to the same thing as
        C{set} jelly, and be unjellied as C{set} if available.
        """
        inputList = [jelly._sets.Set([1, 2, 3])]
        inputJelly = jelly.jelly(inputList)
        self.assertEquals(inputJelly, jelly.jelly([set([1, 2, 3])]))
        output = jelly.unjelly(inputJelly)
        # Even if the class is different, it should coerce to the same list
        self.assertEquals(list(inputList[0]), list(output[0]))
        if set is jelly._sets.Set:
            self.assertIsInstance(output[0], jelly._sets.Set)
        else:
            self.assertIsInstance(output[0], set)

Example 29

Project: mythbox Source File: test_posixbase.py
    def test_removeAllReturnsRemovedDescriptors(self):
        """
        L{PosixReactorBase._removeAll} returns a list of removed
        L{IReadDescriptor} and L{IWriteDescriptor} objects.
        """
        reactor = TrivialReactor()
        reader = object()
        writer = object()
        reactor.addReader(reader)
        reactor.addWriter(writer)
        removed = reactor._removeAll(
            reactor._readers, reactor._writers)
        self.assertEqual(set(removed), set([reader, writer]))
        self.assertNotIn(reader, reactor._readers)
        self.assertNotIn(writer, reactor._writers)

Example 30

Project: SubliminalCollaborator Source File: test_zipstream.py
Function: test_unzipiterchunkydirectory
    def test_unzipIterChunkyDirectory(self):
        """
        The path to which a file is extracted by L{zipstream.unzipIterChunky}
        is determined by joining the C{directory} argument to C{unzip} with the
        path within the archive of the file being extracted.
        """
        numfiles = 10
        contents = ['This is test file %d!' % i for i in range(numfiles)]
        zpfilename = self.makeZipFile(contents, 'foo')
        list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))
        self.assertEqual(
            set(self.unzipdir.child('foo').listdir()),
            set(map(str, range(numfiles))))

        for child in self.unzipdir.child('foo').children():
            num = int(child.basename())
            self.assertEqual(child.getContent(), contents[num])

Example 31

Project: SubliminalCollaborator Source File: maildir.py
Function: sync
    def sync(self):
        """
        Discard the contents of any message marked for deletion and reset
        deletion tracking.
        """
        for index in self._delete:
            self.msgs[index] = ""
        self._delete = set()

Example 32

Project: mythbox Source File: test_paths.py
Function: test_walk
    def test_walk(self):
        """
        Verify that walking the path gives the same result as the known file
        hierarchy.
        """
        x = [foo.path for foo in self.path.walk()]
        self.assertEquals(set(x), set(self.all))

Example 33

Project: SubliminalCollaborator Source File: test_http_headers.py
Function: test_keys
    def test_keys(self, _method='keys', _requireList=True):
        """
        L{_DictHeaders.keys} will return a list of all present header names.
        """
        headers, wrapper = self.headers(test=["lemur"], foo=["bar"])
        keys = getattr(wrapper, _method)()
        if _requireList:
            self.assertIsInstance(keys, list)
        self.assertEqual(set(keys), set(["foo", "test"]))

Example 34

Project: mythbox Source File: test_zipstream.py
Function: test_unzipiterchunky
    def test_unzipIterChunky(self):
        """
        L{twisted.python.zipstream.unzipIterChunky} returns an iterator which
        must be exhausted to completely unzip the input archive.
        """
        numfiles = 10
        contents = ['This is test file %d!' % i for i in range(numfiles)]
        zpfilename = self.makeZipFile(contents)
        list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path))
        self.assertEquals(
            set(self.unzipdir.listdir()),
            set(map(str, range(numfiles))))

        for child in self.unzipdir.children():
            num = int(child.basename())
            self.assertEquals(child.getContent(), contents[num])

Example 35

Project: mythbox Source File: test_zipstream.py
    def test_unzipDirectory(self):
        """
        The path to which a file is extracted by L{zipstream.unzip} is
        determined by joining the C{directory} argument to C{unzip} with the
        path within the archive of the file being extracted.
        """
        numfiles = 3
        zpfilename = self.makeZipFile([str(i) for i in range(numfiles)], 'foo')
        zipstream.unzip(zpfilename, self.unzipdir.path)
        self.assertEqual(
            set(self.unzipdir.child('foo').listdir()),
            set(map(str, range(numfiles))))
        for i in range(numfiles):
            self.assertEqual(
                self.unzipdir.child('foo').child(str(i)).getContent(), str(i))

Example 36

Project: SubliminalCollaborator Source File: test_tap.py
    def test_checkersPamAuth(self):
        """
        The L{OpenSSHFactory} built by L{tap.makeService} has a portal with
        L{IPluggableAuthenticationModules}, L{ISSHPrivateKey} and
        L{IUsernamePassword} interfaces registered as checkers if C{pamauth} is
        available.
        """
        # Fake the presence of pamauth, even if PyPAM is not installed
        self.patch(tap, "pamauth", object())
        config = tap.Options()
        service = tap.makeService(config)
        portal = service.factory.portal
        self.assertEqual(
            set(portal.checkers.keys()),
            set([IPluggableAuthenticationModules, ISSHPrivateKey,
                 IUsernamePassword]))

Example 37

Project: mythbox Source File: trial.py
Function: init
    def __init__(self):
        self['tests'] = set()
        usage.Options.__init__(self)

Example 38

Project: SubliminalCollaborator Source File: _glibbase.py
    def __init__(self, glib_module, gtk_module, useGtk=False):
        self._simtag = None
        self._reads = set()
        self._writes = set()
        self._sources = {}
        self._glib = glib_module
        self._gtk = gtk_module
        posixbase.PosixReactorBase.__init__(self)

        self._source_remove = self._glib.source_remove
        self._timeout_add = self._glib.timeout_add

        def _mainquit():
            if self._gtk.main_level():
                self._gtk.main_quit()

        if useGtk:
            self._pending = self._gtk.events_pending
            self._iteration = self._gtk.main_iteration_do
            self._crash = _mainquit
            self._run = self._gtk.main
        else:
            self.context = self._glib.main_context_default()
            self._pending = self.context.pending
            self._iteration = self.context.iteration
            self.loop = self._glib.MainLoop()
            self._crash = lambda: self._glib.idle_add(self.loop.quit)
            self._run = self.loop.run

Example 39

Project: mythbox Source File: test_compat.py
Function: test_set
    def test_set(self):
        """
        L{set} should behave like the expected set interface.
        """
        a = set()
        a.add('b')
        a.add('c')
        a.add('a')
        b = list(a)
        b.sort()
        self.assertEquals(b, ['a', 'b', 'c'])
        a.remove('b')
        b = list(a)
        b.sort()
        self.assertEquals(b, ['a', 'c'])

        a.discard('d')

        b = set(['r', 's'])
        d = a.union(b)
        b = list(d)
        b.sort()
        self.assertEquals(b, ['a', 'c', 'r', 's'])

Example 40

Project: SubliminalCollaborator Source File: maildir.py
Function: init
    def __init__(self, msgs):
        self.msgs = msgs
        self._delete = set()

Example 41

Project: mythbox Source File: base.py
Function: init
    def __init__(self):
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        # reactor internal readers, e.g. the waker.
        self._internalReaders = set()
        self.waker = None

        # Arrange for the running attribute to change to True at the right time
        # and let a subclass possibly do other things at that time (eg install
        # signal handlers).
        self.addSystemEventTrigger(
            'during', 'startup', self._reallyStartRunning)
        self.addSystemEventTrigger('during', 'shutdown', self.crash)
        self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)

        if platform.supportsThreads():
            self._initThreads()
        self.installWaker()

Example 42

Project: mythbox Source File: test_process.py
    def test_processEnded(self):
        """
        L{IProcessProtocol.processEnded} is called after the child process
        exits and L{IProcessProtocol.childConnectionLost} is called for each of
        its file descriptors.
        """
        ended = Deferred()
        lost = []

        class Ender(ProcessProtocol):
            def childDataReceived(self, fd, data):
                msg('childDataReceived(%d, %r)' % (fd, data))
                self.transport.loseConnection()

            def childConnectionLost(self, childFD):
                msg('childConnectionLost(%d)' % (childFD,))
                lost.append(childFD)

            def processExited(self, reason):
                msg('processExited(%r)' % (reason,))

            def processEnded(self, reason):
                msg('processEnded(%r)' % (reason,))
                ended.callback([reason])

        reactor = self.buildReactor()
        reactor.callWhenRunning(
            reactor.spawnProcess, Ender(), sys.executable,
            [sys.executable, self.keepStdioOpenProgram, "child",
             self.keepStdioOpenArg],
            usePTY=self.usePTY)

        def cbEnded((failure,)):
            failure.trap(ProcessDone)
            self.assertEqual(set(lost), set([0, 1, 2]))

Example 43

Project: SubliminalCollaborator Source File: relaymanager.py
    def _cbMX(self, answers, domain, cnamesLeft):
        """
        Try to find the MX host from the given DNS information.

        This will attempt to resolve CNAME results.  It can recognize loops
        and will give up on non-cyclic chains after a specified number of
        lookups.
        """
        # Do this import here so that relaymanager.py doesn't depend on
        # twisted.names, only MXCalculator will.
        from twisted.names import dns, error

        seenAliases = set()
        exchanges = []
        # Examine the answers for the domain we asked about
        pertinentRecords = answers.get(domain, [])
        while pertinentRecords:
            record = pertinentRecords.pop()

            # If it's a CNAME, we'll need to do some more processing
            if record.TYPE == dns.CNAME:

                # Remember that this name was an alias.
                seenAliases.add(domain)

                canonicalName = str(record.name)
                # See if we have some local records which might be relevant.
                if canonicalName in answers:

                    # Make sure it isn't a loop contained entirely within the
                    # results we have here.
                    if canonicalName in seenAliases:
                        return Failure(CanonicalNameLoop(record))

                    pertinentRecords = answers[canonicalName]
                    exchanges = []
                else:
                    if cnamesLeft:
                        # Request more information from the server.
                        return self.getMX(canonicalName, cnamesLeft - 1)
                    else:
                        # Give up.
                        return Failure(CanonicalNameChainTooLong(record))

            # If it's an MX, collect it.
            if record.TYPE == dns.MX:
                exchanges.append((record.preference, record))

        if exchanges:
            exchanges.sort()
            for (preference, record) in exchanges:
                host = str(record.name)
                if host not in self.badMXs:
                    return record
                t = self.clock.seconds() - self.badMXs[host]
                if t >= 0:
                    del self.badMXs[host]
                    return record
            return exchanges[0][1]
        else:
            # Treat no answers the same as an error - jump to the errback to try
            # to look up an A record.  This provides behavior described as a
            # special case in RFC 974 in the section headed I{Interpreting the
            # List of MX RRs}.
            return Failure(
                error.DNSNameError("No MX records for %r" % (domain,)))

Example 44

Project: mythbox Source File: test_process.py
        def cbAllLost(ignored):
            self.assertEqual(set(lost), set([0, 1, 2]))

Example 45

Project: mythbox Source File: gtk2reactor.py
    def __init__(self, useGtk=True):
        self._simtag = None
        self._reads = set()
        self._writes = set()
        self._sources = {}
        posixbase.PosixReactorBase.__init__(self)
        # pre 2.3.91 the glib iteration and mainloop functions didn't release
        # global interpreter lock, thus breaking thread and signal support.
        if getattr(gobject, "pygtk_version", ()) >= (2, 3, 91) and not useGtk:
            self.context = gobject.main_context_default()
            self.__pending = self.context.pending
            self.__iteration = self.context.iteration
            self.loop = gobject.MainLoop()
            self.__crash = self.loop.quit
            self.__run = self.loop.run
        else:
            import gtk
            self.__pending = gtk.events_pending
            self.__iteration = gtk.main_iteration
            self.__crash = _our_mainquit
            self.__run = gtk.main

Example 46

Project: mythbox Source File: test_fakepwd.py
Function: set_up
    def setUp(self):
        self.database = pwd
        self._users = iter(self.database.getpwall())
        self._uids = set()

Example 47

Project: mythbox Source File: reactor.py
Function: init
    def __init__(self):
        base.ReactorBase.__init__(self)
        self.port = _iocp.CompletionPort()
        self.handles = set()

Example 48

Project: mythbox Source File: posixbase.py
Function: remove_all
    def _removeAll(self, readers, writers):
        """
        Remove all readers and writers, and list of removed L{IReadDescriptor}s
        and L{IWriteDescriptor}s.

        Meant for calling from subclasses, to implement removeAll, like::

          def removeAll(self):
              return self._removeAll(self._reads, self._writes)

        where C{self._reads} and C{self._writes} are iterables.
        """
        removedReaders = set(readers) - self._internalReaders
        for reader in removedReaders:
            self.removeReader(reader)

        removedWriters = set(writers)
        for writer in removedWriters:
            self.removeWriter(writer)

        return list(removedReaders | removedWriters)

Example 49

Project: mythbox Source File: test_script.py
Function: test_gettestmodules_multiple
    def test_getTestModules_multiple(self):
        modules = trial.getTestModules(sibpath('scripttest.py'))
        self.failUnlessEqual(set(modules),
                             set(['twisted.trial.test.test_test_visitor',
                                  'twisted.trial.test.test_class']))

Example 50

Project: TwistedBot Source File: base.py
Function: init
    def __init__(self):
        self.threadCallQueue = []
        self._eventTriggers = {}
        self._pendingTimedCalls = []
        self._newTimedCalls = []
        self._cancellations = 0
        self.running = False
        self._started = False
        self._justStopped = False
        self._startedBefore = False
        # reactor internal readers, e.g. the waker.
        self._internalReaders = set()
        self.waker = None

        # Arrange for the running attribute to change to True at the right time
        # and let a subclass possibly do other things at that time (eg install
        # signal handlers).
        self.addSystemEventTrigger(
            'during', 'startup', self._reallyStartRunning)
        self.addSystemEventTrigger('during', 'shutdown', self.crash)
        self.addSystemEventTrigger('during', 'shutdown', self.disconnectAll)

        if platform.supportsThreads():
            self._initThreads()
        self.installWaker()
See More Examples - Go to Next Page
Page 1 Selected Page 2