示例#1
0
class VersionHandlerTest(unittest.TestCase):
    """
    Tests for L{wokkel.generic.VersionHandler}.
    """

    def test_onVersion(self):
        """
        Test response to incoming version request.
        """
        self.stub = XmlStreamStub()
        self.protocol = generic.VersionHandler('Test', '0.1.0')
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.send = self.stub.xmlstream.send
        self.protocol.connectionInitialized()

        iq = domish.Element((None, 'iq'))
        iq['from'] = '[email protected]/Home'
        iq['to'] = 'example.org'
        iq['type'] = 'get'
        query = iq.addElement((NS_VERSION, 'query'))
        self.stub.send(iq)

        response = self.stub.output[-1]
        self.assertEquals('[email protected]/Home', response['to'])
        self.assertEquals('example.org', response['from'])
        self.assertEquals('result', response['type'])
        self.assertEquals(NS_VERSION, response.query.uri)
        elements = list(domish.generateElementsQNamed(response.query.children,
                                                      'name', NS_VERSION))
        self.assertEquals(1, len(elements))
        self.assertEquals('Test', unicode(elements[0]))
        elements = list(domish.generateElementsQNamed(response.query.children,
                                                      'version', NS_VERSION))
        self.assertEquals(1, len(elements))
        self.assertEquals('0.1.0', unicode(elements[0]))
示例#2
0
 def setUp(self):
     """
     Set up stub and protocol for testing.
     """
     self.stub = XmlStreamStub()
     self.protocol = disco.DiscoClientProtocol()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
 def setUp(self):
     self.stub = XmlStreamStub()
     self.stub.xmlstream.factory = FactoryWithJID()
     self.protocol = protocols.AdminHandler()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
     registry = getUtility(IRegistry)
     settings = registry.forInterface(IXMPPSettings, check=False)
     settings.xmpp_domain = u'example.com'
示例#4
0
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = muc.MUCClient()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()
        self.test_room = 'test'
        self.test_srv = 'conference.example.org'
        self.test_nick = 'Nick'

        self.room_jid = JID(self.test_room + '@' + self.test_srv + '/' +
                            self.test_nick)

        self.user_jid = JID('[email protected]/Testing')
示例#5
0
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = mock.MockDifferentialSyncronisationHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

        self.original = \
            """
            Hamlet: Do you see yonder cloud that's almost in shape of a camel?
            Polonius: By the mass, and 'tis like a camel, indeed.
            Hamlet: Methinks it is like a weasel.
            Polonius: It is backed like a weasel.
            Hamlet: Or like a whale?
            Polonius: Very like a whale.
            """

        self.plain = \
            """
            Hamlet: Do you see the cloud over there that's almost the shape of a camel?
            Polonius: By golly, it is like a camel, indeed.
            Hamlet: I think it looks like a weasel.
            Polonius: It is shaped like a weasel.
            Hamlet: Or like a whale?
            Polonius: It's totally like a whale.
            """

        self.trekkie = \
            """
            Kirk: Do you see yonder cloud that's almost in shape of a Klingon?
            Spock: By the mass, and 'tis like a Klingon, indeed.
            Kirk: Methinks it is like a Vulcan.
            Spock: It is backed like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: Very like a Romulan.
            """

        self.final = \
            """
            Kirk: Do you see the cloud over there that's almost the shape of a Klingon?
            Spock: By golly, it is like a Klingon, indeed.
            Kirk: I think it looks like a Vulcan.
            Spock: It is shaped like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: It's totally like a Romulan.
            """

        self.protocol.mock_text = {'hamlet': self.original}
        self.dmp = diff_match_patch()
示例#6
0
 def setUp(self):
     """
     Set up stub and protocol for testing.
     """
     self.stub = XmlStreamStub()
     self.patch(XMPPHandler, 'request', self.request)
     self.protocol = disco.DiscoClientProtocol()
示例#7
0
 def setUp(self):
     """
     Set up stub and protocol for testing.
     """
     self.stub = XmlStreamStub()
     self.protocol = disco.DiscoClientProtocol()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
 def setUp(self):
     self.stub = XmlStreamStub()
     self.stub.xmlstream.factory = FactoryWithJID()
     self.protocol = protocols.AdminHandler()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
     registry = getUtility(IRegistry)
     settings = registry.forInterface(IXMPPSettings, check=False)
     settings.xmpp_domain = u'example.com'
示例#9
0
class VersionHandlerTest(unittest.TestCase):
    """
    Tests for L{wokkel.generic.VersionHandler}.
    """
    def setUp(self):
        self.protocol = generic.VersionHandler('Test', '0.1.0')

    def test_interface(self):
        """
        L{generic.VersionHandler} implements {IDisco}.
        """
        verifyObject(IDisco, self.protocol)

    def test_onVersion(self):
        """
        Test response to incoming version request.
        """
        self.stub = XmlStreamStub()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.send = self.stub.xmlstream.send
        self.protocol.connectionInitialized()

        iq = domish.Element((None, 'iq'))
        iq['from'] = '[email protected]/Home'
        iq['to'] = 'example.org'
        iq['type'] = 'get'
        iq.addElement((NS_VERSION, 'query'))
        self.stub.send(iq)

        response = self.stub.output[-1]
        self.assertEquals('[email protected]/Home', response['to'])
        self.assertEquals('example.org', response['from'])
        self.assertEquals('result', response['type'])
        self.assertEquals(NS_VERSION, response.query.uri)
        elements = list(
            domish.generateElementsQNamed(response.query.children, 'name',
                                          NS_VERSION))
        self.assertEquals(1, len(elements))
        self.assertEquals('Test', unicode(elements[0]))
        elements = list(
            domish.generateElementsQNamed(response.query.children, 'version',
                                          NS_VERSION))
        self.assertEquals(1, len(elements))
        self.assertEquals('0.1.0', unicode(elements[0]))
示例#10
0
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = muc.MUCClient()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()
        self.test_room = 'test'
        self.test_srv  = 'conference.example.org'
        self.test_nick = 'Nick'

        self.room_jid = JID(self.test_room+'@'+self.test_srv+'/'+self.test_nick)

        self.user_jid = JID('[email protected]/Testing')
示例#11
0
class RosterClientProtocolTest(unittest.TestCase):
    """
    Tests for L{xmppim.RosterClientProtocol}.
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = xmppim.RosterClientProtocol()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()


    def test_removeItem(self):
        """
        Removing a roster item is setting an item with subscription C{remove}.
        """
        d = self.protocol.removeItem(JID('*****@*****.**'))

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEquals(NS_ROSTER, iq.query.uri)

        children = list(domish.generateElementsQNamed(iq.query.children,
                                                      'item', NS_ROSTER))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('*****@*****.**', child['jid'])
        self.assertEquals('remove', child['subscription'])

        # Fake successful response

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d
示例#12
0
class RosterClientProtocolTest(unittest.TestCase):
    """
    Tests for L{xmppim.RosterClientProtocol}.
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = xmppim.RosterClientProtocol()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()


    def test_removeItem(self):
        """
        Removing a roster item is setting an item with subscription C{remove}.
        """
        d = self.protocol.removeItem(JID('*****@*****.**'))

        # Inspect outgoing iq request

        iq = self.stub.output[-1]
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertNotIdentical(None, iq.query)
        self.assertEquals(NS_ROSTER, iq.query.uri)

        children = list(domish.generateElementsQNamed(iq.query.children,
                                                      'item', NS_ROSTER))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('*****@*****.**', child['jid'])
        self.assertEquals('remove', child['subscription'])

        # Fake successful response

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = mock.MockDifferentialSyncronisationHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

        self.original = \
            """
            Hamlet: Do you see yonder cloud that's almost in shape of a camel?
            Polonius: By the mass, and 'tis like a camel, indeed.
            Hamlet: Methinks it is like a weasel.
            Polonius: It is backed like a weasel.
            Hamlet: Or like a whale?
            Polonius: Very like a whale.
            """

        self.plain = \
            """
            Hamlet: Do you see the cloud over there that's almost the shape of a camel?
            Polonius: By golly, it is like a camel, indeed.
            Hamlet: I think it looks like a weasel.
            Polonius: It is shaped like a weasel.
            Hamlet: Or like a whale?
            Polonius: It's totally like a whale.
            """

        self.trekkie = \
            """
            Kirk: Do you see yonder cloud that's almost in shape of a Klingon?
            Spock: By the mass, and 'tis like a Klingon, indeed.
            Kirk: Methinks it is like a Vulcan.
            Spock: It is backed like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: Very like a Romulan.
            """

        self.final = \
            """
            Kirk: Do you see the cloud over there that's almost the shape of a Klingon?
            Spock: By golly, it is like a Klingon, indeed.
            Kirk: I think it looks like a Vulcan.
            Spock: It is shaped like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: It's totally like a Romulan.
            """

        self.protocol.mock_text = {'hamlet': self.original}
        self.dmp = diff_match_patch()
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = mock.MockDifferentialSyncronisationHandler()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#15
0
class DifferentialSyncronisationHandlerFunctionalTest(unittest.TestCase):
    """
    Functional test for the DifferentialSynchronisationProtocol.
    """
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = mock.MockDifferentialSyncronisationHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

        self.original = \
            """
            Hamlet: Do you see yonder cloud that's almost in shape of a camel?
            Polonius: By the mass, and 'tis like a camel, indeed.
            Hamlet: Methinks it is like a weasel.
            Polonius: It is backed like a weasel.
            Hamlet: Or like a whale?
            Polonius: Very like a whale.
            """

        self.plain = \
            """
            Hamlet: Do you see the cloud over there that's almost the shape of a camel?
            Polonius: By golly, it is like a camel, indeed.
            Hamlet: I think it looks like a weasel.
            Polonius: It is shaped like a weasel.
            Hamlet: Or like a whale?
            Polonius: It's totally like a whale.
            """

        self.trekkie = \
            """
            Kirk: Do you see yonder cloud that's almost in shape of a Klingon?
            Spock: By the mass, and 'tis like a Klingon, indeed.
            Kirk: Methinks it is like a Vulcan.
            Spock: It is backed like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: Very like a Romulan.
            """

        self.final = \
            """
            Kirk: Do you see the cloud over there that's almost the shape of a Klingon?
            Spock: By golly, it is like a Klingon, indeed.
            Kirk: I think it looks like a Vulcan.
            Spock: It is shaped like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: It's totally like a Romulan.
            """

        self.protocol.mock_text = {'hamlet': self.original}
        self.dmp = diff_match_patch()

    def test_full_cycle(self):
        # foo logs in.
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='hamlet'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # bar logs in.
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='hamlet'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # foo changes the Sheakespearean text to plain english,
        # and creates a patch.
        original2plain_patch = self.dmp.patch_make(self.original, self.plain)
        original2plain_text = self.dmp.patch_toText(original2plain_patch)
        xml = "<iq from='*****@*****.**' to='example.com' type='set'>" + \
              "<patch xmlns='http://jarn.com/ns/collaborative-editing' node='hamlet'>" + \
              original2plain_text + \
              "</patch></iq>"
        self.stub.send(parseXml(xml))

        # Before receiving a patch from the server bar has already updated
        # his own version to trekkie and sends it away.
        original2trekkie_patch = self.dmp.patch_make(self.original,
                                                     self.trekkie)
        original2trekkie_text = self.dmp.patch_toText(original2trekkie_patch)
        xml = "<iq from='*****@*****.**' to='example.com' type='set'>" + \
              "<patch xmlns='http://jarn.com/ns/collaborative-editing' node='hamlet'>" + \
              original2trekkie_text + \
              "</patch></iq>"
        self.stub.send(parseXml(xml))

        # So now, both have obtained a patch to apply each other changes on
        # the already changed document. They are the same and merged perfectly.
        iq_to_foo = self.stub.output[-1]
        plain2final_text = iq_to_foo.patch.children[0]
        plain2final_patch = self.dmp.patch_fromText(plain2final_text)
        foo_result = self.dmp.patch_apply(plain2final_patch, self.plain)
        foo_final = foo_result[0]
        self.assertEqual(self.final, foo_final)

        iq_to_bar = self.stub.output[-3]
        trekkie2final_text = iq_to_bar.patch.children[0]
        trekkie2final_patch = self.dmp.patch_fromText(trekkie2final_text)
        bar_result = self.dmp.patch_apply(trekkie2final_patch, self.trekkie)
        bar_final = bar_result[0]
        self.assertEqual(self.final, bar_final)
class DifferentialSyncronisationHandlerFunctionalTest(unittest.TestCase):
    """
    Functional test for the DifferentialSynchronisationProtocol.
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = mock.MockDifferentialSyncronisationHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

        self.original = \
            """
            Hamlet: Do you see yonder cloud that's almost in shape of a camel?
            Polonius: By the mass, and 'tis like a camel, indeed.
            Hamlet: Methinks it is like a weasel.
            Polonius: It is backed like a weasel.
            Hamlet: Or like a whale?
            Polonius: Very like a whale.
            """

        self.plain = \
            """
            Hamlet: Do you see the cloud over there that's almost the shape of a camel?
            Polonius: By golly, it is like a camel, indeed.
            Hamlet: I think it looks like a weasel.
            Polonius: It is shaped like a weasel.
            Hamlet: Or like a whale?
            Polonius: It's totally like a whale.
            """

        self.trekkie = \
            """
            Kirk: Do you see yonder cloud that's almost in shape of a Klingon?
            Spock: By the mass, and 'tis like a Klingon, indeed.
            Kirk: Methinks it is like a Vulcan.
            Spock: It is backed like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: Very like a Romulan.
            """

        self.final = \
            """
            Kirk: Do you see the cloud over there that's almost the shape of a Klingon?
            Spock: By golly, it is like a Klingon, indeed.
            Kirk: I think it looks like a Vulcan.
            Spock: It is shaped like a Vulcan.
            Kirk: Or like a Romulan?
            Spock: It's totally like a Romulan.
            """

        self.protocol.mock_text = {'hamlet': self.original}
        self.dmp = diff_match_patch()

    def test_full_cycle(self):
        # foo logs in.
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='hamlet'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # bar logs in.
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='hamlet'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # foo changes the Sheakespearean text to plain english,
        # and creates a patch.
        original2plain_patch = self.dmp.patch_make(self.original, self.plain)
        original2plain_text = self.dmp.patch_toText(original2plain_patch)
        xml = "<iq from='*****@*****.**' to='example.com' type='set'>" + \
              "<patch xmlns='http://jarn.com/ns/collaborative-editing' node='hamlet'>" + \
              original2plain_text + \
              "</patch></iq>"
        self.stub.send(parseXml(xml))

        # Before receiving a patch from the server bar has already updated
        # his own version to trekkie and sends it away.
        original2trekkie_patch = self.dmp.patch_make(self.original, self.trekkie)
        original2trekkie_text = self.dmp.patch_toText(original2trekkie_patch)
        xml = "<iq from='*****@*****.**' to='example.com' type='set'>" + \
              "<patch xmlns='http://jarn.com/ns/collaborative-editing' node='hamlet'>" + \
              original2trekkie_text + \
              "</patch></iq>"
        self.stub.send(parseXml(xml))

        # So now, both have obtained a patch to apply each other changes on
        # the already changed document. They are the same and merged perfectly.
        iq_to_foo = self.stub.output[-1]
        plain2final_text = iq_to_foo.patch.children[0]
        plain2final_patch = self.dmp.patch_fromText(plain2final_text)
        foo_result = self.dmp.patch_apply(plain2final_patch, self.plain)
        foo_final = foo_result[0]
        self.assertEqual(self.final, foo_final)

        iq_to_bar = self.stub.output[-3]
        trekkie2final_text = iq_to_bar.patch.children[0]
        trekkie2final_patch = self.dmp.patch_fromText(trekkie2final_text)
        bar_result = self.dmp.patch_apply(trekkie2final_patch, self.trekkie)
        bar_final = bar_result[0]
        self.assertEqual(self.final, bar_final)
示例#17
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = ping.PingClientProtocol()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#18
0
class PingHandlerTest(unittest.TestCase):
    """
    Tests for L{ping.PingHandler}.
    """
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = ping.PingHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_onPing(self):
        """
        A ping should have a simple result response.
        """
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                   <ping xmlns='urn:xmpp:ping'/>
                 </iq>"""
        self.stub.send(parseXml(xml))

        response = self.stub.output[-1]
        self.assertEquals('example.com', response.getAttribute('from'))
        self.assertEquals('*****@*****.**', response.getAttribute('to'))
        self.assertEquals('result', response.getAttribute('type'))

    def test_onPingHandled(self):
        """
        The ping handler should mark the stanza as handled.
        """
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                   <ping xmlns='urn:xmpp:ping'/>
                 </iq>"""
        iq = parseXml(xml)
        self.stub.send(iq)

        self.assertTrue(iq.handled)

    def test_interfaceIDisco(self):
        """
        The ping handler should provice Service Discovery information.
        """
        verify.verifyObject(iwokkel.IDisco, self.protocol)

    def test_getDiscoInfo(self):
        """
        The ping namespace should be returned as a supported feature.
        """
        def cb(info):
            discoInfo = disco.DiscoInfo()
            for item in info:
                discoInfo.append(item)
            self.assertIn('urn:xmpp:ping', discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'), '')
        d.addCallback(cb)
        return d

    def test_getDiscoInfoNode(self):
        """
        The ping namespace should not be returned for a node.
        """
        def cb(info):
            discoInfo = disco.DiscoInfo()
            for item in info:
                discoInfo.append(item)
            self.assertNotIn('urn:xmpp:ping', discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'), 'test')
        d.addCallback(cb)
        return d

    def test_getDiscoItems(self):
        """
        Items are not supported by this handler, so an empty list is expected.
        """
        def cb(items):
            self.assertEquals(0, len(items))

        d = defer.maybeDeferred(self.protocol.getDiscoItems,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'), '')
        d.addCallback(cb)
        return d
示例#19
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = xmppim.RosterClientProtocol()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#20
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = xmppim.RosterClientProtocol()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#21
0
class DiscoClientProtocolTest(unittest.TestCase):
    """
    Tests for L{disco.DiscoClientProtocol}.
    """
    def setUp(self):
        """
        Set up stub and protocol for testing.
        """
        self.stub = XmlStreamStub()
        self.protocol = disco.DiscoClientProtocol()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_requestItems(self):
        """
        Test request sent out by C{requestItems} and parsing of response.
        """
        def cb(items):
            items = list(items)
            self.assertEqual(2, len(items))
            self.assertEqual(JID(u'test.example.org'), items[0].entity)

        d = self.protocol.requestItems(JID(u'example.org'), u"foo")
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u'example.org', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.assertEqual(u'foo', iq.query.getAttribute(u'node'))
        self.assertEqual(NS_DISCO_ITEMS, iq.query.uri)

        response = toResponse(iq, u'result')
        query = response.addElement((NS_DISCO_ITEMS, u'query'))

        element = query.addElement(u'item')
        element[u'jid'] = u'test.example.org'
        element[u'node'] = u'music'
        element[u'name'] = u'Music from the time of Shakespeare'

        element = query.addElement(u'item')
        element[u'jid'] = u"test2.example.org"

        self.stub.send(response)
        return d

    def test_requestItemsFrom(self):
        """
        A disco items request can be sent with an explicit sender address.
        """
        d = self.protocol.requestItems(JID(u'example.org'),
                                       sender=JID(u'test.example.org'))

        iq = self.stub.output[-1]
        self.assertEqual(u'test.example.org', iq.getAttribute(u'from'))

        response = toResponse(iq, u'result')
        response.addElement((NS_DISCO_ITEMS, u'query'))
        self.stub.send(response)

        return d

    def test_requestInfo(self):
        """
        Test request sent out by C{requestInfo} and parsing of response.
        """
        def cb(info):
            self.assertIn((u'conference', u'text'), info.identities)
            self.assertIn(u'http://jabber.org/protocol/disco#info',
                          info.features)
            self.assertIn(u'http://jabber.org/protocol/muc', info.features)

        d = self.protocol.requestInfo(JID(u'example.org'), 'foo')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u'example.org', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.assertEqual(u'foo', iq.query.getAttribute(u'node'))
        self.assertEqual(NS_DISCO_INFO, iq.query.uri)

        response = toResponse(iq, u'result')
        query = response.addElement((NS_DISCO_INFO, u'query'))

        element = query.addElement(u"identity")
        element[u'category'] = u'conference'  # required
        element[u'type'] = u'text'  # required
        element[u"name"] = u'Romeo and Juliet, Act II, Scene II'  # optional

        element = query.addElement("feature")
        element[u'var'] = u'http://jabber.org/protocol/disco#info'  # required

        element = query.addElement(u"feature")
        element[u'var'] = u'http://jabber.org/protocol/muc'

        self.stub.send(response)
        return d

    def test_requestInfoFrom(self):
        """
        A disco info request can be sent with an explicit sender address.
        """
        d = self.protocol.requestInfo(JID(u'example.org'),
                                      sender=JID(u'test.example.org'))

        iq = self.stub.output[-1]
        self.assertEqual(u'test.example.org', iq.getAttribute(u'from'))

        response = toResponse(iq, u'result')
        response.addElement((NS_DISCO_INFO, u'query'))
        self.stub.send(response)

        return d
示例#22
0
class MucClientTest(unittest.TestCase):
    timeout = 2

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = muc.MUCClient()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()
        self.test_room = 'test'
        self.test_srv  = 'conference.example.org'
        self.test_nick = 'Nick'

        self.room_jid = JID(self.test_room+'@'+self.test_srv+'/'+self.test_nick)

        self.user_jid = JID('[email protected]/Testing')

    def _createRoom(self):
        """A helper method to create a test room.
        """
        # create a room
        self.current_room = muc.Room(self.test_room, self.test_srv, self.test_nick)
        self.protocol._setRoom(self.current_room)


    def test_interface(self):
        """
        Do instances of L{muc.MUCClient} provide L{iwokkel.IMUCClient}?
        """
        verify.verifyObject(iwokkel.IMUCClient, self.protocol)


    def test_userJoinedRoom(self):
        """The client receives presence from an entity joining the room.

        This tests the class L{muc.UserPresence} and the userJoinedRoom event method.

        The test sends the user presence and tests if the event method is called.

        """
        p = muc.UserPresence()
	p['to'] = self.user_jid.full()
        p['from'] = self.room_jid.full()

        # create a room
        self._createRoom()

        def userPresence(room, user):
            self.failUnless(room.name==self.test_room, 'Wrong room name')
            self.failUnless(room.inRoster(user), 'User not in roster')
            	           
	
        d, self.protocol.userJoinedRoom = calledAsync(userPresence)
        self.stub.send(p)
        return d


    def test_groupChat(self):
        """The client receives a groupchat message from an entity in the room.
        """
        m = muc.GroupChat('*****@*****.**',body='test')
	m['from'] = self.room_jid.full()

        self._createRoom()

        def groupChat(room, user, message):
            self.failUnless(message=='test', "Wrong group chat message")
            self.failUnless(room.name==self.test_room, 'Wrong room name')
            	           
	
        d, self.protocol.receivedGroupChat = calledAsync(groupChat)
        self.stub.send(m)
        return d


    def test_discoServerSupport(self):
        """Disco support from client to server.
        """
        test_srv = 'shakespeare.lit'

        def cb(query):
            # check namespace
            self.failUnless(query.uri==disco.NS_INFO, 'Wrong namespace')
            

        d = self.protocol.disco(test_srv)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        
        # send back a response
        response = toResponse(iq, 'result')
        response.addElement('query', disco.NS_INFO)
        # need to add information to response
        response.query.addChild(disco.DiscoFeature(muc.NS_MUC))
        response.query.addChild(disco.DiscoIdentity(category='conference',
                                                    name='Macbeth Chat Service',
                                                    type='text'))
        
        self.stub.send(response)
        return d
        

        
    def test_joinRoom(self):
        """Joining a room
        """
        
        def cb(room):
            self.assertEquals(self.test_room, room.name)

        d = self.protocol.join(self.test_srv, self.test_room, self.test_nick)
        d.addCallback(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name=='presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')

        # send back user presence, they joined        
        response = muc.UserPresence(frm=self.test_room+'@'+self.test_srv+'/'+self.test_nick)
        self.stub.send(response)
        return d

    

    def test_joinRoomForbidden(self):
        """Client joining a room and getting a forbidden error.
        """

        def cb(error):
            
            self.failUnless(error.value.mucCondition=='forbidden','Wrong muc condition')

            
            
        d = self.protocol.join(self.test_srv, self.test_room, self.test_nick)
        d.addBoth(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name=='presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')
        # send back user presence, they joined
        
        response = muc.PresenceError(error=muc.MUCError('auth',
                                                        'forbidden'
                                                        ),
                                     frm=self.room_jid.full())
        self.stub.send(response)
        return d        


    def test_joinRoomBadJid(self):
        """Client joining a room and getting a forbidden error.
        """

        def cb(error):
            
            self.failUnless(error.value.mucCondition=='jid-malformed','Wrong muc condition')

            
            
        d = self.protocol.join(self.test_srv, self.test_room, self.test_nick)
        d.addBoth(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name=='presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')
        # send back user presence, they joined
        
        response = muc.PresenceError(error=muc.MUCError('modify',
                                                        'jid-malformed'
                                                        ),
                                     frm=self.room_jid.full())
        self.stub.send(response)
        return d        



    def test_partRoom(self):
        """Client leaves a room
        """
        def cb(left):
            self.failUnless(left, 'did not leave room')


        d = self.protocol.leave(self.room_jid)
        d.addCallback(cb)

        prs = self.stub.output[-1]
        
        self.failUnless(prs['type']=='unavailable', 'Unavailable is not being sent')
        
        response = prs
        response['from'] = response['to']
        response['to'] = '*****@*****.**'

        self.stub.send(response)
        return d
        

    def test_userPartsRoom(self):
        """An entity leaves the room, a presence of type unavailable is received by the client.
        """

        p = muc.UnavailableUserPresence()
	p['to'] = self.user_jid.full()
        p['from'] = self.room_jid.full()

        # create a room
        self._createRoom()
        # add user to room
        u = muc.User(self.room_jid.resource)

        room = self.protocol._getRoom(self.room_jid)
        room.addUser(u)

        def userPresence(room, user):
            self.failUnless(room.name==self.test_room, 'Wrong room name')
            self.failUnless(room.inRoster(user)==False, 'User in roster')
            	           
        d, self.protocol.userLeftRoom = calledAsync(userPresence)
        self.stub.send(p)
        return d
        

    def test_ban(self):
        """Ban an entity in a room.
        """
        banned = JID('[email protected]/TroubleMakger')
        def cb(banned):
            self.failUnless(banned, 'Did not ban user')

            
        d = self.protocol.ban(self.room_jid, banned, self.user_jid, reason='Spam')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        
        self.failUnless(xpath.matches("/iq[@type='set' and @to='%s']/query/item[@affiliation='outcast']" % (self.room_jid.userhost(),), iq), 'Wrong ban stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d


    def test_kick(self):
        """Kick an entity from a room.
        """
        kicked = JID('[email protected]/TroubleMakger')
        def cb(kicked):
            self.failUnless(kicked, 'Did not kick user')

            
        d = self.protocol.kick(self.room_jid, kicked, self.user_jid, reason='Spam')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        
        self.failUnless(xpath.matches("/iq[@type='set' and @to='%s']/query/item[@affiliation='none']" % (self.room_jid.userhost(),), iq), 'Wrong kick stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d

        

    def test_password(self):
        """Sending a password via presence to a password protected room.
        """
        
        self.protocol.password(self.room_jid, 'secret')
        
        prs = self.stub.output[-1]
        
        self.failUnless(xpath.matches("/presence[@to='%s']/x/password[text()='secret']" % (self.room_jid.full(),), prs), 'Wrong presence stanza')


    def test_history(self):
        """Receiving history on room join.
        """
        m = muc.HistoryMessage(self.room_jid.userhost(), self.protocol._makeTimeStamp(), body='test')
 	m['from'] = self.room_jid.full()
        
        self._createRoom()

        def roomHistory(room, user, body, stamp, frm=None):
            self.failUnless(body=='test', "wrong message body")
            self.failUnless(stamp, 'Does not have a history stamp')
	           

        d, self.protocol.receivedHistory = calledAsync(roomHistory)
        self.stub.send(m)
        return d


    def test_oneToOneChat(self):
        """Converting a one to one chat to a multi-user chat.
        """
        archive = []
        thread = "e0ffe42b28561960c6b12b944a092794b9683a38"
        # create messages
        msg = domish.Element((None, 'message'))
        msg['to'] = '*****@*****.**'
        msg['type'] = 'chat'
        msg.addElement('body', None, 'test')
        msg.addElement('thread', None, thread)

        archive.append(msg)

        msg = domish.Element((None, 'message'))
        msg['to'] = '*****@*****.**'
        msg['type'] = 'chat'
        msg.addElement('body', None, 'yo')
        msg.addElement('thread', None, thread)

        archive.append(msg)

        self.protocol.history(self.room_jid, archive)


        while len(self.stub.output)>0:
            m = self.stub.output.pop()
            # check for delay element
            self.failUnless(m.name=='message', 'Wrong stanza')
            self.failUnless(xpath.matches("/message/delay", m), 'Invalid history stanza')
        

    def test_invite(self):
        """Invite a user to a room
        """
        other_jid = '*****@*****.**'

        self.protocol.invite(other_jid, 'This is a test')

        msg = self.stub.output[-1]

        self.failUnless(xpath.matches("/message[@to='%s']/x/invite/reason" % (other_jid,), msg), 'Wrong message type')


        
    def test_privateMessage(self):
        """Send private messages to muc entities.
        """
        other_nick = self.room_jid.userhost()+'/OtherNick'

        self.protocol.chat(other_nick, 'This is a test')

        msg = self.stub.output[-1]

        self.failUnless(xpath.matches("/message[@type='chat' and @to='%s']/body" % (other_nick,), msg), 'Wrong message type')


    def test_register(self):
        """Client registering with a room. http://xmpp.org/extensions/xep-0045.html#register

        """
        
        def cb(iq):
            # check for a result
            self.failUnless(iq['type']=='result', 'We did not get a result')
        
        d = self.protocol.register(self.room_jid)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.failUnless(xpath.matches("/iq/query[@xmlns='%s']" % (muc.NS_REQUEST), iq), 'Invalid iq register request')
        
        response = toResponse(iq, 'result')
        
        self.stub.send(response)
        return d

    def test_voice(self):
        """ Client requesting voice for a room.
        """
        self.protocol.voice(self.room_jid.userhost())

        m = self.stub.output[-1]
        
        self.failUnless(xpath.matches("/message/x[@type='submit']/field/value[text()='%s']" % (muc.NS_MUC_REQUEST,), m), 'Invalid voice message stanza')


    def test_roomConfigure(self):
        """ Default configure and changing the room name.
        """

        def cb(iq):
            self.failUnless(iq['type']=='result', 'Not a result')
            

        fields = []

        fields.append(data_form.Field(label='Natural-Language Room Name',
                                      var='muc#roomconfig_roomname',
                                      value=self.test_room))
        
        d = self.protocol.configure(self.room_jid.userhost(), fields)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.failUnless(xpath.matches("/iq/query[@xmlns='%s']/x"% (muc.NS_MUC_OWNER,), iq), 'Bad configure request')
        
        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d


    def test_roomDestroy(self):
        """ Destroy a room.
        """

        def cb(destroyed):
            self.failUnless(destroyed==True, 'Room not destroyed.')
                   
        d = self.protocol.destroy(self.room_jid)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.failUnless(xpath.matches("/iq/query[@xmlns='%s']/destroy"% (muc.NS_MUC_OWNER,), iq), 'Bad configure request')
        
        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d


    def test_nickChange(self):
        """Send a nick change to the server.
        """
        test_nick = 'newNick'
        
        self._createRoom()

        def cb(room):
            self.assertEquals(self.test_room, room.name)
            self.assertEquals(test_nick, room.nick)

        d = self.protocol.nick(self.room_jid, test_nick)
        d.addCallback(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name=='presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')

        # send back user presence, they joined        
        response = muc.UserPresence(frm=self.test_room+'@'+self.test_srv+'/'+test_nick)
        
        self.stub.send(response)
        return d

    def test_grantVoice(self):
        """Test granting voice to a user.

        """
        give_voice = JID('[email protected]/TroubleMakger')
        def cb(give_voice):
            self.failUnless(give_voice, 'Did not give voice user')

            
        d = self.protocol.grantVoice(self.user_jid, self.room_jid, give_voice)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        
        self.failUnless(xpath.matches("/iq[@type='set' and @to='%s']/query/item[@role='participant']" % (self.room_jid.userhost(),), iq), 'Wrong voice stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d


    def test_changeStatus(self):
        """Change status
        """
        self._createRoom()
        r = self.protocol._getRoom(self.room_jid)
        u = muc.User(self.room_jid.resource)
        r.addUser(u)

        def cb(room):
            self.assertEquals(self.test_room, room.name)
            u = room.getUser(self.room_jid.resource)
            self.failUnless(u is not None, 'User not found')
            self.failUnless(u.status == 'testing MUC', 'Wrong status')
            self.failUnless(u.show == 'xa', 'Wrong show')
            
        d = self.protocol.status(self.room_jid, 'xa', 'testing MUC')
        d.addCallback(cb)

        prs = self.stub.output[-1]

        self.failUnless(prs.name=='presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')

        # send back user presence, they joined        
        response = muc.UserPresence(frm=self.room_jid.full())
        response.addElement('show', None, 'xa')
        response.addElement('status', None, 'testing MUC')
        self.stub.send(response)
        return d        
class AdminCommandsProtocolTest(unittest.TestCase):
    """ """
    layer = XMPPCORE_INTEGRATION_TESTING

    def setUp(self):
        self.stub = XmlStreamStub()
        self.stub.xmlstream.factory = FactoryWithJID()
        self.protocol = protocols.AdminHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()
        registry = getUtility(IRegistry)
        settings = registry.forInterface(IXMPPSettings, check=False)
        settings.xmpp_domain = u'example.com'

    def test_addUser(self):
        d = self.protocol.addUser(u'*****@*****.**', u'secret')

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.failIf(iq.command is None)
        self.assertEqual(protocols.NODE_ADMIN_ADD_USER,
                         iq.command.getAttribute('node'))
        self.assertEqual('execute', iq.command.getAttribute('action'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        command = response.addElement((protocols.NS_COMMANDS, u'command'))
        command[u'node'] = protocols.NODE_ADMIN_ADD_USER
        command[u'status'] = u'executing'
        command[u'sessionid'] = u'sid-0'
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NODE_ADMIN)
        userjid = data_form.Field(u'jid-single',
                                  var=u'accountjid',
                                  required=True)
        password = data_form.Field(u'text-private',
                                   var=u'password',
                                   required=True)
        password_verify = data_form.Field(u'text-private',
                                          var=u'password-verify',
                                          required=True)
        form.addField(form_type)
        form.addField(userjid)
        form.addField(password)
        form.addField(password_verify)
        command.addContent(form.toElement())
        self.stub.send(response)

        iq = self.stub.output[-1]
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.assertEqual(protocols.NODE_ADMIN_ADD_USER,
                         iq.command.getAttribute(u'node'))
        self.assertEqual(u'sid-0', iq.command.getAttribute(u'sessionid'))
        form = data_form.findForm(iq.command, protocols.NODE_ADMIN)
        self.assertEqual(u'submit', form.formType)
        self.failUnless(u'accountjid' in form.fields)
        self.assertEqual(u'*****@*****.**', form.fields['accountjid'].value)
        self.failUnless(u'password' in form.fields)
        self.assertEqual(u'secret', form.fields['password'].value)
        self.failUnless(u'password-verify' in form.fields)
        self.assertEqual(u'secret', form.fields['password-verify'].value)

    def test_deleteUsers(self):
        self.protocol.deleteUsers(u'*****@*****.**')

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.failIf(iq.command is None)
        self.assertEqual(protocols.NODE_ADMIN_DELETE_USER,
                         iq.command.getAttribute('node'))
        self.assertEqual('execute', iq.command.getAttribute('action'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        command = response.addElement((protocols.NS_COMMANDS, u'command'))
        command[u'node'] = protocols.NODE_ADMIN_DELETE_USER
        command[u'status'] = u'executing'
        command[u'sessionid'] = u'sid-0'
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NODE_ADMIN)
        userjids = data_form.Field(u'jid-multi', var=u'accountjids')
        form.addField(form_type)
        form.addField(userjids)
        command.addContent(form.toElement())
        self.stub.send(response)

        iq = self.stub.output[-1]
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.assertEqual(protocols.NODE_ADMIN_DELETE_USER,
                         iq.command.getAttribute(u'node'))
        self.assertEqual(u'sid-0', iq.command.getAttribute(u'sessionid'))
        form = data_form.findForm(iq.command, protocols.NODE_ADMIN)
        self.assertEqual(u'submit', form.formType)
        self.failUnless(u'accountjids' in form.fields)
        self.assertEqual([u'*****@*****.**'],
                         form.fields['accountjids'].values)

    def test_sendAnnouncement(self):
        self.protocol.sendAnnouncement(u'Hello world')

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.failIf(iq.command is None)
        self.assertEqual(protocols.NODE_ADMIN_ANNOUNCE,
                         iq.command.getAttribute('node'))
        self.assertEqual('execute', iq.command.getAttribute('action'))

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        command = response.addElement((protocols.NS_COMMANDS, u'command'))
        command[u'node'] = protocols.NODE_ADMIN_ANNOUNCE
        command[u'status'] = u'executing'
        command[u'sessionid'] = u'sid-0'
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NODE_ADMIN)
        subject = data_form.Field(u'text-single', var=u'subject')
        body = data_form.Field(u'text-multi', var=u'body')
        form.addField(form_type)
        form.addField(subject)
        form.addField(body)
        command.addContent(form.toElement())
        self.stub.send(response)

        iq = self.stub.output[-1]
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.assertEqual(protocols.NODE_ADMIN_ANNOUNCE,
                         iq.command.getAttribute(u'node'))
        self.assertEqual(u'sid-0', iq.command.getAttribute(u'sessionid'))
        form = data_form.findForm(iq.command, protocols.NODE_ADMIN)
        self.assertEqual(u'submit', form.formType)
        self.failUnless(u'subject' in form.fields)
        self.assertEqual(u'Announce', form.fields['subject'].value)
        self.failUnless(u'body' in form.fields)
        self.assertEqual(u'Hello world', form.fields['body'].value)
示例#24
0
class MucClientTest(unittest.TestCase):
    timeout = 2

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = muc.MUCClient()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()
        self.test_room = 'test'
        self.test_srv = 'conference.example.org'
        self.test_nick = 'Nick'

        self.room_jid = JID(self.test_room + '@' + self.test_srv + '/' +
                            self.test_nick)

        self.user_jid = JID('[email protected]/Testing')

    def _createRoom(self):
        """A helper method to create a test room.
        """
        # create a room
        self.current_room = muc.Room(self.test_room, self.test_srv,
                                     self.test_nick)
        self.protocol._setRoom(self.current_room)

    def test_interface(self):
        """
        Do instances of L{muc.MUCClient} provide L{iwokkel.IMUCClient}?
        """
        verify.verifyObject(iwokkel.IMUCClient, self.protocol)

    def test_userJoinedRoom(self):
        """The client receives presence from an entity joining the room.

        This tests the class L{muc.UserPresence} and the userJoinedRoom event method.

        The test sends the user presence and tests if the event method is called.

        """
        p = muc.UserPresence()
        p['to'] = self.user_jid.full()
        p['from'] = self.room_jid.full()

        # create a room
        self._createRoom()

        def userPresence(room, user):
            self.failUnless(room.name == self.test_room, 'Wrong room name')
            self.failUnless(room.inRoster(user), 'User not in roster')

        d, self.protocol.userJoinedRoom = calledAsync(userPresence)
        self.stub.send(p)
        return d

    def test_groupChat(self):
        """The client receives a groupchat message from an entity in the room.
        """
        m = muc.GroupChat('*****@*****.**', body='test')
        m['from'] = self.room_jid.full()

        self._createRoom()

        def groupChat(room, user, message):
            self.failUnless(message == 'test', "Wrong group chat message")
            self.failUnless(room.name == self.test_room, 'Wrong room name')

        d, self.protocol.receivedGroupChat = calledAsync(groupChat)
        self.stub.send(m)
        return d

    def test_discoServerSupport(self):
        """Disco support from client to server.
        """
        test_srv = 'shakespeare.lit'

        def cb(query):
            # check namespace
            self.failUnless(query.uri == disco.NS_INFO, 'Wrong namespace')

        d = self.protocol.disco(test_srv)
        d.addCallback(cb)

        iq = self.stub.output[-1]

        # send back a response
        response = toResponse(iq, 'result')
        response.addElement('query', disco.NS_INFO)
        # need to add information to response
        response.query.addChild(disco.DiscoFeature(muc.NS_MUC))
        response.query.addChild(
            disco.DiscoIdentity(category='conference',
                                name='Macbeth Chat Service',
                                type='text'))

        self.stub.send(response)
        return d

    def test_joinRoom(self):
        """Joining a room
        """
        def cb(room):
            self.assertEquals(self.test_room, room.name)

        d = self.protocol.join(self.test_srv, self.test_room, self.test_nick)
        d.addCallback(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name == 'presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')

        # send back user presence, they joined
        response = muc.UserPresence(frm=self.test_room + '@' + self.test_srv +
                                    '/' + self.test_nick)
        self.stub.send(response)
        return d

    def test_joinRoomForbidden(self):
        """Client joining a room and getting a forbidden error.
        """
        def cb(error):

            self.failUnless(error.value.mucCondition == 'forbidden',
                            'Wrong muc condition')

        d = self.protocol.join(self.test_srv, self.test_room, self.test_nick)
        d.addBoth(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name == 'presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')
        # send back user presence, they joined

        response = muc.PresenceError(error=muc.MUCError('auth', 'forbidden'),
                                     frm=self.room_jid.full())
        self.stub.send(response)
        return d

    def test_joinRoomBadJid(self):
        """Client joining a room and getting a forbidden error.
        """
        def cb(error):

            self.failUnless(error.value.mucCondition == 'jid-malformed',
                            'Wrong muc condition')

        d = self.protocol.join(self.test_srv, self.test_room, self.test_nick)
        d.addBoth(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name == 'presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')
        # send back user presence, they joined

        response = muc.PresenceError(error=muc.MUCError(
            'modify', 'jid-malformed'),
                                     frm=self.room_jid.full())
        self.stub.send(response)
        return d

    def test_partRoom(self):
        """Client leaves a room
        """
        def cb(left):
            self.failUnless(left, 'did not leave room')

        d = self.protocol.leave(self.room_jid)
        d.addCallback(cb)

        prs = self.stub.output[-1]

        self.failUnless(prs['type'] == 'unavailable',
                        'Unavailable is not being sent')

        response = prs
        response['from'] = response['to']
        response['to'] = '*****@*****.**'

        self.stub.send(response)
        return d

    def test_userPartsRoom(self):
        """An entity leaves the room, a presence of type unavailable is received by the client.
        """

        p = muc.UnavailableUserPresence()
        p['to'] = self.user_jid.full()
        p['from'] = self.room_jid.full()

        # create a room
        self._createRoom()
        # add user to room
        u = muc.User(self.room_jid.resource)

        room = self.protocol._getRoom(self.room_jid)
        room.addUser(u)

        def userPresence(room, user):
            self.failUnless(room.name == self.test_room, 'Wrong room name')
            self.failUnless(room.inRoster(user) == False, 'User in roster')

        d, self.protocol.userLeftRoom = calledAsync(userPresence)
        self.stub.send(p)
        return d

    def test_ban(self):
        """Ban an entity in a room.
        """
        banned = JID('[email protected]/TroubleMakger')

        def cb(banned):
            self.failUnless(banned, 'Did not ban user')

        d = self.protocol.ban(self.room_jid,
                              banned,
                              self.user_jid,
                              reason='Spam')
        d.addCallback(cb)

        iq = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/iq[@type='set' and @to='%s']/query/item[@affiliation='outcast']"
                % (self.room_jid.userhost(), ), iq), 'Wrong ban stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d

    def test_kick(self):
        """Kick an entity from a room.
        """
        kicked = JID('[email protected]/TroubleMakger')

        def cb(kicked):
            self.failUnless(kicked, 'Did not kick user')

        d = self.protocol.kick(self.room_jid,
                               kicked,
                               self.user_jid,
                               reason='Spam')
        d.addCallback(cb)

        iq = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/iq[@type='set' and @to='%s']/query/item[@affiliation='none']"
                % (self.room_jid.userhost(), ), iq), 'Wrong kick stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d

    def test_password(self):
        """Sending a password via presence to a password protected room.
        """

        self.protocol.password(self.room_jid, 'secret')

        prs = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/presence[@to='%s']/x/password[text()='secret']" %
                (self.room_jid.full(), ), prs), 'Wrong presence stanza')

    def test_history(self):
        """Receiving history on room join.
        """
        m = muc.HistoryMessage(self.room_jid.userhost(),
                               self.protocol._makeTimeStamp(),
                               body='test')
        m['from'] = self.room_jid.full()

        self._createRoom()

        def roomHistory(room, user, body, stamp, frm=None):
            self.failUnless(body == 'test', "wrong message body")
            self.failUnless(stamp, 'Does not have a history stamp')

        d, self.protocol.receivedHistory = calledAsync(roomHistory)
        self.stub.send(m)
        return d

    def test_oneToOneChat(self):
        """Converting a one to one chat to a multi-user chat.
        """
        archive = []
        thread = "e0ffe42b28561960c6b12b944a092794b9683a38"
        # create messages
        msg = domish.Element((None, 'message'))
        msg['to'] = '*****@*****.**'
        msg['type'] = 'chat'
        msg.addElement('body', None, 'test')
        msg.addElement('thread', None, thread)

        archive.append(msg)

        msg = domish.Element((None, 'message'))
        msg['to'] = '*****@*****.**'
        msg['type'] = 'chat'
        msg.addElement('body', None, 'yo')
        msg.addElement('thread', None, thread)

        archive.append(msg)

        self.protocol.history(self.room_jid, archive)

        while len(self.stub.output) > 0:
            m = self.stub.output.pop()
            # check for delay element
            self.failUnless(m.name == 'message', 'Wrong stanza')
            self.failUnless(xpath.matches("/message/delay", m),
                            'Invalid history stanza')

    def test_invite(self):
        """Invite a user to a room
        """
        other_jid = '*****@*****.**'

        self.protocol.invite(other_jid, 'This is a test')

        msg = self.stub.output[-1]

        self.failUnless(
            xpath.matches("/message[@to='%s']/x/invite/reason" % (other_jid, ),
                          msg), 'Wrong message type')

    def test_privateMessage(self):
        """Send private messages to muc entities.
        """
        other_nick = self.room_jid.userhost() + '/OtherNick'

        self.protocol.chat(other_nick, 'This is a test')

        msg = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/message[@type='chat' and @to='%s']/body" % (other_nick, ),
                msg), 'Wrong message type')

    def test_register(self):
        """Client registering with a room. http://xmpp.org/extensions/xep-0045.html#register

        """
        def cb(iq):
            # check for a result
            self.failUnless(iq['type'] == 'result', 'We did not get a result')

        d = self.protocol.register(self.room_jid)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.failUnless(
            xpath.matches("/iq/query[@xmlns='%s']" % (muc.NS_REQUEST), iq),
            'Invalid iq register request')

        response = toResponse(iq, 'result')

        self.stub.send(response)
        return d

    def test_voice(self):
        """ Client requesting voice for a room.
        """
        self.protocol.voice(self.room_jid.userhost())

        m = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/message/x[@type='submit']/field/value[text()='%s']" %
                (muc.NS_MUC_REQUEST, ), m), 'Invalid voice message stanza')

    def test_roomConfigure(self):
        """ Default configure and changing the room name.
        """
        def cb(iq):
            self.failUnless(iq['type'] == 'result', 'Not a result')

        fields = []

        fields.append(
            data_form.Field(label='Natural-Language Room Name',
                            var='muc#roomconfig_roomname',
                            value=self.test_room))

        d = self.protocol.configure(self.room_jid.userhost(), fields)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.failUnless(
            xpath.matches("/iq/query[@xmlns='%s']/x" % (muc.NS_MUC_OWNER, ),
                          iq), 'Bad configure request')

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d

    def test_roomDestroy(self):
        """ Destroy a room.
        """
        def cb(destroyed):
            self.failUnless(destroyed == True, 'Room not destroyed.')

        d = self.protocol.destroy(self.room_jid)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.failUnless(
            xpath.matches(
                "/iq/query[@xmlns='%s']/destroy" % (muc.NS_MUC_OWNER, ), iq),
            'Bad configure request')

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d

    def test_nickChange(self):
        """Send a nick change to the server.
        """
        test_nick = 'newNick'

        self._createRoom()

        def cb(room):
            self.assertEquals(self.test_room, room.name)
            self.assertEquals(test_nick, room.nick)

        d = self.protocol.nick(self.room_jid, test_nick)
        d.addCallback(cb)

        prs = self.stub.output[-1]
        self.failUnless(prs.name == 'presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')

        # send back user presence, they joined
        response = muc.UserPresence(frm=self.test_room + '@' + self.test_srv +
                                    '/' + test_nick)

        self.stub.send(response)
        return d

    def test_grantVoice(self):
        """Test granting voice to a user.

        """
        give_voice = JID('[email protected]/TroubleMakger')

        def cb(give_voice):
            self.failUnless(give_voice, 'Did not give voice user')

        d = self.protocol.grantVoice(self.user_jid, self.room_jid, give_voice)
        d.addCallback(cb)

        iq = self.stub.output[-1]

        self.failUnless(
            xpath.matches(
                "/iq[@type='set' and @to='%s']/query/item[@role='participant']"
                % (self.room_jid.userhost(), ), iq), 'Wrong voice stanza')

        response = toResponse(iq, 'result')

        self.stub.send(response)

        return d

    def test_changeStatus(self):
        """Change status
        """
        self._createRoom()
        r = self.protocol._getRoom(self.room_jid)
        u = muc.User(self.room_jid.resource)
        r.addUser(u)

        def cb(room):
            self.assertEquals(self.test_room, room.name)
            u = room.getUser(self.room_jid.resource)
            self.failUnless(u is not None, 'User not found')
            self.failUnless(u.status == 'testing MUC', 'Wrong status')
            self.failUnless(u.show == 'xa', 'Wrong show')

        d = self.protocol.status(self.room_jid, 'xa', 'testing MUC')
        d.addCallback(cb)

        prs = self.stub.output[-1]

        self.failUnless(prs.name == 'presence', "Need to be presence")
        self.failUnless(getattr(prs, 'x', None), 'No muc x element')

        # send back user presence, they joined
        response = muc.UserPresence(frm=self.room_jid.full())
        response.addElement('show', None, 'xa')
        response.addElement('status', None, 'testing MUC')
        self.stub.send(response)
        return d
示例#25
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = pubsub.PubSubClient()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#26
0
class PubSubClientTest(unittest.TestCase):
    timeout = 2

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = pubsub.PubSubClient()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_interface(self):
        """
        Do instances of L{pubsub.PubSubClient} provide L{iwokkel.IPubSubClient}?
        """
        verify.verifyObject(iwokkel.IPubSubClient, self.protocol)

    def test_eventItems(self):
        """
        Test receiving an items event resulting in a call to itemsReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('items')
        items['node'] = 'test'
        item1 = items.addElement('item')
        item1['id'] = 'item1'
        item2 = items.addElement('retract')
        item2['id'] = 'item2'
        item3 = items.addElement('item')
        item3['id'] = 'item3'

        def itemsReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)
            self.assertEquals([item1, item2, item3], event.items)

        d, self.protocol.itemsReceived = calledAsync(itemsReceived)
        self.stub.send(message)
        return d

    def test_eventItemsCollection(self):
        """
        Test receiving an items event resulting in a call to itemsReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('items')
        items['node'] = 'test'

        headers = shim.Headers([('Collection', 'collection')])
        message.addChild(headers)

        def itemsReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)
            self.assertEquals({'Collection': ['collection']}, event.headers)

        d, self.protocol.itemsReceived = calledAsync(itemsReceived)
        self.stub.send(message)
        return d

    def test_event_delete(self):
        """
        Test receiving a delete event resulting in a call to deleteReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('delete')
        items['node'] = 'test'

        def deleteReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)

        d, self.protocol.deleteReceived = calledAsync(deleteReceived)
        self.stub.send(message)
        return d

    def test_event_purge(self):
        """
        Test receiving a purge event resulting in a call to purgeReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('purge')
        items['node'] = 'test'

        def purgeReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)

        d, self.protocol.purgeReceived = calledAsync(purgeReceived)
        self.stub.send(message)
        return d

    def test_createNode(self):
        """
        Test sending create request.
        """
        def cb(nodeIdentifier):
            self.assertEquals('test', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'create',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d

    def test_createNodeInstant(self):
        """
        Test sending create request resulting in an instant node.
        """
        def cb(nodeIdentifier):
            self.assertEquals('test', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'))
        d.addCallback(cb)

        iq = self.stub.output[-1]
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'create',
                                          NS_PUBSUB))
        child = children[0]
        self.assertFalse(child.hasAttribute('node'))

        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        create = command.addElement('create')
        create['node'] = 'test'
        self.stub.send(response)
        return d

    def test_createNodeRenamed(self):
        """
        Test sending create request resulting in renamed node.
        """
        def cb(nodeIdentifier):
            self.assertEquals('test2', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'create',
                                          NS_PUBSUB))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        create = command.addElement('create')
        create['node'] = 'test2'
        self.stub.send(response)
        return d

    def test_deleteNode(self):
        """
        Test sending delete request.
        """

        d = self.protocol.deleteNode(JID('pubsub.example.org'), 'test')

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'delete',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d

    def test_publish(self):
        """
        Test sending publish request.
        """

        item = pubsub.Item()
        d = self.protocol.publish(JID('pubsub.example.org'), 'test', [item])

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'publish',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        items = list(
            domish.generateElementsQNamed(child.children, 'item', NS_PUBSUB))
        self.assertEquals(1, len(items))
        self.assertIdentical(item, items[0])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d

    def test_publishNoItems(self):
        """
        Test sending publish request without items.
        """

        d = self.protocol.publish(JID('pubsub.example.org'), 'test')

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'publish',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d

    def test_subscribe(self):
        """
        Test sending subscription request.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                    JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'subscribe',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('*****@*****.**', child['jid'])

        response = toResponse(iq, 'result')
        pubsub = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = pubsub.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'subscribed'
        self.stub.send(response)
        return d

    def test_subscribePending(self):
        """
        Test sending subscription request that results in a pending
        subscription.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                    JID('*****@*****.**'))

        iq = self.stub.output[-1]
        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = command.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'pending'
        self.stub.send(response)
        self.assertFailure(d, pubsub.SubscriptionPending)
        return d

    def test_subscribeUnconfigured(self):
        """
        Test sending subscription request that results in an unconfigured
        subscription.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                    JID('*****@*****.**'))

        iq = self.stub.output[-1]
        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = command.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'unconfigured'
        self.stub.send(response)
        self.assertFailure(d, pubsub.SubscriptionUnconfigured)
        return d

    def test_unsubscribe(self):
        """
        Test sending unsubscription request.
        """
        d = self.protocol.unsubscribe(JID('pubsub.example.org'), 'test',
                                      JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'unsubscribe',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('*****@*****.**', child['jid'])

        self.stub.send(toResponse(iq, 'result'))
        return d

    def test_items(self):
        """
        Test sending items request.
        """
        def cb(items):
            self.assertEquals([], items)

        d = self.protocol.items(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('get', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'items',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        items = response.addElement((NS_PUBSUB, 'pubsub')).addElement('items')
        items['node'] = 'test'

        self.stub.send(response)

        return d

    def test_itemsMaxItems(self):
        """
        Test sending items request, with limit on the number of items.
        """
        def cb(items):
            self.assertEquals(2, len(items))
            self.assertEquals([item1, item2], items)

        d = self.protocol.items(JID('pubsub.example.org'), 'test', maxItems=2)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('get', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(
            domish.generateElementsQNamed(iq.pubsub.children, 'items',
                                          NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('2', child['max_items'])

        response = toResponse(iq, 'result')
        items = response.addElement((NS_PUBSUB, 'pubsub')).addElement('items')
        items['node'] = 'test'
        item1 = items.addElement('item')
        item1['id'] = 'item1'
        item2 = items.addElement('item')
        item2['id'] = 'item2'

        self.stub.send(response)

        return d
示例#27
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.stub.xmlstream.factory = FactoryWithJID()
     self.protocol = protocols.AdminHandler()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#28
0
class AdminCommandsProtocolTest(unittest.TestCase):
    """
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.stub.xmlstream.factory = FactoryWithJID()
        self.protocol = protocols.AdminHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_addUser(self):
        self.protocol.addUser(u'*****@*****.**', u'secret')

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.failIf(iq.command is None)
        self.assertEqual(protocols.NODE_ADMIN_ADD_USER,
                         iq.command.getAttribute('node'))
        self.assertEqual('execute', iq.command.getAttribute('action'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        command = response.addElement((protocols.NS_COMMANDS, u'command'))
        command[u'node'] = protocols.NODE_ADMIN_ADD_USER
        command[u'status'] = u'executing'
        command[u'sessionid'] = u'sid-0'
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NODE_ADMIN)
        userjid = data_form.Field(u'jid-single',
                                  var=u'accountjid', required=True)
        password = data_form.Field(u'text-private',
                                   var=u'password', required=True)
        password_verify = data_form.Field(u'text-private',
                                          var=u'password-verify',
                                          required=True)
        form.addField(form_type)
        form.addField(userjid)
        form.addField(password)
        form.addField(password_verify)
        command.addContent(form.toElement())
        self.stub.send(response)

        iq = self.stub.output[-1]
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.assertEqual(protocols.NODE_ADMIN_ADD_USER,
                         iq.command.getAttribute(u'node'))
        self.assertEqual(u'sid-0', iq.command.getAttribute(u'sessionid'))
        form = data_form.findForm(iq.command, protocols.NODE_ADMIN)
        self.assertEqual(u'submit', form.formType)
        self.failUnless(u'accountjid' in form.fields)
        self.assertEqual(u'*****@*****.**', form.fields['accountjid'].value)
        self.failUnless(u'password' in form.fields)
        self.assertEqual(u'secret', form.fields['password'].value)
        self.failUnless(u'password-verify' in form.fields)
        self.assertEqual(u'secret', form.fields['password-verify'].value)

    def test_deleteUsers(self):
        self.protocol.deleteUsers(u'*****@*****.**')

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.failIf(iq.command is None)
        self.assertEqual(protocols.NODE_ADMIN_DELETE_USER,
                         iq.command.getAttribute('node'))
        self.assertEqual('execute', iq.command.getAttribute('action'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        command = response.addElement((protocols.NS_COMMANDS, u'command'))
        command[u'node'] = protocols.NODE_ADMIN_DELETE_USER
        command[u'status'] = u'executing'
        command[u'sessionid'] = u'sid-0'
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NODE_ADMIN)
        userjids = data_form.Field(u'jid-multi',
                                  var=u'accountjids')
        form.addField(form_type)
        form.addField(userjids)
        command.addContent(form.toElement())
        self.stub.send(response)

        iq = self.stub.output[-1]
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.assertEqual(protocols.NODE_ADMIN_DELETE_USER,
                         iq.command.getAttribute(u'node'))
        self.assertEqual(u'sid-0', iq.command.getAttribute(u'sessionid'))
        form = data_form.findForm(iq.command, protocols.NODE_ADMIN)
        self.assertEqual(u'submit', form.formType)
        self.failUnless(u'accountjids' in form.fields)
        self.assertEqual([u'*****@*****.**'],
                         form.fields['accountjids'].values)

    def test_sendAnnouncement(self):
        self.protocol.sendAnnouncement(u'Hello world')

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.failIf(iq.command is None)
        self.assertEqual(protocols.NODE_ADMIN_ANNOUNCE,
                         iq.command.getAttribute('node'))
        self.assertEqual('execute', iq.command.getAttribute('action'))

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        command = response.addElement((protocols.NS_COMMANDS, u'command'))
        command[u'node'] = protocols.NODE_ADMIN_ANNOUNCE
        command[u'status'] = u'executing'
        command[u'sessionid'] = u'sid-0'
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden', var=u'FORM_TYPE',
                                    value=protocols.NODE_ADMIN)
        subject = data_form.Field(u'text-single', var=u'subject')
        body = data_form.Field(u'text-multi', var=u'body')
        form.addField(form_type)
        form.addField(subject)
        form.addField(body)
        command.addContent(form.toElement())
        self.stub.send(response)

        iq = self.stub.output[-1]
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.assertEqual(protocols.NS_COMMANDS, iq.command.uri)
        self.assertEqual(protocols.NODE_ADMIN_ANNOUNCE,
                         iq.command.getAttribute(u'node'))
        self.assertEqual(u'sid-0', iq.command.getAttribute(u'sessionid'))
        form = data_form.findForm(iq.command, protocols.NODE_ADMIN)
        self.assertEqual(u'submit', form.formType)
        self.failUnless(u'subject' in form.fields)
        self.assertEqual(u'Announce', form.fields['subject'].value)
        self.failUnless(u'body' in form.fields)
        self.assertEqual(u'Hello world', form.fields['body'].value)
示例#29
0
class PingClientProtocolTest(unittest.TestCase):
    """
    Tests for L{ping.PingClientProtocol}.
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = ping.PingClientProtocol()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()


    def test_ping(self):
        """
        Pinging a service should fire a deferred with None
        """
        def cb(result):
            self.assertIdentical(None, result)

        d = self.protocol.ping(JID("example.com"))
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.assertEqual('urn:xmpp:ping', iq.ping.uri)

        response = toResponse(iq, u'result')
        self.stub.send(response)

        return d


    def test_pingWithSender(self):
        """
        Pinging a service with a sender address should include that address.
        """
        d = self.protocol.ping(JID("example.com"),
                               sender=JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEqual(u'*****@*****.**', iq.getAttribute(u'from'))

        response = toResponse(iq, u'result')
        self.stub.send(response)

        return d


    def test_pingNotSupported(self):
        """
        Pinging a service should fire a deferred with None if not supported.
        """
        def cb(result):
            self.assertIdentical(None, result)

        d = self.protocol.ping(JID("example.com"))
        d.addCallback(cb)

        iq = self.stub.output[-1]

        exc = StanzaError('service-unavailable')
        response = exc.toResponse(iq)
        self.stub.send(response)

        return d


    def test_pingStanzaError(self):
        """
        Pinging a service should errback a deferred on other (stanza) errors.
        """
        def cb(exc):
            self.assertEquals('item-not-found', exc.condition)

        d = self.protocol.ping(JID("example.com"))
        self.assertFailure(d, StanzaError)
        d.addCallback(cb)

        iq = self.stub.output[-1]

        exc = StanzaError('item-not-found')
        response = exc.toResponse(iq)
        self.stub.send(response)

        return d
示例#30
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = mock.MockDifferentialSyncronisationHandler()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#31
0
class DifferentialSyncronisationHandlerTest(unittest.TestCase):
    """
    Tests for the DifferentialSynchronisationProtocol.
    """
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = mock.MockDifferentialSyncronisationHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_onPresence(self):
        # User [email protected] joins
        self.protocol.mock_text['test-node'] = 'foo'
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))
        self.assertEqual({u'test-node': set([u'*****@*****.**'])},
                         self.protocol.node_participants)
        self.assertEqual({u'*****@*****.**': set([u'test-node'])},
                         self.protocol.participant_nodes)
        self.assertEqual({u'test-node': 'foo'}, self.protocol.shadow_copies)

        # Another user joins:
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # The new user should receive a user-joined for the existing user.
        message = self.stub.output[-1]
        self.assertEqual(
            "<message to='*****@*****.**'>" +
            "<x xmlns='http://jarn.com/ns/collaborative-editing'>" +
            "<item action='user-joined' node='test-node' user='******'/>"
            + "</x></message>", message.toXml())

        #The already active user should receive a user-joined
        message = self.stub.output[-2]
        self.assertEqual(
            "<message to='*****@*****.**'>" +
            "<x xmlns='http://jarn.com/ns/collaborative-editing'>" +
            "<item action='user-joined' node='test-node' user='******'/>"
            + "</x></message>", message.toXml())

        # Then [email protected] leaves the node.

        xml = """<presence from='*****@*****.**' to='example.com'
                    type='unavailable'/>"""
        self.stub.send(parseXml(xml))

        # Make sure the [email protected] is indeed gone,
        self.assertEqual({u'test-node': set([u'*****@*****.**'])},
                         self.protocol.node_participants)
        self.assertEqual({u'*****@*****.**': set([u'test-node'])},
                         self.protocol.participant_nodes)

        # test2@example should have received a notification
        message = self.stub.output[-1]
        self.assertEqual(
            "<message to='*****@*****.**'>" +
            "<x xmlns='http://jarn.com/ns/collaborative-editing'>" +
            "<item action='user-left' node='test-node' user='******'/>"
            + "</x></message>", message.toXml())

        # Then [email protected] leaves as well.
        xml = """<presence from='*****@*****.**' to='example.com'
                    type='unavailable'/>"""
        self.stub.send(parseXml(xml))

        self.assertEqual({}, self.protocol.node_participants)
        self.assertEqual({}, self.protocol.participant_nodes)
        self.assertEqual({}, self.protocol.shadow_copies)

    def test_getShadowCopyIQ(self):
        # User [email protected] joins
        self.protocol.mock_text['test-node'] = 'foo'
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # And requests the shadow copy of 'test-node'
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                    <shadowcopy xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </iq>"""
        self.stub.send(parseXml(xml))
        response = self.stub.output[-1]
        self.assertEqual(
            "<iq to='*****@*****.**' from='example.com' type='result'>" +
            "<shadowcopy xmlns='http://jarn.com/ns/collaborative-editing' node='test-node'>foo</shadowcopy>"
            + "</iq>", response.toXml())

        # Requesting the shadow copy of an non-existent node should result in Unauthorized error
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                    <shadowcopy xmlns='http://jarn.com/ns/collaborative-editing'
                           node='unknown-node'/>
                 </iq>"""
        self.stub.send(parseXml(xml))
        response = self.stub.output[-1]
        self.assertEqual(
            "<iq to='*****@*****.**' from='example.com' type='error'>" +
            "<error xmlns='http://jarn.com/ns/collaborative-editing'>Unauthorized</error></iq>",
            response.toXml())

        # User [email protected] who has not sent a presence to the component should not be able
        # to retrieve the text.
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                 <shadowcopy xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </iq>"""
        self.stub.send(parseXml(xml))
        response = self.stub.output[-1]
        self.assertEqual(
            "<iq to='*****@*****.**' from='example.com' type='error'>" +
            "<error xmlns='http://jarn.com/ns/collaborative-editing'>Unauthorized</error></iq>",
            response.toXml())

    def test_onPatch(self):
        # 'foo' is the initial text. foo and bar present.
        self.protocol.mock_text['test-node'] = 'foo'
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # bar sends a patch changing the text to 'foobar'.
        xml = """<iq from='*****@*****.**' to='example.com' id='id_1' type='set'>
                    <patch xmlns='http://jarn.com/ns/collaborative-editing'
                        node='test-node'>@@ -1,3 +1,6 @@\n foo\n+bar\n</patch>
                </iq>"""
        self.stub.send(parseXml(xml))

        # He should have received a 'success' reply
        response = self.stub.output[-2]
        self.assertEqual(
            "<iq to='*****@*****.**' from='example.com' id='id_1' type='result'>"
            +
            "<success xmlns='http://jarn.com/ns/collaborative-editing'/></iq>",
            response.toXml())

        # foo receives the same patch.
        iq = self.stub.output[-1]
        self.assertEqual(
            "<iq to='*****@*****.**' type='set' id='H_0'>" +
            "<patch xmlns='http://jarn.com/ns/collaborative-editing' " +
            "node='test-node' user='******'>@@ -1,3 +1,6 @@\n foo\n+bar\n</patch></iq>",
            iq.toXml())

        # The shadow copy is 'foobar'
        self.assertEqual(u'foobar', self.protocol.shadow_copies['test-node'])

    def test_interfaceIDisco(self):
        """
        The handler should provice Service Discovery information.
        """
        verify.verifyObject(iwokkel.IDisco, self.protocol)

    def test_getDiscoInfo(self):
        """
        The namespace should be returned as a supported feature.
        """
        def cb(info):
            discoInfo = disco.DiscoInfo()
            for item in info:
                discoInfo.append(item)
            self.assertIn('http://jarn.com/ns/collaborative-editing',
                          discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'), '')
        d.addCallback(cb)
        return d

    def test_getDiscoInfoNode(self):
        """
        The namespace should not be returned for a node.
        """
        def cb(info):
            discoInfo = disco.DiscoInfo()
            self.assertEqual([], info)
            self.assertNotIn('http://jarn.com/ns/collaborative-editing',
                             discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'), 'test')
        d.addCallback(cb)
        return d

    def test_getDiscoItems(self):
        """
        Items are not supported by this handler.
        """
        def cb(items):
            self.assertEquals(0, len(items))

        d = defer.maybeDeferred(self.protocol.getDiscoItems,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'), '')
        d.addCallback(cb)
        return d
示例#32
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.client = FakeClient(self.stub.xmlstream, JID('*****@*****.**'))
     self.service = xmppim.RosterClientProtocol()
     self.service.setHandlerParent(self.client)
示例#33
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = pubsub.PubSubClient()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#34
0
class PingClientProtocolTest(unittest.TestCase):
    """
    Tests for L{ping.PingClientProtocol}.
    """
    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = ping.PingClientProtocol()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_ping(self):
        """
        Pinging a service should fire a deferred with None
        """
        def cb(result):
            self.assertIdentical(None, result)

        d = self.protocol.ping(JID("example.com"))
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u'example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.assertEqual('urn:xmpp:ping', iq.ping.uri)

        response = toResponse(iq, u'result')
        self.stub.send(response)

        return d

    def test_pingWithSender(self):
        """
        Pinging a service with a sender address should include that address.
        """
        d = self.protocol.ping(JID("example.com"),
                               sender=JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEqual(u'*****@*****.**', iq.getAttribute(u'from'))

        response = toResponse(iq, u'result')
        self.stub.send(response)

        return d

    def test_pingNotSupported(self):
        """
        Pinging a service should fire a deferred with None if not supported.
        """
        def cb(result):
            self.assertIdentical(None, result)

        d = self.protocol.ping(JID("example.com"))
        d.addCallback(cb)

        iq = self.stub.output[-1]

        exc = StanzaError('service-unavailable')
        response = exc.toResponse(iq)
        self.stub.send(response)

        return d

    def test_pingStanzaError(self):
        """
        Pinging a service should errback a deferred on other (stanza) errors.
        """
        def cb(exc):
            self.assertEquals('item-not-found', exc.condition)

        d = self.protocol.ping(JID("example.com"))
        self.assertFailure(d, StanzaError)
        d.addCallback(cb)

        iq = self.stub.output[-1]

        exc = StanzaError('item-not-found')
        response = exc.toResponse(iq)
        self.stub.send(response)

        return d
示例#35
0
class PubSubCommandsProtocolTest(unittest.TestCase):
    """
    """
    def setUp(self):
        self.stub = XmlStreamStub()
        self.stub.xmlstream.factory = FactoryWithJID()
        self.protocol = protocols.PubSubHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_getNodes(self):
        d = self.protocol.getNodes(JID(u'pubsub.example.com'), u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_ITEMS, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_ITEMS, u'query'))
        query[u'node'] = u'foo_node'
        child1 = query.addElement('item')
        child1['node'] = 'foodoo_child_1'
        child1['name'] = 'Foodoo child one'
        child1['jid'] = u'pubsub.example.com'
        child2 = query.addElement('item')
        child2['node'] = 'foodoo_child_2'
        child2['jid'] = u'pubsub.example.com'

        self.stub.send(response)

        def cb(result):
            self.assertEqual([{
                'node': 'foodoo_child_1',
                'jid': u'pubsub.example.com',
                'name': 'Foodoo child one'
            }, {
                'node': 'foodoo_child_2',
                'jid': u'pubsub.example.com'
            }], result)

        d.addCallback(cb)
        return d

    def test_getSubscriptions(self):
        d = self.protocol.getSubscriptions(JID(u'pubsub.example.com'),
                                           u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        subscriptions = response.pubsub.addElement(u'subscriptions')
        subscriptions[u'node'] = u'foo_node'
        subscription1 = subscriptions.addElement(u'subscription')
        subscription1[u'jid'] = u'*****@*****.**'
        subscription1[u'subscription'] = u'unconfigured'
        subscription2 = subscriptions.addElement(u'subscription')
        subscription2[u'jid'] = u'*****@*****.**'
        subscription2[u'subscription'] = u'subscribed'
        subscription2[u'subid'] = u'123-abc'

        self.stub.send(response)

        def cb(result):
            self.assertEqual([(JID(u'*****@*****.**'), u'unconfigured'),
                              (JID(u'*****@*****.**'), u'subscribed')],
                             result)

        d.addCallback(cb)
        return d

    def test_setSubscriptions(self):
        d = self.protocol.setSubscriptions(
            JID(u'pubsub.example.com'), u'foo_node',
            [(JID(u'*****@*****.**'), u'subscribed'),
             (JID(u'*****@*****.**'), u'none')])

        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        subscriptions = iq.pubsub.subscriptions.children
        self.assertEqual(2, len(subscriptions))
        self.assertEqual(u'*****@*****.**', subscriptions[0]['jid'])
        self.assertEqual(u'subscribed', subscriptions[0]['subscription'])
        self.assertEqual(u'*****@*****.**', subscriptions[1]['jid'])
        self.assertEqual(u'none', subscriptions[1]['subscription'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d

    def test_getNodeType(self):
        d = self.protocol.getNodeType(JID(u'pubsub.example.com'), u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_INFO, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_INFO, u'query'))
        query[u'node'] = u'foo_node'
        identity = query.addElement(u'identity')
        identity[u'category'] = u'pubsub'
        identity[u'type'] = u'collection'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(u'collection', result)

        d.addCallback(cb)
        return d

    def test_getDefaultNodeConfiguration(self):
        d = self.protocol.getDefaultNodeConfiguration(
            JID(u'pubsub.example.com'))
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.default is None)

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        default = pubsub.addElement(u'default')
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NS_PUBSUB_NODE_CONFIG)
        form_title = data_form.Field(u'text-single',
                                     var=u'pubsub#title',
                                     label=u'A friendly name for the node')
        field_subscr = data_form.Field(u'boolean',
                                       var=u'pubsub#subscribe',
                                       label=u'Whether to allow subscriptions',
                                       value=u'1')
        form.addField(form_type)
        form.addField(form_title)
        form.addField(field_subscr)
        default.addContent(form.toElement())
        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                {
                    u'pubsub#subscribe': u'true',
                    u'pubsub#title': None
                }, result)

        d.addCallback(cb)
        return d

    def test_getNodeConfiguration(self):
        d = self.protocol.getNodeConfiguration(JID(u'pubsub.example.com'),
                                               u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.configure is None)
        self.assertEqual(u'foo_node', iq.pubsub.configure[u'node'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        configure = pubsub.addElement(u'configure')
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NS_PUBSUB_NODE_CONFIG)
        form_title = data_form.Field(u'text-single',
                                     var=u'pubsub#title',
                                     label=u'A friendly name for the node')

        field_subscr = data_form.Field(u'boolean',
                                       var=u'pubsub#subscribe',
                                       label=u'Whether to allow subscriptions',
                                       value=u'1')
        form.addField(form_type)
        form.addField(form_title)
        form.addField(field_subscr)
        configure.addContent(form.toElement())

        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                {
                    u'pubsub#subscribe': u'true',
                    u'pubsub#title': None
                }, result)

        d.addCallback(cb)
        return d

    def test_configureNode(self):
        d = self.protocol.configureNode(JID(u'pubsub.example.com'),
                                        u'foo_node',
                                        {u'pubsub#collection': u'bar_node'})
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.configure is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.configure.getAttribute(u'node'))
        self.failIf(iq.pubsub.configure.x is None)
        x = iq.pubsub.configure.x
        self.assertEqual(data_form.NS_X_DATA, x.uri)
        self.assertEqual(u'submit', x.getAttribute('type'))
        self.assertEqual(2, len(x.children))
        fields = x.children
        self.failIf(fields[0].value is None)
        self.assertEqual([protocols.NS_PUBSUB_NODE_CONFIG],
                         fields[0].value.children)
        self.assertEqual(u'pubsub#collection', fields[1].getAttribute(u'var'))
        self.failIf(fields[1].value is None)
        self.assertEqual([u'bar_node'], fields[1].value.children)
        self.assertEqual(fields[0].value.children,
                         [protocols.NS_PUBSUB_NODE_CONFIG])

        response = toResponse(iq, u'result')
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d

    def test_associateNodeToCollection(self):
        d = self.protocol.associateNodeWithCollection(
            JID(u'pubsub.example.com'), u'foo_node', u'collection_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.collection is None)
        self.assertEqual('collection_node', iq.pubsub.collection['node'])
        self.failIf(iq.pubsub.collection.associate is None)
        self.assertEqual('foo_node', iq.pubsub.collection.associate['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
         self.protocol.xmlstream.factory.authenticator.jid.full()

        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d

    def test_getAffiliations(self):
        d = self.protocol.getAffiliations(JID(u'pubsub.example.com'),
                                          u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node', iq.pubsub.affiliations['node'])
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))

        affiliations = pubsub.addElement(u'affiliations')
        affiliations['node'] = u'foo_node'
        user = affiliations.addElement(u'affiliation')
        user['jid'] = '*****@*****.**'
        user['affiliation'] = 'owner'
        foo = affiliations.addElement(u'affiliation')
        foo['jid'] = '*****@*****.**'
        foo['affiliation'] = 'publisher'
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result, [(JID(u'*****@*****.**'), 'owner'),
                                      (JID(u'*****@*****.**'), 'publisher')])

        d.addCallback(cb)
        return d

    def test_modifyAffiliations(self):
        d = self.protocol.modifyAffiliations(
            JID(u'pubsub.example.com'), u'foo_node',
            [(JID(u'*****@*****.**'), 'none')])
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node', iq.pubsub.affiliations['node'])
        affiliation = iq.pubsub.affiliations.affiliation
        self.assertEqual('*****@*****.**', affiliation['jid'])
        self.assertEqual('none', affiliation['affiliation'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result, True)

        d.addCallback(cb)
        return d
示例#36
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.stub.xmlstream.factory = FactoryWithJID()
     self.protocol = protocols.PubSubHandler()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
class DifferentialSyncronisationHandlerTest(unittest.TestCase):
    """
    Tests for the DifferentialSynchronisationProtocol.
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = mock.MockDifferentialSyncronisationHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_onPresence(self):
        # User [email protected] joins
        self.protocol.mock_text['test-node'] = 'foo'
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))
        self.assertEqual({u'test-node': set([u'*****@*****.**'])},
                         self.protocol.node_participants)
        self.assertEqual({u'*****@*****.**': set([u'test-node'])},
                          self.protocol.participant_nodes)
        self.assertEqual({u'test-node': 'foo'},
                         self.protocol.shadow_copies)

        # Another user joins:
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # The new user should receive a user-joined for the existing user.
        message = self.stub.output[-1]
        self.assertEqual(
            "<message to='*****@*****.**'>" +
            "<x xmlns='http://jarn.com/ns/collaborative-editing'>" +
            "<item action='user-joined' node='test-node' user='******'/>" +
            "</x></message>", message.toXml())

        #The already active user should receive a user-joined
        message = self.stub.output[-2]
        self.assertEqual(
            "<message to='*****@*****.**'>" +
            "<x xmlns='http://jarn.com/ns/collaborative-editing'>" +
            "<item action='user-joined' node='test-node' user='******'/>" +
            "</x></message>", message.toXml())

        # Then [email protected] leaves the node.

        xml = """<presence from='*****@*****.**' to='example.com'
                    type='unavailable'/>"""
        self.stub.send(parseXml(xml))

        # Make sure the [email protected] is indeed gone,
        self.assertEqual({u'test-node': set([u'*****@*****.**'])},
                         self.protocol.node_participants)
        self.assertEqual({u'*****@*****.**': set([u'test-node'])},
                         self.protocol.participant_nodes)

        # test2@example should have received a notification
        message = self.stub.output[-1]
        self.assertEqual(
            "<message to='*****@*****.**'>" +
            "<x xmlns='http://jarn.com/ns/collaborative-editing'>" +
            "<item action='user-left' node='test-node' user='******'/>" +
            "</x></message>", message.toXml())

        # Then [email protected] leaves as well.
        xml = """<presence from='*****@*****.**' to='example.com'
                    type='unavailable'/>"""
        self.stub.send(parseXml(xml))

        self.assertEqual({}, self.protocol.node_participants)
        self.assertEqual({}, self.protocol.participant_nodes)
        self.assertEqual({}, self.protocol.shadow_copies)

    def test_getShadowCopyIQ(self):
        # User [email protected] joins
        self.protocol.mock_text['test-node'] = 'foo'
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # And requests the shadow copy of 'test-node'
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                    <shadowcopy xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </iq>"""
        self.stub.send(parseXml(xml))
        response = self.stub.output[-1]
        self.assertEqual("<iq to='*****@*****.**' from='example.com' type='result'>" +
                         "<shadowcopy xmlns='http://jarn.com/ns/collaborative-editing' node='test-node'>foo</shadowcopy>" +
                         "</iq>", response.toXml())

        # Requesting the shadow copy of an non-existent node should result in Unauthorized error
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                    <shadowcopy xmlns='http://jarn.com/ns/collaborative-editing'
                           node='unknown-node'/>
                 </iq>"""
        self.stub.send(parseXml(xml))
        response = self.stub.output[-1]
        self.assertEqual("<iq to='*****@*****.**' from='example.com' type='error'>" +
                         "<error xmlns='http://jarn.com/ns/collaborative-editing'>Unauthorized</error></iq>",
                         response.toXml())

        # User [email protected] who has not sent a presence to the component should not be able
        # to retrieve the text.
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                 <shadowcopy xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </iq>"""
        self.stub.send(parseXml(xml))
        response = self.stub.output[-1]
        self.assertEqual("<iq to='*****@*****.**' from='example.com' type='error'>" +
                         "<error xmlns='http://jarn.com/ns/collaborative-editing'>Unauthorized</error></iq>",
                         response.toXml())

    def test_onPatch(self):
        # 'foo' is the initial text. foo and bar present.
        self.protocol.mock_text['test-node'] = 'foo'
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))
        xml = """<presence from='*****@*****.**' to='example.com'>
                    <query xmlns='http://jarn.com/ns/collaborative-editing'
                           node='test-node'/>
                 </presence>"""
        self.stub.send(parseXml(xml))

        # bar sends a patch changing the text to 'foobar'.
        xml = """<iq from='*****@*****.**' to='example.com' id='id_1' type='set'>
                    <patch xmlns='http://jarn.com/ns/collaborative-editing'
                        node='test-node'>@@ -1,3 +1,6 @@\n foo\n+bar\n</patch>
                </iq>"""
        self.stub.send(parseXml(xml))

        # He should have received a 'success' reply
        response = self.stub.output[-2]
        self.assertEqual(
            "<iq to='*****@*****.**' from='example.com' id='id_1' type='result'>" +
            "<success xmlns='http://jarn.com/ns/collaborative-editing'/></iq>", 
            response.toXml())

        # foo receives the same patch.
        iq = self.stub.output[-1]
        self.assertEqual(
            "<iq to='*****@*****.**' type='set' id='H_0'>" +
            "<patch xmlns='http://jarn.com/ns/collaborative-editing' " +
            "node='test-node' user='******'>@@ -1,3 +1,6 @@\n foo\n+bar\n</patch></iq>",
            iq.toXml())

        # The shadow copy is 'foobar'
        self.assertEqual(u'foobar', self.protocol.shadow_copies['test-node'])

    def test_interfaceIDisco(self):
        """
        The handler should provice Service Discovery information.
        """
        verify.verifyObject(iwokkel.IDisco, self.protocol)

    def test_getDiscoInfo(self):
        """
        The namespace should be returned as a supported feature.
        """

        def cb(info):
            discoInfo = disco.DiscoInfo()
            for item in info:
                discoInfo.append(item)
            self.assertIn('http://jarn.com/ns/collaborative-editing',
                          discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'),
                                '')
        d.addCallback(cb)
        return d

    def test_getDiscoInfoNode(self):
        """
        The namespace should not be returned for a node.
        """

        def cb(info):
            discoInfo = disco.DiscoInfo()
            self.assertEqual([], info)
            self.assertNotIn('http://jarn.com/ns/collaborative-editing',
                             discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'),
                                'test')
        d.addCallback(cb)
        return d

    def test_getDiscoItems(self):
        """
        Items are not supported by this handler.
        """

        def cb(items):
            self.assertEquals(0, len(items))

        d = defer.maybeDeferred(self.protocol.getDiscoItems,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'),
                                '')
        d.addCallback(cb)
        return d
示例#38
0
class PubSubCommandsProtocolTest(unittest.TestCase):
    """
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.stub.xmlstream.factory = FactoryWithJID()
        self.protocol = protocols.PubSubHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_getNodes(self):
        d = self.protocol.getNodes(JID(u'pubsub.example.com'),
                                   u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_ITEMS, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_ITEMS, u'query'))
        query[u'node'] = u'foo_node'
        child1 = query.addElement('item')
        child1['node'] = 'foodoo_child_1'
        child1['name'] = 'Foodoo child one'
        child1['jid'] = u'pubsub.example.com'
        child2 = query.addElement('item')
        child2['node'] = 'foodoo_child_2'
        child2['jid'] = u'pubsub.example.com'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                [{'node': 'foodoo_child_1',
                  'jid': u'pubsub.example.com',
                  'name': 'Foodoo child one'},
                 {'node': 'foodoo_child_2',
                  'jid': u'pubsub.example.com'}],
                 result)

        d.addCallback(cb)
        return d

    def test_getSubscriptions(self):
        d = self.protocol.getSubscriptions(JID(u'pubsub.example.com'),
                                           u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        subscriptions = response.pubsub.addElement(u'subscriptions')
        subscriptions[u'node'] = u'foo_node'
        subscription1 = subscriptions.addElement(u'subscription')
        subscription1[u'jid'] = u'*****@*****.**'
        subscription1[u'subscription'] = u'unconfigured'
        subscription2 = subscriptions.addElement(u'subscription')
        subscription2[u'jid'] = u'*****@*****.**'
        subscription2[u'subscription'] = u'subscribed'
        subscription2[u'subid'] = u'123-abc'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                [(JID(u'*****@*****.**'), u'unconfigured'),
                 (JID(u'*****@*****.**'), u'subscribed')],
                 result)

        d.addCallback(cb)
        return d

    def test_setSubscriptions(self):
        d = self.protocol.setSubscriptions(
            JID(u'pubsub.example.com'),
            u'foo_node',
            [(JID(u'*****@*****.**'), u'subscribed'),
             (JID(u'*****@*****.**'), u'none')])

        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.subscriptions is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.subscriptions.getAttribute(u'node'))
        subscriptions = iq.pubsub.subscriptions.children
        self.assertEqual(2, len(subscriptions))
        self.assertEqual(u'*****@*****.**', subscriptions[0]['jid'])
        self.assertEqual(u'subscribed', subscriptions[0]['subscription'])
        self.assertEqual(u'*****@*****.**', subscriptions[1]['jid'])
        self.assertEqual(u'none', subscriptions[1]['subscription'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d

    def test_getNodeType(self):
        d = self.protocol.getNodeType(JID(u'pubsub.example.com'),
                                      u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.query is None)
        self.assertEqual(protocols.NS_DISCO_INFO, iq.query.uri)
        self.assertEqual(u'foo_node', iq.query['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        query = response.addElement((protocols.NS_DISCO_INFO, u'query'))
        query[u'node'] = u'foo_node'
        identity = query.addElement(u'identity')
        identity[u'category'] = u'pubsub'
        identity[u'type'] = u'collection'

        self.stub.send(response)

        def cb(result):
            self.assertEqual(u'collection', result)

        d.addCallback(cb)
        return d

    def test_getDefaultNodeConfiguration(self):
        d = self.protocol.getDefaultNodeConfiguration(
            JID(u'pubsub.example.com'))
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.default is None)

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        default = pubsub.addElement(u'default')
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NS_PUBSUB_NODE_CONFIG)
        form_title = data_form.Field(u'text-single',
                                     var=u'pubsub#title',
                                     label=u'A friendly name for the node')
        field_subscr = data_form.Field(u'boolean',
                                       var=u'pubsub#subscribe',
                                       label=u'Whether to allow subscriptions',
                                       value=u'1')
        form.addField(form_type)
        form.addField(form_title)
        form.addField(field_subscr)
        default.addContent(form.toElement())
        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                {u'pubsub#subscribe': u'true',
                 u'pubsub#title': None},
                result)

        d.addCallback(cb)
        return d

    def test_getNodeConfiguration(self):
        d = self.protocol.getNodeConfiguration(
            JID(u'pubsub.example.com'), u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.configure is None)
        self.assertEqual(u'foo_node', iq.pubsub.configure[u'node'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))
        configure = pubsub.addElement(u'configure')
        form = data_form.Form(u'form')
        form_type = data_form.Field(u'hidden',
                                    var=u'FORM_TYPE',
                                    value=protocols.NS_PUBSUB_NODE_CONFIG)
        form_title = data_form.Field(u'text-single',
                                     var=u'pubsub#title',
                                     label=u'A friendly name for the node')

        field_subscr = data_form.Field(u'boolean',
                                       var=u'pubsub#subscribe',
                                       label=u'Whether to allow subscriptions',
                                       value=u'1')
        form.addField(form_type)
        form.addField(form_title)
        form.addField(field_subscr)
        configure.addContent(form.toElement())

        self.stub.send(response)

        def cb(result):
            self.assertEqual(
                {u'pubsub#subscribe': u'true',
                 u'pubsub#title': None},
                result)

        d.addCallback(cb)
        return d

    def test_configureNode(self):
        d = self.protocol.configureNode(JID(u'pubsub.example.com'),
                                        u'foo_node',
                                        {u'pubsub#collection': u'bar_node'})
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.configure is None)
        self.assertEqual(u'foo_node',
                         iq.pubsub.configure.getAttribute(u'node'))
        self.failIf(iq.pubsub.configure.x is None)
        x = iq.pubsub.configure.x
        self.assertEqual(data_form.NS_X_DATA, x.uri)
        self.assertEqual(u'submit', x.getAttribute('type'))
        self.assertEqual(2, len(x.children))
        fields = x.children
        self.failIf(fields[0].value is None)
        self.assertEqual([protocols.NS_PUBSUB_NODE_CONFIG],
                         fields[0].value.children)
        self.assertEqual(u'pubsub#collection', fields[1].getAttribute(u'var'))
        self.failIf(fields[1].value is None)
        self.assertEqual([u'bar_node'], fields[1].value.children)
        self.assertEqual(fields[0].value.children,
            [protocols.NS_PUBSUB_NODE_CONFIG])

        response = toResponse(iq, u'result')
        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d

    def test_associateNodeToCollection(self):
        d = self.protocol.associateNodeWithCollection(
            JID(u'pubsub.example.com'),
            u'foo_node',
            u'collection_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.collection is None)
        self.assertEqual('collection_node',
                         iq.pubsub.collection['node'])
        self.failIf(iq.pubsub.collection.associate is None)
        self.assertEqual('foo_node',
                         iq.pubsub.collection.associate['node'])

        response = toResponse(iq, u'result')
        response['to'] = \
         self.protocol.xmlstream.factory.authenticator.jid.full()

        self.stub.send(response)

        def cb(result):
            self.assertEqual(True, result)

        d.addCallback(cb)
        return d

    def test_getAffiliations(self):
        d = self.protocol.getAffiliations(JID(u'pubsub.example.com'),
                                          u'foo_node')
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'get', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node',
                         iq.pubsub.affiliations['node'])
        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        pubsub = response.addElement((protocols.NS_PUBSUB_OWNER, u'pubsub'))

        affiliations = pubsub.addElement(u'affiliations')
        affiliations['node'] = u'foo_node'
        user = affiliations.addElement(u'affiliation')
        user['jid'] = '*****@*****.**'
        user['affiliation'] = 'owner'
        foo = affiliations.addElement(u'affiliation')
        foo['jid'] = '*****@*****.**'
        foo['affiliation'] = 'publisher'
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result,
            [(JID(u'*****@*****.**'), 'owner'),
             (JID(u'*****@*****.**'), 'publisher')])

        d.addCallback(cb)
        return d

    def test_modifyAffiliations(self):
        d = self.protocol.modifyAffiliations(JID(u'pubsub.example.com'),
            u'foo_node', [(JID(u'*****@*****.**'), 'none')])
        iq = self.stub.output[-1]
        self.assertEqual(u'pubsub.example.com', iq.getAttribute(u'to'))
        self.assertEqual(u'set', iq.getAttribute(u'type'))
        self.failIf(iq.pubsub is None)
        self.assertEqual(protocols.NS_PUBSUB_OWNER, iq.pubsub.uri)
        self.failIf(iq.pubsub.affiliations is None)
        self.assertEqual('foo_node',
                         iq.pubsub.affiliations['node'])
        affiliation = iq.pubsub.affiliations.affiliation
        self.assertEqual('*****@*****.**', affiliation['jid'])
        self.assertEqual('none', affiliation['affiliation'])

        response = toResponse(iq, u'result')
        response['to'] = \
            self.protocol.xmlstream.factory.authenticator.jid.full()
        self.stub.send(response)

        def cb(result):
            self.assertEqual(result, True)

        d.addCallback(cb)
        return d
示例#39
0
class DiscoClientProtocolTest(unittest.TestCase):
    """
    Tests for L{disco.DiscoClientProtocol}.
    """

    def setUp(self):
        """
        Set up stub and protocol for testing.
        """
        self.stub = XmlStreamStub()
        self.protocol = disco.DiscoClientProtocol()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()

    def test_requestItems(self):
        """
        Test request sent out by C{requestItems} and parsing of response.
        """

        def cb(items):
            items = list(items)
            self.assertEqual(2, len(items))
            self.assertEqual(JID(u"test.example.org"), items[0].entity)

        d = self.protocol.requestItems(JID(u"example.org"), u"foo")
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u"example.org", iq.getAttribute(u"to"))
        self.assertEqual(u"get", iq.getAttribute(u"type"))
        self.assertEqual(u"foo", iq.query.getAttribute(u"node"))
        self.assertEqual(NS_DISCO_ITEMS, iq.query.uri)

        response = toResponse(iq, u"result")
        query = response.addElement((NS_DISCO_ITEMS, u"query"))

        element = query.addElement(u"item")
        element[u"jid"] = u"test.example.org"
        element[u"node"] = u"music"
        element[u"name"] = u"Music from the time of Shakespeare"

        element = query.addElement(u"item")
        element[u"jid"] = u"test2.example.org"

        self.stub.send(response)
        return d

    def test_requestItemsFrom(self):
        """
        A disco items request can be sent with an explicit sender address.
        """
        d = self.protocol.requestItems(JID(u"example.org"), sender=JID(u"test.example.org"))

        iq = self.stub.output[-1]
        self.assertEqual(u"test.example.org", iq.getAttribute(u"from"))

        response = toResponse(iq, u"result")
        response.addElement((NS_DISCO_ITEMS, u"query"))
        self.stub.send(response)

        return d

    def test_requestInfo(self):
        """
        Test request sent out by C{requestInfo} and parsing of response.
        """

        def cb(info):
            self.assertIn((u"conference", u"text"), info.identities)
            self.assertIn(u"http://jabber.org/protocol/disco#info", info.features)
            self.assertIn(u"http://jabber.org/protocol/muc", info.features)

        d = self.protocol.requestInfo(JID(u"example.org"), "foo")
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEqual(u"example.org", iq.getAttribute(u"to"))
        self.assertEqual(u"get", iq.getAttribute(u"type"))
        self.assertEqual(u"foo", iq.query.getAttribute(u"node"))
        self.assertEqual(NS_DISCO_INFO, iq.query.uri)

        response = toResponse(iq, u"result")
        query = response.addElement((NS_DISCO_INFO, u"query"))

        element = query.addElement(u"identity")
        element[u"category"] = u"conference"  # required
        element[u"type"] = u"text"  # required
        element[u"name"] = u"Romeo and Juliet, Act II, Scene II"  # optional

        element = query.addElement("feature")
        element[u"var"] = u"http://jabber.org/protocol/disco#info"  # required

        element = query.addElement(u"feature")
        element[u"var"] = u"http://jabber.org/protocol/muc"

        self.stub.send(response)
        return d

    def test_requestInfoFrom(self):
        """
        A disco info request can be sent with an explicit sender address.
        """
        d = self.protocol.requestInfo(JID(u"example.org"), sender=JID(u"test.example.org"))

        iq = self.stub.output[-1]
        self.assertEqual(u"test.example.org", iq.getAttribute(u"from"))

        response = toResponse(iq, u"result")
        response.addElement((NS_DISCO_INFO, u"query"))
        self.stub.send(response)

        return d
示例#40
0
class PingHandlerTest(unittest.TestCase):
    """
    Tests for L{ping.PingHandler}.
    """

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = ping.PingHandler()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()


    def test_onPing(self):
        """
        A ping should have a simple result response.
        """
        xml = """<iq from='*****@*****.**' to='example.com' type='get'>
                   <ping xmlns='urn:xmpp:ping'/>
                 </iq>"""
        self.stub.send(parseXml(xml))

        response = self.stub.output[-1]
        self.assertEquals('example.com', response.getAttribute('from'))
        self.assertEquals('*****@*****.**', response.getAttribute('to'))
        self.assertEquals('result', response.getAttribute('type'))


    def test_interfaceIDisco(self):
        """
        The ping handler should provice Service Discovery information.
        """
        verify.verifyObject(iwokkel.IDisco, self.protocol)


    def test_getDiscoInfo(self):
        """
        The ping namespace should be returned as a supported feature.
        """
        def cb(info):
            discoInfo = disco.DiscoInfo()
            for item in info:
                discoInfo.append(item)
            self.assertIn('urn:xmpp:ping', discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'),
                                '')
        d.addCallback(cb)
        return d


    def test_getDiscoInfoNode(self):
        """
        The ping namespace should not be returned for a node.
        """
        def cb(info):
            discoInfo = disco.DiscoInfo()
            for item in info:
                discoInfo.append(item)
            self.assertNotIn('urn:xmpp:ping', discoInfo.features)

        d = defer.maybeDeferred(self.protocol.getDiscoInfo,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'),
                                'test')
        d.addCallback(cb)
        return d


    def test_getDiscoItems(self):
        """
        Items are not supported by this handler, so an empty list is expected.
        """
        def cb(items):
            self.assertEquals(0, len(items))

        d = defer.maybeDeferred(self.protocol.getDiscoItems,
                                JID('[email protected]/home'),
                                JID('pubsub.example.org'),
                                '')
        d.addCallback(cb)
        return d
示例#41
0
class PubSubClientTest(unittest.TestCase):
    timeout = 2

    def setUp(self):
        self.stub = XmlStreamStub()
        self.protocol = pubsub.PubSubClient()
        self.protocol.xmlstream = self.stub.xmlstream
        self.protocol.connectionInitialized()


    def test_interface(self):
        """
        Do instances of L{pubsub.PubSubClient} provide L{iwokkel.IPubSubClient}?
        """
        verify.verifyObject(iwokkel.IPubSubClient, self.protocol)


    def test_eventItems(self):
        """
        Test receiving an items event resulting in a call to itemsReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('items')
        items['node'] = 'test'
        item1 = items.addElement('item')
        item1['id'] = 'item1'
        item2 = items.addElement('retract')
        item2['id'] = 'item2'
        item3 = items.addElement('item')
        item3['id'] = 'item3'

        def itemsReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)
            self.assertEquals([item1, item2, item3], event.items)

        d, self.protocol.itemsReceived = calledAsync(itemsReceived)
        self.stub.send(message)
        return d


    def test_eventItemsCollection(self):
        """
        Test receiving an items event resulting in a call to itemsReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('items')
        items['node'] = 'test'

        headers = shim.Headers([('Collection', 'collection')])
        message.addChild(headers)

        def itemsReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)
            self.assertEquals({'Collection': ['collection']}, event.headers)

        d, self.protocol.itemsReceived = calledAsync(itemsReceived)
        self.stub.send(message)
        return d


    def test_event_delete(self):
        """
        Test receiving a delete event resulting in a call to deleteReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('delete')
        items['node'] = 'test'

        def deleteReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)

        d, self.protocol.deleteReceived = calledAsync(deleteReceived)
        self.stub.send(message)
        return d


    def test_event_purge(self):
        """
        Test receiving a purge event resulting in a call to purgeReceived.
        """
        message = domish.Element((None, 'message'))
        message['from'] = 'pubsub.example.org'
        message['to'] = '[email protected]/home'
        event = message.addElement((NS_PUBSUB_EVENT, 'event'))
        items = event.addElement('purge')
        items['node'] = 'test'

        def purgeReceived(event):
            self.assertEquals(JID('[email protected]/home'), event.recipient)
            self.assertEquals(JID('pubsub.example.org'), event.sender)
            self.assertEquals('test', event.nodeIdentifier)

        d, self.protocol.purgeReceived = calledAsync(purgeReceived)
        self.stub.send(message)
        return d


    def test_createNode(self):
        """
        Test sending create request.
        """

        def cb(nodeIdentifier):
            self.assertEquals('test', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'create', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d


    def test_createNodeInstant(self):
        """
        Test sending create request resulting in an instant node.
        """

        def cb(nodeIdentifier):
            self.assertEquals('test', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'))
        d.addCallback(cb)

        iq = self.stub.output[-1]
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'create', NS_PUBSUB))
        child = children[0]
        self.assertFalse(child.hasAttribute('node'))

        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        create = command.addElement('create')
        create['node'] = 'test'
        self.stub.send(response)
        return d


    def test_createNodeRenamed(self):
        """
        Test sending create request resulting in renamed node.
        """

        def cb(nodeIdentifier):
            self.assertEquals('test2', nodeIdentifier)

        d = self.protocol.createNode(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'create', NS_PUBSUB))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        create = command.addElement('create')
        create['node'] = 'test2'
        self.stub.send(response)
        return d


    def test_deleteNode(self):
        """
        Test sending delete request.
        """

        d = self.protocol.deleteNode(JID('pubsub.example.org'), 'test')

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'delete', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d


    def test_publish(self):
        """
        Test sending publish request.
        """

        item = pubsub.Item()
        d = self.protocol.publish(JID('pubsub.example.org'), 'test', [item])

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'publish', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        items = list(domish.generateElementsQNamed(child.children,
                                                   'item', NS_PUBSUB))
        self.assertEquals(1, len(items))
        self.assertIdentical(item, items[0])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d


    def test_publishNoItems(self):
        """
        Test sending publish request without items.
        """

        d = self.protocol.publish(JID('pubsub.example.org'), 'test')

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'publish', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        self.stub.send(response)
        return d


    def test_subscribe(self):
        """
        Test sending subscription request.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                      JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'subscribe', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('*****@*****.**', child['jid'])

        response = toResponse(iq, 'result')
        pubsub = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = pubsub.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'subscribed'
        self.stub.send(response)
        return d


    def test_subscribePending(self):
        """
        Test sending subscription request that results in a pending
        subscription.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                      JID('*****@*****.**'))

        iq = self.stub.output[-1]
        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = command.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'pending'
        self.stub.send(response)
        self.assertFailure(d, pubsub.SubscriptionPending)
        return d


    def test_subscribeUnconfigured(self):
        """
        Test sending subscription request that results in an unconfigured
        subscription.
        """
        d = self.protocol.subscribe(JID('pubsub.example.org'), 'test',
                                      JID('*****@*****.**'))

        iq = self.stub.output[-1]
        response = toResponse(iq, 'result')
        command = response.addElement((NS_PUBSUB, 'pubsub'))
        subscription = command.addElement('subscription')
        subscription['node'] = 'test'
        subscription['jid'] = '*****@*****.**'
        subscription['subscription'] = 'unconfigured'
        self.stub.send(response)
        self.assertFailure(d, pubsub.SubscriptionUnconfigured)
        return d


    def test_unsubscribe(self):
        """
        Test sending unsubscription request.
        """
        d = self.protocol.unsubscribe(JID('pubsub.example.org'), 'test',
                                      JID('*****@*****.**'))

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('set', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'unsubscribe', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('*****@*****.**', child['jid'])

        self.stub.send(toResponse(iq, 'result'))
        return d


    def test_items(self):
        """
        Test sending items request.
        """
        def cb(items):
            self.assertEquals([], items)

        d = self.protocol.items(JID('pubsub.example.org'), 'test')
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('get', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'items', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])

        response = toResponse(iq, 'result')
        items = response.addElement((NS_PUBSUB, 'pubsub')).addElement('items')
        items['node'] = 'test'

        self.stub.send(response)

        return d


    def test_itemsMaxItems(self):
        """
        Test sending items request, with limit on the number of items.
        """
        def cb(items):
            self.assertEquals(2, len(items))
            self.assertEquals([item1, item2], items)

        d = self.protocol.items(JID('pubsub.example.org'), 'test', maxItems=2)
        d.addCallback(cb)

        iq = self.stub.output[-1]
        self.assertEquals('pubsub.example.org', iq.getAttribute('to'))
        self.assertEquals('get', iq.getAttribute('type'))
        self.assertEquals('pubsub', iq.pubsub.name)
        self.assertEquals(NS_PUBSUB, iq.pubsub.uri)
        children = list(domish.generateElementsQNamed(iq.pubsub.children,
                                                      'items', NS_PUBSUB))
        self.assertEquals(1, len(children))
        child = children[0]
        self.assertEquals('test', child['node'])
        self.assertEquals('2', child['max_items'])

        response = toResponse(iq, 'result')
        items = response.addElement((NS_PUBSUB, 'pubsub')).addElement('items')
        items['node'] = 'test'
        item1 = items.addElement('item')
        item1['id'] = 'item1'
        item2 = items.addElement('item')
        item2['id'] = 'item2'

        self.stub.send(response)

        return d
示例#42
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.protocol = ping.PingClientProtocol()
     self.protocol.xmlstream = self.stub.xmlstream
     self.protocol.connectionInitialized()
示例#43
0
 def setUp(self):
     self.stub = XmlStreamStub()
     self.stub.xmlstream.factory = FactoryWithJID()
     self.vcard = protocols.VCardHandler()
     self.vcard.xmlstream = self.stub.xmlstream
     self.vcard.connectionInitialized()