Python twisted.internet.defer.waitForDeferred() Examples

The following are 30 code examples of twisted.internet.defer.waitForDeferred(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.defer , or try the search function .
Example #1
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_nickServLogin(self):
        """
        Sending NICK without PASS will prompt the user for their password.
        When the user sends their password to NickServ, it will respond with a
        Greeting.
        """
        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
        yield firstuser
        firstuser = firstuser.getResult()

        user = TestCaseUserAgg(firstuser, self.realm, self.factory)
        user.write('NICK firstuser extrainfo\r\n')
        response = self._response(user, 'PRIVMSG')
        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][0], service.NICKSERV)
        self.assertEquals(response[0][1], 'PRIVMSG')
        self.assertEquals(response[0][2], ['firstuser', 'Password?'])
        user.transport.clear()

        user.write('PRIVMSG nickserv firstuser_password\r\n')
        self._assertGreeting(user) 
Example #2
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testNickServLogin(self):
        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
        yield firstuser
        firstuser = firstuser.getResult()

        user = TestCaseUserAgg(firstuser, self.realm, self.factory)
        user.write('NICK firstuser extrainfo\r\n')
        response = self._response(user)
        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][0], service.NICKSERV)
        self.assertEquals(response[0][1], 'PRIVMSG')
        self.assertEquals(response[0][2], ['firstuser', 'Password?'])
        user.transport.clear()

        user.write('PRIVMSG nickserv firstuser_password\r\n')
        self._assertGreeting(user) 
Example #3
Source File: test_defgen.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _genBasics(self):

        x = waitForDeferred(getThing())
        yield x
        x = x.getResult()

        self.assertEqual(x, "hi")

        ow = waitForDeferred(getOwie())
        yield ow
        try:
            ow.getResult()
        except ZeroDivisionError as e:
            self.assertEqual(str(e), 'OMG')
        yield "WOOSH"
        return 
Example #4
Source File: stream.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def _readUntil(self, f):
        """Internal helper function which repeatedly calls f each time
        after more data has been received, until it returns non-None."""
        while True:
            r = f()
            if r is not None:
                yield r
                return

            newdata = self.stream.read()
            if isinstance(newdata, defer.Deferred):
                newdata = defer.waitForDeferred(newdata)
                yield newdata
                newdata = newdata.getResult()

            if newdata is None:
                # End Of File
                newdata = self.data
                self.data = ''
                yield newdata
                return
            self.data += str(newdata) 
Example #5
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testUserRetrieval(self):
        realm = service.InMemoryWordsRealm("realmname")

        # Make a user to play around with
        d = wFD(realm.createUser(u"testuser"))
        yield d
        user = d.getResult()

        # Make sure getting the user returns the same object
        d = wFD(realm.getUser(u"testuser"))
        yield d
        retrieved = d.getResult()
        self.assertIdentical(user, retrieved)

        # Make sure looking up the user also returns the same object
        d = wFD(realm.lookupUser(u"testuser"))
        yield d
        lookedUp = d.getResult()
        self.assertIdentical(retrieved, lookedUp)

        # Make sure looking up a user who does not exist fails
        d = wFD(realm.lookupUser(u"nosuchuser"))
        yield d
        self.assertRaises(ewords.NoSuchUser, d.getResult) 
Example #6
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testUserAddition(self):
        realm = service.InMemoryWordsRealm("realmname")

        # Create and manually add a user to the realm
        p = service.User("testuser")
        d = wFD(realm.addUser(p))
        yield d
        user = d.getResult()
        self.assertIdentical(p, user)

        # Make sure getting that user returns the same object
        d = wFD(realm.getUser(u"testuser"))
        yield d
        retrieved = d.getResult()
        self.assertIdentical(user, retrieved)

        # Make sure looking up that user returns the same object
        d = wFD(realm.lookupUser(u"testuser"))
        yield d
        lookedUp = d.getResult()
        self.assertIdentical(retrieved, lookedUp) 
Example #7
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testGroupRetrieval(self):
        realm = service.InMemoryWordsRealm("realmname")

        d = wFD(realm.createGroup(u"testgroup"))
        yield d
        group = d.getResult()

        d = wFD(realm.getGroup(u"testgroup"))
        yield d
        retrieved = d.getResult()

        self.assertIdentical(group, retrieved)

        d = wFD(realm.getGroup(u"nosuchgroup"))
        yield d
        self.assertRaises(ewords.NoSuchGroup, d.getResult) 
Example #8
Source File: test_defgen.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _genBasics(self):

        x = waitForDeferred(getThing())
        yield x
        x = x.getResult()

        self.assertEqual(x, "hi")

        ow = waitForDeferred(getOwie())
        yield ow
        try:
            ow.getResult()
        except ZeroDivisionError as e:
            self.assertEqual(str(e), 'OMG')
        yield "WOOSH"
        return 
Example #9
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def testEnumeration(self):
        realm = service.InMemoryWordsRealm("realmname")
        d = wFD(realm.createGroup(u"groupone"))
        yield d
        d.getResult()

        d = wFD(realm.createGroup(u"grouptwo"))
        yield d
        d.getResult()

        groups = wFD(realm.itergroups())
        yield groups
        groups = groups.getResult()

        n = [g.name for g in groups]
        n.sort()
        self.assertEquals(n, ["groupone", "grouptwo"]) 
Example #10
Source File: fileupload.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def _readBoundaryLine(self):
        # print("_readBoundaryLine")
        line = self.stream.readline(size=1024)
        if isinstance(line, defer.Deferred):
            line = defer.waitForDeferred(line)
            yield line
            line = line.getResult()

        if line == "--\r\n":
            # THE END!
            yield False
            return
        elif line != "\r\n":
            raise MimeFormatError("Unexpected data on same line as boundary: %r" % (line,))
        yield True
        return 
Example #11
Source File: test_ftp.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testPASV(self):
        # Login
        wfd = defer.waitForDeferred(self._anonymousLogin())
        yield wfd
        wfd.getResult()

        # Issue a PASV command, and extract the host and port from the response
        pasvCmd = defer.waitForDeferred(self.client.queueStringCommand('PASV'))
        yield pasvCmd
        responseLines = pasvCmd.getResult()
        host, port = ftp.decodeHostPort(responseLines[-1][4:])

        # Make sure the server is listening on the port it claims to be
        self.assertEqual(port, self.serverProtocol.dtpPort.getHost().port)

        # Semi-reasonable way to force cleanup
        self.serverProtocol.transport.loseConnection() 
Example #12
Source File: delete.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def http_DELETE(self, request):
    """
    Respond to a DELETE request. (RFC 2518, section 8.6)
    """
    if not self.exists():
        log.error("File not found: %s" % (self,))
        raise HTTPError(responsecode.NOT_FOUND)

    depth = request.headers.getHeader("depth", "infinity")

    #
    # Check authentication and access controls
    #
    parent = waitForDeferred(request.locateResource(parentForURL(request.uri)))
    yield parent
    parent = parent.getResult()

    x = waitForDeferred(parent.authorize(request, (davxml.Unbind(),)))
    yield x
    x.getResult()

    x = waitForDeferred(deleteResource(request, self, request.uri, depth))
    yield x
    yield x.getResult() 
Example #13
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testGetGroupMode(self):
        user = wFD(self._loggedInUser(u'useruser'))
        yield user
        user = user.getResult()

        add = wFD(self.realm.createGroup(u"somechannel"))
        yield add
        somechannel = add.getResult()

        user.write('JOIN #somechannel\r\n')

        user.transport.clear()
        user.write('MODE #somechannel\r\n')

        response = self._response(user)
        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][1], '324') 
Example #14
Source File: test_fileupload.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def doTest(self, boundary, data, expected_args, expected_files):
        # import time, gc, cgi, cStringIO
        for bytes in range(1, 20):
            # s = TestStream(data, maxReturn=bytes)
            s = stream.IStream(data)
            # t=time.time()
            d = waitForDeferred(fileupload.parseMultipartFormData(s, boundary))
            yield d
            args, files = d.getResult()
            # e=time.time()
            # print "%.2g"%(e-t)
            self.assertEquals(args, expected_args)

            # Read file data back into memory to compare.
            out = {}
            for name, l in files.items():
                out[name] = [(filename, ctype, f.read()) for (filename, ctype, f) in l]
            self.assertEquals(out, expected_files)

        # data=cStringIO.StringIO(data)
        # t=time.time()
        # d=cgi.parse_multipart(data, {'boundary':boundary})
        # e=time.time()
        # print "CGI: %.2g"%(e-t) 
Example #15
Source File: deferredruntest.py    From pth-toolkit with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _run_cleanups(self):
        """Run the cleanups on the test case.

        We expect that the cleanups on the test case can also return
        asynchronous Deferreds.  As such, we take the responsibility for
        running the cleanups, rather than letting TestCase do it.
        """
        while self.case._cleanups:
            f, args, kwargs = self.case._cleanups.pop()
            d = defer.maybeDeferred(f, *args, **kwargs)
            thing = defer.waitForDeferred(d)
            yield thing
            try:
                thing.getResult()
            except Exception:
                exc_info = sys.exc_info()
                self.case._report_traceback(exc_info)
                last_exception = exc_info[1]
        yield last_exception 
Example #16
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testUserRetrieval(self):
        realm = service.InMemoryWordsRealm("realmname")

        # Make a user to play around with
        d = wFD(realm.createUser(u"testuser"))
        yield d
        user = d.getResult()

        # Make sure getting the user returns the same object
        d = wFD(realm.getUser(u"testuser"))
        yield d
        retrieved = d.getResult()
        self.assertIdentical(user, retrieved)

        # Make sure looking up the user also returns the same object
        d = wFD(realm.lookupUser(u"testuser"))
        yield d
        lookedUp = d.getResult()
        self.assertIdentical(retrieved, lookedUp)

        # Make sure looking up a user who does not exist fails
        d = wFD(realm.lookupUser(u"nosuchuser"))
        yield d
        self.assertRaises(ewords.NoSuchUser, d.getResult) 
Example #17
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testUserAddition(self):
        realm = service.InMemoryWordsRealm("realmname")

        # Create and manually add a user to the realm
        p = service.User("testuser")
        d = wFD(realm.addUser(p))
        yield d
        user = d.getResult()
        self.assertIdentical(p, user)

        # Make sure getting that user returns the same object
        d = wFD(realm.getUser(u"testuser"))
        yield d
        retrieved = d.getResult()
        self.assertIdentical(user, retrieved)

        # Make sure looking up that user returns the same object
        d = wFD(realm.lookupUser(u"testuser"))
        yield d
        lookedUp = d.getResult()
        self.assertIdentical(retrieved, lookedUp) 
Example #18
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testGroupRetrieval(self):
        realm = service.InMemoryWordsRealm("realmname")

        d = wFD(realm.createGroup(u"testgroup"))
        yield d
        group = d.getResult()

        d = wFD(realm.getGroup(u"testgroup"))
        yield d
        retrieved = d.getResult()

        self.assertIdentical(group, retrieved)

        d = wFD(realm.getGroup(u"nosuchgroup"))
        yield d
        self.assertRaises(ewords.NoSuchGroup, d.getResult) 
Example #19
Source File: proppatch.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def http_PROPPATCH(self, request):
    """
    Respond to a PROPPATCH request. (RFC 2518, section 8.2)
    """
    if not self.exists():
        log.error("File not found: %s" % (self,))
        raise HTTPError(responsecode.NOT_FOUND)

    x = waitForDeferred(self.authorize(request, (davxml.WriteProperties(),)))
    yield x
    x.getResult()

    #
    # Read request body
    #
    try:
        doc = waitForDeferred(davXMLFromStream(request.stream))
        yield doc
        doc = doc.getResult()
    except ValueError, e:
        log.error("Error while handling PROPPATCH body: %s" % (e,))
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e))) 
Example #20
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_joinTopicless(self):
        """
        When a user joins a group without a topic, no topic information is
        sent to that user.
        """
        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
        yield firstuser
        firstuser = firstuser.getResult()

        somechannel = wFD(self.realm.createGroup(u"somechannel"))
        yield somechannel
        somechannel = somechannel.getResult()

        # Bring in one user, make sure he gets into the channel sanely
        user = TestCaseUserAgg(firstuser, self.realm, self.factory)
        self._login(user, "firstuser")
        user.transport.clear()
        user.write('JOIN #somechannel\r\n')

        response = self._response(user)
        responseCodes = [r[1] for r in response]
        self.assertNotIn('332', responseCodes)
        self.assertNotIn('333', responseCodes) 
Example #21
Source File: test_service.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testEnumeration(self):
        realm = service.InMemoryWordsRealm("realmname")
        d = wFD(realm.createGroup(u"groupone"))
        yield d
        d.getResult()

        d = wFD(realm.createGroup(u"grouptwo"))
        yield d
        d.getResult()

        groups = wFD(realm.itergroups())
        yield groups
        groups = groups.getResult()

        n = [g.name for g in groups]
        n.sort()
        self.assertEquals(n, ["groupone", "grouptwo"]) 
Example #22
Source File: report.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def http_REPORT(self, request):
    """
    Respond to a REPORT request. (RFC 3253, section 3.6)
    """
    if not self.exists():
        log.error("File not found: %s" % (self,))
        raise HTTPError(responsecode.NOT_FOUND)

    #
    # Check authentication and access controls
    #
    x = waitForDeferred(self.authorize(request, (davxml.Read(),)))
    yield x
    x.getResult()

    #
    # Read request body
    #
    try:
        doc = waitForDeferred(davXMLFromStream(request.stream))
        yield doc
        doc = doc.getResult()
    except ValueError, e:
        log.error("Error while handling REPORT body: %s" % (e,))
        raise HTTPError(StatusResponse(responsecode.BAD_REQUEST, str(e))) 
Example #23
Source File: test_service.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testFailedLogin(self):
        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
        yield firstuser
        firstuser = firstuser.getResult()

        user = TestCaseUserAgg(firstuser, self.realm, self.factory)
        self._login(user, "firstuser", "wrongpass")
        response = self._response(user, "PRIVMSG")
        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][2], ['firstuser', 'Login failed.  Goodbye.']) 
Example #24
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def _loggedInUser(self, name):
        d = wFD(self.realm.lookupUser(name))
        yield d
        user = d.getResult()
        agg = TestCaseUserAgg(user, self.realm, self.factory)
        self._login(agg, name)
        yield agg 
Example #25
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testPASSLogin(self):
        user = wFD(self._loggedInUser(u'firstuser'))
        yield user
        user = user.getResult()
        self._assertGreeting(user) 
Example #26
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testFailedLogin(self):
        firstuser = wFD(self.realm.lookupUser(u'firstuser'))
        yield firstuser
        firstuser = firstuser.getResult()

        user = TestCaseUserAgg(firstuser, self.realm, self.factory)
        self._login(user, "firstuser", "wrongpass")
        response = self._response(user)
        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][2], ['firstuser', 'Login failed.  Goodbye.']) 
Example #27
Source File: test_service.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testPrivateMessage(self):
        user = wFD(self._loggedInUser(u'useruser'))
        yield user
        user = user.getResult()

        other = wFD(self._loggedInUser(u'otheruser'))
        yield other
        other = other.getResult()

        user.transport.clear()
        other.transport.clear()

        user.write('PRIVMSG otheruser :Hello, monkey.\r\n')

        response = self._response(user)
        event = self._response(other)

        self.failIf(response)
        self.assertEquals(len(event), 1)
        self.assertEquals(event[0][0], 'useruser!useruser@realmname')
        self.assertEquals(event[0][1], 'PRIVMSG')
        self.assertEquals(event[0][2], ['otheruser', 'Hello, monkey.'])

        user.write('PRIVMSG nousernamedthis :Hello, monkey.\r\n')

        response = self._response(user)

        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][0], 'realmname')
        self.assertEquals(response[0][1], '401')
        self.assertEquals(response[0][2], ['useruser', 'nousernamedthis', 'No such nick/channel.']) 
Example #28
Source File: test_service.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def testOper(self):
        user = wFD(self._loggedInUser(u'useruser'))
        yield user
        user = user.getResult()

        user.transport.clear()
        user.write('OPER user pass\r\n')
        response = self._response(user)

        self.assertEquals(len(response), 1)
        self.assertEquals(response[0][1], '491') 
Example #29
Source File: test_defgen.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _genStackUsage(self):
        for x in range(5000):
            # Test with yielding a deferred
            x = waitForDeferred(defer.succeed(1))
            yield x
            x = x.getResult()
        yield 0 
Example #30
Source File: test_service.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testGroupAddition(self):
        realm = service.InMemoryWordsRealm("realmname")

        p = service.Group("testgroup")
        d = wFD(realm.addGroup(p))
        yield d
        d.getResult()

        d = wFD(realm.getGroup(u"testGroup"))
        yield d
        group = d.getResult()

        self.assertIdentical(p, group)