Esempio n. 1
0
 def testCertifiedRemoteCall(self):
     d = self._callRemote('authenticate', 'adim', 'adim')
     cnxId, _ = unittest.deferredResult(d)
     retValue = self._callRemote('lastIndexationTimeAndState', cnxId,
                                 'foo.pdf')
     self.assertEquals(unittest.deferredResult(retValue),
                       [0, Document.UNKNOWN_STATE])
Esempio n. 2
0
 def testRebind(self):
     server = Server()
     p = reactor.listenUDP(0, server, interface="127.0.0.1")
     reactor.iterate()
     unittest.deferredResult(defer.maybeDeferred(p.stopListening))
     p = reactor.listenUDP(0, server, interface="127.0.0.1")
     reactor.iterate()
     unittest.deferredResult(defer.maybeDeferred(p.stopListening))
 def test_check_connection(self):
     """command check"""
     deferred = self.factory.check("check")
     self.assertEquals(unittest.deferredResult(deferred),
                       """False""")
     self.factory.write("connect")
     self.factory.write("bots.netofpeers.net:8555")
     self._wait_for("Connected")
     deferred = self.factory.check("check")
     self.assertEquals(unittest.deferredResult(deferred),
                       """True""")
 def test_disconnect(self):
     """command disconnect"""
     deferred = self.factory.check("disconnect")
     self.assertEquals(unittest.deferredResult(deferred),
                       """not connected""")
     self.factory.write("connect")
     self.factory.write("bots.netofpeers.net:8555")
     self._wait_for("Connected")
     deferred = self.factory.check("disconnect")
     self.assertEquals(unittest.deferredResult(deferred),
                       """Not connected""")
 def test_jump(self):
     """command jump"""
     deferred = self.factory.check("jump")
     self.assertEquals(unittest.deferredResult(deferred),
                       """[192.33.178.29:5010]""")
     deferred = self.factory.check("")
     self.assertEquals(unittest.deferredResult(deferred),
                       """not connected""")
     self.factory.write("connect")
     self.factory.write("bots.netofpeers.net:8555")
     self._wait_for("Connected")
     self.factory.check("jump")
     self.assertEquals(unittest.deferredResult(deferred),
                       """192.33.178.29:5010""")
Esempio n. 6
0
    def test_simple(self):

        doc = div[p['foo'],p['bar']]
        result = unittest.deferredResult(
            rend.Page(docFactory=loaders.stan(doc)).renderString()
            )
        self.assertEquals(result, '<div><p>foo</p><p>bar</p></div>')
Esempio n. 7
0
 def testRequestAvatarId(self):
     db = checkers.PluggableAuthenticationModulesChecker()
     conv = self._makeConv({1:'password', 2:'entry', 3:''})
     creds = credentials.PluggableAuthenticationModules('testuser',
             conv)
     d = db.requestAvatarId(creds)
     self.assertEquals(unittest.deferredResult(d), 'testuser')
Esempio n. 8
0
 def testRawAuthentication(self):
     for user, passwd in [('adim', 'adim'), ('foo', 'bar')]:
         digest = self._callRemote('authenticate', user, passwd)
         expected = rpc.make_uid(user, passwd)
         got, _ = unittest.deferredResult(digest)
         self.assertEquals(got, expected, ('%s != %s (%s)' % (got, expected, _)))
         self.assertEquals(_, '')
 def test_go(self):
     """command go"""
     deferred = self.factory.write("go")
     deferred = self.factory.check("")
     self.assertEquals(unittest.deferredResult(deferred),
                       """2 parameters instead of 2, using default\nnot connected\n""")
     self.factory.write("connect")
     self.factory.write("bots.netofpeers.net:8555")
     self._wait_for("Connected")
     self.factory.write("go")
     deferred = self.factory.check("")
     self.assertEquals(unittest.deferredResult(deferred),
                       """2 parameters instead of 2, using default\nmoved to 0.0,0.0\n""")
     self.factory.write("go")
     deferred = self.factory.check("0.25,0.43")
     self.assertEquals(unittest.deferredResult(deferred),
                       """moved to 0.25,0.43\n""")
    def test_about(self):
        """command about"""
        deferred = self.factory.check("about")
        self.assertEquals(unittest.deferredResult(deferred),
                          """Solipsis Navigator 0.1.1

Licensed under the GNU LGPL
(c) France Telecom R&D""")
Esempio n. 11
0
 def testDeferredWrapper(self):
     from twisted.internet import defer
     from twisted.internet import reactor 
     a = defer.Deferred()
     reactor.callLater(0, lambda: a.callback("test"))
     b = flow.Merge(a, slowlist([1,2,flow.Cooperate(),3]))
     rhs = unittest.deferredResult(flow.Deferred(b))
     self.assertEquals(rhs, [1, 2, 'test', 3])
Esempio n. 12
0
 def testCallback(self):
     cb = flow.Callback()
     d = flow.Deferred(buildlist(cb))
     for x in range(9):
         cb.result(x)
     cb.finish()
     rhs = unittest.deferredResult(d)
     self.assertEquals([range(9)],rhs)
Esempio n. 13
0
 def testAnonymousAuthenticationFailure(self):
     """when portal.anonymousQuerier is None, anonymous login is not allowed"""
     self.portal.anonymousQuerier = None
     digest = self._callRemote('authenticate', '', '')
     got, err = unittest.deferredResult(digest)
     self.assertEquals(got, '')
     # XXX: need a better check
     self.assertNotEquals(err, '')
Esempio n. 14
0
 def testAnonymousAuthenticationFailure(self):
     """when portal.anonymousQuerier is None, anonymous login is not allowed"""
     self.portal.anonymousQuerier = None
     digest = self._callRemote('authenticate', '', '')
     got, err = unittest.deferredResult(digest)
     self.assertEquals(got, '')
     # XXX: need a better check
     self.assertNotEquals(err, '')
Esempio n. 15
0
 def testRawAuthentication(self):
     for user, passwd in [('adim', 'adim'), ('foo', 'bar')]:
         digest = self._callRemote('authenticate', user, passwd)
         expected = rpc.make_uid(user, passwd)
         got, _ = unittest.deferredResult(digest)
         self.assertEquals(got, expected,
                           ('%s != %s (%s)' % (got, expected, _)))
         self.assertEquals(_, '')
Esempio n. 16
0
 def testProtocol(self):
     from twisted.protocols import loopback
     server = flow.Protocol()
     server.controller = echoServer
     client = flow.makeProtocol(echoClient)()
     client.factory = protocol.ClientFactory()
     client.factory.d = defer.Deferred()
     loopback.loopback(server, client)
     self.assertEquals('testing', unittest.deferredResult(client.factory.d))
Esempio n. 17
0
    def testRequestAvatarId(self):
        dbfile = self.mktemp()
        db = checkers.FilePasswordDB(dbfile, caseSensitive=0)
        f = file(dbfile, 'w')
        for (u, p) in self.users:
            f.write('%s:%s\n' % (u, p))
        f.close()

        for (u, p) in self.users:
            c = credentials.UsernamePassword(u, p)
            d = defer.maybeDeferred(db.requestAvatarId, c)
            self.assertEquals(unittest.deferredResult(d), u)

        for (u, p) in self.users:
            self.assertEquals(
                unittest.deferredResult(db.requestAvatarId(
                    credentials.UsernameHashedPassword(u, p))),
                u
            )
 def test_not_valid(self):
     """command not valid"""
     # assert using 'deferredResult'
     deferred = self.factory.check("dummy")
     self.assertEquals(unittest.deferredResult(deferred),
                       """do_dummy not a valid command""")
     # assert using custom callback
     deferred = self.factory.check("")
     deferred.addCallback(self._assert_not_valid)
     while not self.done:
         reactor.iterate(0.1)
Esempio n. 19
0
 def testProtocolLocalhost(self):
     PORT = 8392
     server = protocol.ServerFactory()
     server.protocol = flow.Protocol
     server.protocol.controller = echoServer
     reactor.listenTCP(PORT,server)
     client = protocol.ClientFactory()
     client.protocol = flow.makeProtocol(echoClient)
     client.d = defer.Deferred()
     reactor.connectTCP("localhost", PORT, client)
     self.assertEquals('testing', unittest.deferredResult(client.d))
Esempio n. 20
0
def deferredRender(res, req):
    d = util.maybeDeferred(res.renderHTTP,
        context.PageContext(
            tag=res, parent=context.RequestContext(
                tag=req)))
    def done(result):
        if isinstance(result, str):
            req.write(result)
        req.d.callback(req)
        return result
    d.addCallback(done)
    return unittest.deferredResult(req.d, 1)
Esempio n. 21
0
def deferredRender(res):
    defres = req()
    d = util.maybeDeferred(res.renderHTTP,
        context.PageContext(
            tag=res, parent=context.RequestContext(
                tag=defres)))
    def done(result):
        if isinstance(result, str):
            defres.write(result)
        defres.d.callback(defres.accumulator)
        return result
    d.addCallback(done)
    return unittest.deferredResult(defres.d, 1)
 def test_display(self):
     """command display"""
     deferred = self.factory.check("display")
     self.assertEquals(unittest.deferredResult(deferred),
                       """not connected""")
     self.factory.write("connect")
     self.factory.write("bots.netofpeers.net:8555")
     self._wait_for("Connected")
     # not using deferredResult here since it swallows timeout
     deferred = self.factory.check("display")
     deferred.addCallback(self._assert_display)
     while not self.done:
         reactor.iterate(0.1)
Esempio n. 23
0
def deferredRender(res, req):
    d = util.maybeDeferred(res.renderHTTP,
        context.PageContext(
            tag=res, parent=context.RequestContext(
                tag=req)))

    def done(result):
        if isinstance(result, str):
            req.write(result)
        req.d.callback(req)
        return result
    d.addCallback(done)
    return unittest.deferredResult(req.d, 1)
    def test_help(self):
        """command help"""
        deferred = self.factory.check("help")
        self.assertEquals(unittest.deferredResult(deferred),
                          """[all]""")
        deferred = self.factory.check("")
        self.assertEquals(unittest.deferredResult(deferred),
                          """{'about': ['display general information', ''],
 'check': ['chech status of connection', ''],
 'connect': ['connect to specified node', 'bots.netofpeers.net:8551'],
 'create': ['create Node', 'Guest'],
 'disconnect': ['discoonnect from current node', ''],
 'display': ['display current address', ''],
 'go': ['go to position', '0,0'],
 'help': ['display help [on cmd]', 'all'],
 'hover': ['emumate hover on peer', '0,0'],
 'jump': ['jump to node', '192.33.178.29:5010'],
 'kill': ['kill node', ''],
 'mem': ['dump a snapshot of memory (debugging tool)', ''],
 'menu': ['display peer menu', ''],
 'pref': ['change preferences', ''],
 'quit': ['close navigator', '']}\n""")
Esempio n. 25
0
    def test_remembers(self):
        class Page(rend.Page):
            docFactory = loaders.stan(html[body[p(data=directive('foo'),
                                                  render=directive('bar'))]])

            def data_foo(self, ctx, data):
                return 'foo'

            def render_bar(self, ctx, data):
                return ctx.tag.clear()[data + 'bar']

        result = unittest.deferredResult(Page().renderString())
        self.assertEquals(result, '<html><body><p>foobar</p></body></html>')
Esempio n. 26
0
 def _disabled_testThreaded(self):
     from time import sleep
     #self.fail("This test freezes and consumes 100% CPU.")
     class CountIterator:
         def __init__(self, count):
             self.count = count
         def __iter__(self):
             return self
         def next(self): # this is run in a separate thread
             sleep(.1)
             val = self.count
             if not(val):
                 raise StopIteration
             self.count -= 1
             return val
     result = [7,6,5,4,3,2,1]
     d = flow.Deferred(flow.Threaded(CountIterator(7)))
     self.assertEquals(result, unittest.deferredResult(d))
     d = flow.Deferred(flow.Threaded(CountIterator(7)))
     sleep(2)
     self.assertEquals(result, unittest.deferredResult(d))
     d = flow.Deferred(flow.Threaded(CountIterator(7)))
     sleep(.3)
     self.assertEquals(result, unittest.deferredResult(d))
Esempio n. 27
0
 def test_remembers(self):
     class Page(rend.Page):
         docFactory = loaders.stan(
             html[
                 body[
                     p(data=directive('foo'), render=directive('bar'))
                     ]
                 ]
             )
         def data_foo(self, ctx, data):
             return 'foo'
         def render_bar(self, ctx, data):
             return ctx.tag.clear()[data+'bar']
     result = unittest.deferredResult(Page().renderString())
     self.assertEquals(result, '<html><body><p>foobar</p></body></html>')
Esempio n. 28
0
 def testRegister(self):
     self.register()
     dest, m = self.sent[0]
     self.assertEquals((dest.host, dest.port), ("client.com", 5060))
     self.assertEquals(m.code, 200)
     self.assertEquals(m.headers["via"], ["SIP/2.0/UDP client.com:5060"])
     self.assertEquals(m.headers["to"], ["sip:[email protected]"])
     self.assertEquals(m.headers["contact"], ["sip:[email protected]:5060"])
     self.failUnless(int(m.headers["expires"][0]) in (3600, 3601, 3599, 3598))
     self.assertEquals(len(self.registry.users), 1)
     dc, uri = self.registry.users["joe"]
     self.assertEquals(uri.toString(), "sip:[email protected]:5060")
     desturl = unittest.deferredResult(
         self.proxy.locator.getAddress(sip.URL(username="******", host="bell.example.com")))
     self.assertEquals((desturl.host, desturl.port), ("client.com", 5060))
Esempio n. 29
0
def deferredRender(res):
    defres = req()
    d = util.maybeDeferred(
        res.renderHTTP,
        context.PageContext(tag=res,
                            parent=context.RequestContext(tag=defres)))

    def done(result):
        if isinstance(result, str):
            defres.write(result)
        defres.d.callback(defres.accumulator)
        return result

    d.addCallback(done)
    return unittest.deferredResult(defres.d, 1)
Esempio n. 30
0
 def testConcurrentCallback(self):
     ca = flow.Callback()
     ca.name = 'a'
     cb = flow.Callback()
     cb.name = 'b'
     d = flow.Deferred(testconcur(ca,cb))
     ca.result(1)
     cb.result(2)
     ca.result(3)
     ca.result(4)
     ca.finish()
     cb.result(5)
     cb.finish()
     rhs = unittest.deferredResult(d)
     self.assertEquals([('a',1),('b',2),('a',3),('a',4),('b',5)],rhs)
Esempio n. 31
0
    def testHashedPasswords(self):
        def hash(u, p, s):
            return crypt(p, s)

        dbfile = self.mktemp()
        db = checkers.FilePasswordDB(dbfile, hash=hash)
        f = file(dbfile, 'w')
        for (u, p) in self.users:
            f.write('%s:%s\n' % (u, crypt(p, u[:2])))
        f.close()

        r = TestRealm()
        port = portal.Portal(r)
        port.registerChecker(db)

        for (u, p) in self.users:
            c = credentials.UsernamePassword(u, p)

            d = defer.maybeDeferred(db.requestAvatarId, c)
            self.assertEquals(unittest.deferredResult(d), u)

            d = port.login(c, None, ITestable)
            i, a, l = unittest.deferredResult(d)
            self.assertEquals(a.original.name, u)

            # It should fail if we pass the wrong password
            c = credentials.UsernamePassword(u, 'wrong password')
            d = port.login(c, None, ITestable)
            f = unittest.deferredError(d)
            f.trap(error.UnauthorizedLogin)

            # And it should fail for UsernameHashedPassword
            c = credentials.UsernameHashedPassword(u, crypt(p, u[:2]))
            d = port.login(c, None, ITestable)
            f = unittest.deferredError(d)
            f.trap(error.UnhandledCredentials)
Esempio n. 32
0
 def makePage(self, content):
     _ = i18n.Translator(translator=mockTranslator)
     page = rend.Page(
         docFactory=loaders.stan(tags.invisible(render=tags.directive('i18n'))[content]))
     page.render_i18n = i18n.render(_)
     doc = page.docFactory.load()
     ctx = context.WovenContext(context.PageContext(tag=page),
                                tags.invisible[doc])
     page.rememberStuff(ctx)
     io = StringIO()
     writer = io.write
     def finisher(result):
         return io.getvalue()
     d = page.flattenFactory(doc, ctx, writer, finisher)
     r = unittest.deferredResult(d, 1)
     return r
Esempio n. 33
0
 def testResults(self):
     x = self.proxy().callRemote("add", 2, 3)
     self.assertEquals(unittest.deferredResult(x), 5)
     x = self.proxy().callRemote("kwargs", b=2, a=3)
     self.assertEquals(unittest.deferredResult(x), 5)
     x = self.proxy().callRemote("kwargs", b=3)
     self.assertEquals(unittest.deferredResult(x), 4)
     x = self.proxy().callRemote("defer", "a")
     self.assertEquals(unittest.deferredResult(x), "a")
     x = self.proxy().callRemote("dict", {"a" : 1}, "a")
     self.assertEquals(unittest.deferredResult(x), 1)
     x = self.proxy().callRemote("pair", 'a', 1)
     self.assertEquals(unittest.deferredResult(x), ['a', 1, None])
     x = self.proxy().callRemote("struct")
     self.assertEquals(unittest.deferredResult(x)._asdict,
                       {"a": "c"})
     x = self.proxy().callRemote("complex")
     self.assertEquals(unittest.deferredResult(x)._asdict,
                       {"a": ["b", "c", 12, []], "D": "foo"})
Esempio n. 34
0
 def testResults(self):
     x = self.proxy().callRemote("add", 2, 3)
     self.assertEquals(unittest.deferredResult(x), 5)
     x = self.proxy().callRemote("kwargs", b=2, a=3)
     self.assertEquals(unittest.deferredResult(x), 5)
     x = self.proxy().callRemote("kwargs", b=3)
     self.assertEquals(unittest.deferredResult(x), 4)
     x = self.proxy().callRemote("defer", "a")
     self.assertEquals(unittest.deferredResult(x), "a")
     x = self.proxy().callRemote("dict", {"a": 1}, "a")
     self.assertEquals(unittest.deferredResult(x), 1)
     x = self.proxy().callRemote("pair", 'a', 1)
     self.assertEquals(unittest.deferredResult(x), ['a', 1, None])
     x = self.proxy().callRemote("struct")
     self.assertEquals(unittest.deferredResult(x)._asdict, {"a": "c"})
     x = self.proxy().callRemote("complex")
     self.assertEquals(
         unittest.deferredResult(x)._asdict, {
             "a": ["b", "c", 12, []],
             "D": "foo"
         })
Esempio n. 35
0
    def makePage(self, content):
        _ = i18n.Translator(translator=mockTranslator)
        page = rend.Page(
            docFactory=loaders.stan(tags.invisible(render=tags.directive('i18n'))[content]))
        page.render_i18n = i18n.render(_)
        doc = page.docFactory.load()
        ctx = context.WovenContext(context.PageContext(tag=page),
                                   tags.invisible[doc])
        page.rememberStuff(ctx)

        io = StringIO()
        writer = io.write

        def finisher(result):
            return io.getvalue()

        d = page.flattenFactory(doc, ctx, writer, finisher)
        r = unittest.deferredResult(d, 1)
        return r
Esempio n. 36
0
 def testAnonymousAuthentication(self):
     self.portal.anonymousQuerier = object()  # could be anything but None
     digest = self._callRemote('authenticate', '', '')
     got, _ = unittest.deferredResult(digest)
     self.assertEquals(_, '')
     self.assertEquals(got, ANONYMOUS_AVATARID)
Esempio n. 37
0
 def testAnonymousAuthentication(self):
     self.portal.anonymousQuerier = object() # could be anything but None
     digest = self._callRemote('authenticate', '', '')
     got, _ = unittest.deferredResult(digest)
     self.assertEquals(_, '')
     self.assertEquals(got, ANONYMOUS_AVATARID)
Esempio n. 38
0
 def testCertifiedRemoteCall(self):
     d = self._callRemote('authenticate', 'adim', 'adim')
     cnxId, _ = unittest.deferredResult(d)
     retValue = self._callRemote('lastIndexationTimeAndState', cnxId, 'foo.pdf')
     self.assertEquals(unittest.deferredResult(retValue), [0, Document.UNKNOWN_STATE])
Esempio n. 39
0
 def testUncertifiedRemoteCall(self):
     """only authentified people should be able to call remote methods"""
     retValue = self._callRemote('lastIndexationTimeAndState', 'evil', 'foo.pdf')
     self.assertEquals(unittest.deferredResult(retValue), [-1, Document.UNKNOWN_STATE])
Esempio n. 40
0
 def testRawAuthentication(self):
     for user, passwd in [('adim', 'adim'), ('foo', 'bar')]:
         digest = self._callRemote('authenticate', user, passwd)
         expected = rpc.make_uid(user, passwd)
         self.assertEquals(unittest.deferredResult(digest), expected)
Esempio n. 41
0
def deferred_result(d):
    """
    Shorcut to obtain more verbose errors
    """
    d.addErrback(exception)
    return deferredResult(d)
Esempio n. 42
0
 def testUncertifiedRemoteCall(self):
     """only authentified people should be able to call remote methods"""
     retValue = self._callRemote('lastIndexationTime', 'evil', 'foo.pdf')
     self.assertEquals(unittest.deferredResult(retValue), -1)
Esempio n. 43
0
 def testCertifiedRemoteCall(self):
     d = self._callRemote('authenticate', 'adim', 'adim')
     cnxId = unittest.deferredResult(d)
     retValue = self._callRemote('lastIndexationTime', cnxId, 'foo.pdf')
     self.assertEquals(unittest.deferredResult(retValue), 0)
Esempio n. 44
0
    def test_simple(self):

        doc = div[p['foo'], p['bar']]
        result = unittest.deferredResult(
            rend.Page(docFactory=loaders.stan(doc)).renderString())
        self.assertEquals(result, '<div><p>foo</p><p>bar</p></div>')
Esempio n. 45
0
def getResource(root, path):
    return unittest.deferredResult(
        appserver.NevowSite(root).getPageContextForRequestContext(
            context.RequestContext(tag=testutil.FakeRequest(uri=path))))