Changeset 145:216c953d8ecd


Ignore:
Timestamp:
Aug 8, 2011, 1:43:09 PM (9 years ago)
Author:
Ralph Meijer <ralphm@…>
Branch:
wokkel-muc-client-support-24
Message:

Add more tests, remove code redundancy and cleanup variable names.

This adds tests for timeouts in response to joins, nick and presence changes,
error responses from the room JID instead of the occupant JID and receiving
room subject changes.

Location:
wokkel
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • wokkel/muc.py

    r144 r145  
    1010U{XEP-0045<http://www.xmpp.org/extensions/xep-0045.html>}.
    1111"""
    12 import datetime
    1312from dateutil.tz import tzutc
    1413
    1514from zope.interface import implements
    1615
    17 from twisted.internet import defer, reactor
     16from twisted.internet import defer
    1817from twisted.words.protocols.jabber import jid, error, xmlstream
    1918from twisted.words.xish import domish
     
    3938PRESENCE = '/presence'
    4039
    41 GROUPCHAT = MESSAGE +'[@type="groupchat"]/body'
    42 SUBJECT = MESSAGE +'[@type="groupchat"]/subject'
     40GROUPCHAT = MESSAGE +'[@type="groupchat"]'
    4341
    4442DEFER_TIMEOUT = 30 # basic timeout is 30 seconds
     
    263261    def toElement(self):
    264262        """
    265         Returns a L{domish.Element} representing the xml for the history options.
     263        Returns a L{domish.Element} representing the history options.
    266264        """
    267265        element = domish.Element((NS_MUC, 'history'))
     
    315313    @type state: L{int}
    316314
    317     @ivar occupantJID: The JID of the occupant in the room. Generated from roomIdentifier, service, and nick.
     315    @ivar occupantJID: The JID of the occupant in the room. Generated from
     316        roomIdentifier, service, and nick.
    318317    @type occupantJID: L{jid.JID}
    319318    """
     
    460459    timeout = None
    461460
    462     def __init__(self):
    463         XMPPHandler.__init__(self)
    464 
    465         self._rooms = {}
    466         self._deferreds = []
    467 
    468461    presenceTypeParserMap = {
    469462                'error': generic.ErrorStanza,
     
    472465                }
    473466
     467    def __init__(self, reactor=None):
     468        XMPPHandler.__init__(self)
     469
     470        self._rooms = {}
     471        self._deferreds = []
     472
     473        if reactor:
     474            self._reactor = reactor
     475        else:
     476            from twisted.internet import reactor
     477            self._reactor = reactor
     478
     479
    474480    def connectionInitialized(self):
    475481        """
     
    481487        """
    482488        xmppim.BasePresenceProtocol.connectionInitialized(self)
    483 
    484489        self.xmlstream.addObserver(GROUPCHAT, self._onGroupChat)
    485         self.xmlstream.addObserver(SUBJECT, self._onSubject)
    486         # TODO: add history
    487 
    488490        self.initialized()
    489491
     
    502504
    503505
    504     def _getRoom(self, occupantJID):
     506    def _getRoom(self, roomJID):
    505507        """
    506508        Grab a room from the room collection.
     
    511513        @type occupantJID: L{jid.JID}
    512514        """
    513         roomJID = occupantJID.userhostJID()
    514515        return self._rooms.get(roomJID)
    515516
     
    550551            self._userLeavesRoom(occupantJID)
    551552
     553
    552554    def _userLeavesRoom(self, occupantJID):
    553555        # when a user leaves a room we need to update it
    554         room = self._getRoom(occupantJID)
     556        room = self._getRoom(occupantJID.userhostJID())
    555557        if room is None:
    556558            # not in the room yet
     
    576578
    577579        # grab room
    578         room = self._getRoom(occupantJID)
     580        room = self._getRoom(occupantJID.userhostJID())
    579581        if room is None:
    580582            # not in the room yet
     
    600602        A group chat message has been received from a MUC room.
    601603
    602         There are a few event methods that may get called here. receviedGroupChat and receivedHistory
     604        There are a few event methods that may get called here.
     605        L{receivedGroupChat}, L{receivedHistory} or L{receivedHistory}.
    603606        """
    604607        message = GroupChat.fromElement(element)
    605608
    606609        occupantJID = message.sender
    607 
    608610        if not occupantJID:
    609             # need to return an error here XXX
    610611            return
    611612
    612         room = self._getRoom(occupantJID)
     613        roomJID = occupantJID.userhostJID()
     614
     615        room = self._getRoom(roomJID)
    613616        if room is None:
    614617            # not in the room yet
     
    621624            user = None
    622625
    623         if message.delay is None:
     626        if message.subject:
     627            self.receivedSubject(room, user, message.subject)
     628        elif message.delay is None:
    624629            self.receivedGroupChat(room, user, message)
    625630        else:
     
    627632
    628633
    629     def _onSubject(self, msg):
    630         """
    631         A subject has been sent from a MUC room.
    632         """
    633         if not msg.hasAttribute('from'):
    634             return
    635         occupantJID = jid.internJID(msg['from'])
    636 
    637         # grab room
    638         room = self._getRoom(occupantJID)
    639         if room is None:
    640             # not in the room yet
    641             return
    642 
    643         self.receivedSubject(occupantJID, unicode(msg.subject))
    644 
    645 
    646     def _makeTimeStamp(self, stamp=None):
    647         # create a timestamp
    648         if stamp is None:
    649             stamp = datetime.datetime.now()
    650 
    651         return stamp.strftime('%Y%m%dT%H:%M:%S')
    652 
    653 
    654     def _joinedRoom(self, d, prs):
     634    def _joinedRoom(self, presence):
    655635        """
    656636        We have presence that says we joined a room.
    657637        """
    658         occupantJID = jid.internJID(prs['from'])
    659 
    660         # check for errors
    661         if prs.hasAttribute('type') and prs['type'] == 'error':
    662             d.errback(error.exceptionFromStanza(prs))
    663         else:
    664             # change the state of the room
    665             room = self._getRoom(occupantJID)
    666             room.state = 'joined'
    667 
    668             # grab status
    669             status = getattr(prs.x, 'status', None)
    670             if status:
    671                 room.status = status.getAttribute('code', None)
    672 
    673             d.callback(room)
    674 
    675 
    676     def _leftRoom(self, d, prs):
     638        roomJID = presence.sender.userhostJID()
     639
     640        # change the state of the room
     641        room = self._getRoom(roomJID)
     642        room.state = 'joined'
     643
     644        # grab status
     645        if presence.statusCode:
     646            room.status = presence.statusCode
     647
     648        return room
     649
     650
     651    def _leftRoom(self, presence):
    677652        """
    678653        We have presence that says we left a room.
    679654        """
    680         occupantJID = jid.internJID(prs['from'])
    681 
    682         # check for errors
    683         if prs.hasAttribute('type') and prs['type'] == 'error':
    684             d.errback(error.exceptionFromStanza(prs))
    685         else:
    686             # change the state of the room
    687             self._removeRoom(occupantJID)
    688 
    689             d.callback(True)
     655        occupantJID = presence.sender
     656
     657        # change the state of the room
     658        self._removeRoom(occupantJID)
     659
     660        return True
    690661
    691662
     
    785756
    786757
    787     def sendDeferred(self,  obj, timeout):
    788         """
    789         Send data or a domish element, adding a deferred with a timeout.
    790 
    791         @param obj: The object to send over the wire.
    792         @type obj: L{domish.Element} or C{unicode}
    793 
    794         @param timeout: The number of seconds to wait before the deferred is timed out.
     758    def sendDeferred(self, stanza):
     759        """
     760        Send presence stanza, adding a deferred with a timeout.
     761
     762        @param stanza: The presence stanza to send over the wire.
     763        @type stanza: L{generic.Stanza}
     764
     765        @param timeout: The number of seconds to wait before the deferred is
     766            timed out.
    795767        @type timeout: L{int}
    796768
     
    798770        """
    799771        d = defer.Deferred()
    800         self._deferreds.append(d)
    801 
     772
     773        def onResponse(element):
     774            if element.getAttribute('type') == 'error':
     775                d.errback(error.exceptionFromStanza(element))
     776            else:
     777                d.callback(UserPresence.fromElement(element))
    802778
    803779        def onTimeout():
    804             i = 0
    805             for xd in self._deferreds:
    806                 if d == xd:
    807                     self._deferreds.pop(i)
    808                     d.errback(xmlstream.TimeoutError("Timeout waiting for response."))
    809                 i += 1
    810 
    811         call = reactor.callLater(timeout, onTimeout)
     780            d.errback(xmlstream.TimeoutError("Timeout waiting for response."))
     781
     782        call = self._reactor.callLater(DEFER_TIMEOUT, onTimeout)
    812783
    813784        def cancelTimeout(result):
     
    819790        d.addBoth(cancelTimeout)
    820791
    821         self.xmlstream.send(obj)
     792        query = "/presence[@from='%s' or (@from='%s' and @type='error')]" % (
     793                stanza.recipient.full(), stanza.recipient.userhost())
     794        self.xmlstream.addOnetimeObserver(query, onResponse, priority=1)
     795        self.xmlstream.send(stanza.toElement())
    822796        return d
    823797
     
    841815    def getConfigureForm(self, roomJID):
    842816        """
    843         Grab the configuration form from the room. This sends an iq request to the room.
     817        Grab the configuration form from the room.
     818
     819        This sends an iq request to the room.
    844820
    845821        @param roomJID: The bare JID of the room.
     
    876852            presence.history = HistoryOptions(maxstanzas=history)
    877853
    878         d = self.sendDeferred(presence.toElement(), timeout=DEFER_TIMEOUT)
    879 
    880         # add observer for joining the room
    881         query = PRESENCE + u"[@from='%s']" % room.occupantJID
    882         self.xmlstream.addOnetimeObserver(query, self._joinedRoom, 1, d)
    883 
     854        d = self.sendDeferred(presence)
     855        d.addCallback(self._joinedRoom)
    884856        return d
    885857
     
    903875
    904876
    905     def _changed(self, d, occupantJID, prs):
     877    def _changed(self, presence, occupantJID):
    906878        """
    907879        Callback for changing the nick and status.
    908880        """
    909 
    910         status = getattr(prs, 'status', None)
    911         show = getattr(prs, 'show', None)
    912 
    913         room = self._getRoom(occupantJID)
    914 
    915         user = self._changeUserStatus(room, occupantJID, status, show)
    916 
    917         d.callback(room)
     881        room = self._getRoom(occupantJID.userhostJID())
     882        self._changeUserStatus(room, occupantJID, presence.status, presence.show)
     883
     884        return room
    918885
    919886
     
    930897        @type nick: C{unicode}
    931898        """
    932 
    933 
    934899        room = self._getRoom(roomJID)
    935900
     
    939904        # Create presence
    940905        presence = BasicPresence(recipient=room.occupantJID)
    941         d = self.sendDeferred(presence.toElement(), timeout=DEFER_TIMEOUT)
    942 
    943         # Add observer for joining the room
    944         query = PRESENCE+"[@from='%s']" % (room.occupantJID.full())
    945         self.xmlstream.addOnetimeObserver(query, self._changed, 1, d, roomJID)
    946 
     906
     907        d = self.sendDeferred(presence)
     908        d.addCallback(self._changed, room.occupantJID)
    947909        return d
    948910
    949911
    950     def leave(self, occupantJID):
     912    def leave(self, roomJID):
    951913        """
    952914        Leave a MUC room.
     
    954916        See: http://xmpp.org/extensions/xep-0045.html#exit
    955917
    956         @param occupantJID: The Room JID of the room to leave.
    957         @type occupantJID: L{jid.JID}
    958         """
    959         room = self._getRoom(occupantJID)
     918        @param roomJID: The Room JID of the room to leave.
     919        @type roomJID: L{jid.JID}
     920        """
     921        room = self._getRoom(roomJID)
    960922
    961923        presence = xmppim.AvailabilityPresence(recipient=room.occupantJID,
    962924                                               available=False)
    963925
    964         d = self.sendDeferred(presence.toElement(), timeout=DEFER_TIMEOUT)
    965         # add observer for joining the room
    966         query = PRESENCE + u"[@from='%s' and @type='unavailable']" % (room.occupantJID)
    967         self.xmlstream.addOnetimeObserver(query, self._leftRoom, 1, d)
    968 
     926        d = self.sendDeferred(presence)
     927        d.addCallback(self._leftRoom)
    969928        return d
    970929
    971930
    972     def status(self, occupantJID, show=None, status=None):
     931    def status(self, roomJID, show=None, status=None):
    973932        """
    974933        Change user status.
     
    976935        See: http://xmpp.org/extensions/xep-0045.html#changepres
    977936
    978         @param occupantJID: The room jabber/xmpp entity id for the requested configuration form.
    979         @type occupantJID: L{jid.JID}
    980 
    981         @param show: The availability of the entity. Common values are xa, available, etc
     937        @param roomJID: The Room JID of the room.
     938        @type roomJID: L{jid.JID}
     939
     940        @param show: The availability of the entity. Common values are xa,
     941            available, etc
    982942        @type show: C{unicode}
    983943
     
    985945        @type show: C{unicode}
    986946        """
    987         room = self._getRoom(occupantJID)
     947        room = self._getRoom(roomJID)
    988948
    989949        presence = BasicPresence(recipient=room.occupantJID,
    990950                                 show=show, status=status)
    991951
    992         d = self.sendDeferred(presence.toElement(), timeout=DEFER_TIMEOUT)
    993 
    994         # add observer for joining the room
    995         query = PRESENCE + u"[@from='%s']" % room.occupantJID
    996         self.xmlstream.addOnetimeObserver(query, self._changed, 1, d, occupantJID)
    997 
     952        d = self.sendDeferred(presence)
     953        d.addCallback(self._changed, room.occupantJID)
    998954        return d
    999955
     
    11771133        Get an owner list from a room.
    11781134
    1179         @param roomJID: The room jabber/xmpp entity id for the requested member list.
     1135        @param roomJID: The room jabber/xmpp entity id for the requested member
     1136            list.
    11801137        @type roomJID: L{jid.JID}
    11811138        """
     
    11891146        Grab the registration form for a MUC room.
    11901147
    1191         @param room: The room jabber/xmpp entity id for the requested registration form.
     1148        @param room: The room jabber/xmpp entity id for the requested
     1149            registration form.
    11921150        @type room: L{jid.JID}
    11931151        """
  • wokkel/test/test_muc.py

    r144 r145  
    1212
    1313from twisted.trial import unittest
    14 from twisted.internet import defer
     14from twisted.internet import defer, task
    1515from twisted.words.xish import domish, xpath
    1616from twisted.words.protocols.jabber.jid import JID
     17from twisted.words.protocols.jabber.error import StanzaError
     18from twisted.words.protocols.jabber.xmlstream import TimeoutError, toResponse
    1719
    1820from wokkel import data_form, iwokkel, muc
     
    2022from wokkel.test.helpers import XmlStreamStub
    2123
    22 from twisted.words.protocols.jabber.xmlstream import toResponse
    2324
    2425NS_MUC_ADMIN = 'http://jabber.org/protocol/muc#admin'
     
    4041    return d, func
    4142
    42 class MucClientTest(unittest.TestCase):
     43
     44
     45class MUCClientTest(unittest.TestCase):
    4346    timeout = 2
    4447
    4548    def setUp(self):
    4649        self.stub = XmlStreamStub()
    47         self.protocol = muc.MUCClient()
     50        self.clock = task.Clock()
     51        self.protocol = muc.MUCClient(reactor=self.clock)
    4852        self.protocol.xmlstream = self.stub.xmlstream
    4953        self.protocol.connectionInitialized()
     
    102106
    103107
     108    def test_receivedSubject(self):
     109        """
     110        Subject received from a room we're in are passed to receivedSubject.
     111        """
     112        xml = u"""
     113            <message to='%s' from='%s' type='groupchat'>
     114              <subject>test</subject>
     115            </message>
     116        """ % (self.userJID, self.occupantJID)
     117
     118        self._createRoom()
     119
     120        # add user to room
     121        user = muc.User(self.nick)
     122        room = self.protocol._getRoom(self.roomJID)
     123        room.addUser(user)
     124
     125        def receivedSubject(room, user, subject):
     126            self.assertEquals('test', subject, "Wrong group chat message")
     127            self.assertEquals(self.roomIdentifier, room.roomIdentifier,
     128                              'Wrong room name')
     129            self.assertEquals(self.nick, user.nick)
     130
     131        d, self.protocol.receivedSubject = calledAsync(receivedSubject)
     132        self.stub.send(parseXml(xml))
     133        return d
     134
     135
    104136    def test_receivedGroupChat(self):
    105137        """
     
    144176
    145177
    146     def test_joinRoom(self):
     178    def test_join(self):
    147179        """
    148180        Joining a room waits for confirmation, deferred fires room.
     
    155187        d.addCallback(cb)
    156188
    157         prs = self.stub.output[-1]
    158         self.assertEquals('presence', prs.name, "Need to be presence")
    159         self.assertNotIdentical(None, prs.x, 'No muc x element')
     189        element = self.stub.output[-1]
     190        self.assertEquals('presence', element.name, "Need to be presence")
     191        self.assertNotIdentical(None, element.x, 'No muc x element')
    160192
    161193        # send back user presence, they joined
     
    171203
    172204
    173     def test_joinRoomForbidden(self):
    174         """
    175         Client joining a room and getting a forbidden error.
     205    def test_joinForbidden(self):
     206        """
     207        A forbidden error in response to a join errbacks with L{StanzaError}.
    176208        """
    177209
    178210        def cb(error):
    179             self.assertEquals('forbidden', error.value.condition,
     211            self.assertEquals('forbidden', error.condition,
    180212                              'Wrong muc condition')
    181213
    182214        d = self.protocol.join(self.service, self.roomIdentifier, self.nick)
    183         d.addBoth(cb)
    184 
    185         prs = self.stub.output[-1]
    186         self.assertEquals('presence', prs.name, "Need to be presence")
    187         self.assertNotIdentical(None, prs.x, 'No muc x element')
     215        self.assertFailure(d, StanzaError)
     216        d.addCallback(cb)
    188217
    189218        # send back error, forbidden
     
    199228
    200229
    201     def test_joinRoomBadJID(self):
     230    def test_joinForbiddenFromRoomJID(self):
     231        """
     232        An error response to a join sent from the room JID should errback.
     233
     234        Some service implementations send error stanzas from the room JID
     235        instead of the JID the join presence was sent to.
     236        """
     237
     238        d = self.protocol.join(self.service, self.roomIdentifier, self.nick)
     239        self.assertFailure(d, StanzaError)
     240
     241        # send back error, forbidden
     242        xml = u"""
     243            <presence from='%s' type='error'>
     244              <error type='auth'>
     245                <forbidden xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
     246              </error>
     247            </presence>
     248        """ % (self.roomJID)
     249        self.stub.send(parseXml(xml))
     250        return d
     251
     252
     253    def test_joinBadJID(self):
    202254        """
    203255        Client joining a room and getting a jid-malformed error.
     
    205257
    206258        def cb(error):
    207             self.assertEquals('jid-malformed', error.value.condition,
     259            self.assertEquals('jid-malformed', error.condition,
    208260                              'Wrong muc condition')
    209261
    210262        d = self.protocol.join(self.service, self.roomIdentifier, self.nick)
    211         d.addBoth(cb)
    212 
    213         prs = self.stub.output[-1]
    214         self.assertEquals('presence', prs.name, "Need to be presence")
    215         self.assertNotIdentical(None, prs.x, 'No muc x element')
     263        self.assertFailure(d, StanzaError)
     264        d.addCallback(cb)
    216265
    217266        # send back error, bad JID
     
    227276
    228277
    229     def test_partRoom(self):
     278    def test_joinTimeout(self):
     279        """
     280        After not receiving a response to a join, errback with L{TimeoutError}.
     281        """
     282
     283        d = self.protocol.join(self.service, self.roomIdentifier, self.nick)
     284        self.assertFailure(d, TimeoutError)
     285        self.clock.advance(muc.DEFER_TIMEOUT)
     286        return d
     287
     288
     289    def test_leave(self):
    230290        """
    231291        Client leaves a room
     
    235295
    236296        self._createRoom()
    237         d = self.protocol.leave(self.occupantJID)
    238         d.addCallback(cb)
    239 
    240         prs = self.stub.output[-1]
    241 
    242         self.assertEquals('unavailable', prs['type'],
     297        d = self.protocol.leave(self.roomJID)
     298        d.addCallback(cb)
     299
     300        element = self.stub.output[-1]
     301
     302        self.assertEquals('unavailable', element['type'],
    243303                          'Unavailable is not being sent')
    244304
     
    250310
    251311
    252     def test_userPartsRoom(self):
    253         """
    254         An entity leaves the room, a presence of type unavailable is received by the client.
     312    def test_userLeftRoom(self):
     313        """
     314        Unavailable presence from a participant removes it from the room.
    255315        """
    256316
     
    264324        # add user to room
    265325        user = muc.User(self.nick)
    266         room = self.protocol._getRoom(self.occupantJID)
     326        room = self.protocol._getRoom(self.roomJID)
    267327        room.addUser(user)
    268328
    269         def userPresence(room, user):
     329        def userLeftRoom(room, user):
    270330            self.assertEquals(self.roomIdentifier, room.roomIdentifier,
    271331                              'Wrong room name')
    272332            self.assertFalse(room.inRoster(user), 'User in roster')
    273333
    274         d, self.protocol.userLeftRoom = calledAsync(userPresence)
     334        d, self.protocol.userLeftRoom = calledAsync(userLeftRoom)
    275335        self.stub.send(parseXml(xml))
    276336        return d
     
    338398        self.protocol.password(self.occupantJID, 'secret')
    339399
    340         prs = self.stub.output[-1]
     400        element = self.stub.output[-1]
    341401
    342402        self.assertTrue(xpath.matches(
    343403                u"/presence[@to='%s']/x/password"
    344404                    "[text()='secret']" % (self.occupantJID,),
    345                 prs),
     405                element),
    346406            'Wrong presence stanza')
    347407
    348408
    349     def test_historyReceived(self):
     409    def test_receivedHistory(self):
    350410        """
    351411        Receiving history on room join.
     
    362422
    363423
    364         def historyReceived(room, user, message):
     424        def receivedHistory(room, user, message):
    365425            self.assertEquals('test', message.body, "wrong message body")
    366426            stamp = datetime(2002, 10, 13, 23, 58, 37, tzinfo=tzutc())
     
    368428                             'Does not have a history stamp')
    369429
    370         d, self.protocol.receivedHistory = calledAsync(historyReceived)
     430        d, self.protocol.receivedHistory = calledAsync(receivedHistory)
    371431        self.stub.send(parseXml(xml))
    372432        return d
     
    380440        thread = "e0ffe42b28561960c6b12b944a092794b9683a38"
    381441        # create messages
    382         msg = domish.Element((None, 'message'))
    383         msg['to'] = 'testing@example.com'
    384         msg['type'] = 'chat'
    385         msg.addElement('body', None, 'test')
    386         msg.addElement('thread', None, thread)
    387 
    388         archive.append({'stanza': msg,
     442        element = domish.Element((None, 'message'))
     443        element['to'] = 'testing@example.com'
     444        element['type'] = 'chat'
     445        element.addElement('body', None, 'test')
     446        element.addElement('thread', None, thread)
     447
     448        archive.append({'stanza': element,
    389449                        'timestamp': datetime(2002, 10, 13, 23, 58, 37,
    390450                                              tzinfo=tzutc())})
    391451
    392         msg = domish.Element((None, 'message'))
    393         msg['to'] = 'testing2@example.com'
    394         msg['type'] = 'chat'
    395         msg.addElement('body', None, 'yo')
    396         msg.addElement('thread', None, thread)
    397 
    398         archive.append({'stanza': msg,
     452        element = domish.Element((None, 'message'))
     453        element['to'] = 'testing2@example.com'
     454        element['type'] = 'chat'
     455        element.addElement('body', None, 'yo')
     456        element.addElement('thread', None, thread)
     457
     458        archive.append({'stanza': element,
    399459                        'timestamp': datetime(2002, 10, 13, 23, 58, 43,
    400460                                              tzinfo=tzutc())})
     
    404464
    405465        while len(self.stub.output)>0:
    406             m = self.stub.output.pop()
     466            element = self.stub.output.pop()
    407467            # check for delay element
    408             self.assertEquals('message', m.name, 'Wrong stanza')
    409             self.assertTrue(xpath.matches("/message/delay", m), 'Invalid history stanza')
     468            self.assertEquals('message', element.name, 'Wrong stanza')
     469            self.assertTrue(xpath.matches("/message/delay", element),
     470                            'Invalid history stanza')
    410471
    411472
     
    558619
    559620
    560     def test_nickChange(self):
     621    def test_nick(self):
    561622        """
    562623        Send a nick change to the server.
    563624        """
    564         test_nick = 'newNick'
     625        newNick = 'newNick'
    565626
    566627        self._createRoom()
     
    568629        def cb(room):
    569630            self.assertEquals(self.roomIdentifier, room.roomIdentifier)
    570             self.assertEquals(test_nick, room.nick)
    571 
    572         d = self.protocol.nick(self.occupantJID, test_nick)
    573         d.addCallback(cb)
    574 
    575         prs = self.stub.output[-1]
    576         self.assertEquals('presence', prs.name, "Need to be presence")
    577         self.assertNotIdentical(None, prs.x, 'No muc x element')
     631            self.assertEquals(newNick, room.nick)
     632
     633        d = self.protocol.nick(self.roomJID, newNick)
     634        d.addCallback(cb)
     635
     636        element = self.stub.output[-1]
     637        self.assertEquals('presence', element.name, "Need to be presence")
     638        self.assertNotIdentical(None, element.x, 'No muc x element')
    578639
    579640        # send back user presence, nick changed
    580         xml = """
    581             <presence from='%s@%s/%s'>
     641        xml = u"""
     642            <presence from='%s/%s'>
    582643              <x xmlns='http://jabber.org/protocol/muc#user'>
    583644                <item affiliation='member' role='participant'/>
    584645              </x>
    585646            </presence>
    586         """ % (self.roomIdentifier, self.service, test_nick)
     647        """ % (self.roomJID, newNick)
     648        self.stub.send(parseXml(xml))
     649        return d
     650
     651
     652    def test_nickConflict(self):
     653        """
     654        If the server finds the new nick in conflict, the errback is called.
     655        """
     656        newNick = 'newNick'
     657
     658        self._createRoom()
     659
     660        d = self.protocol.nick(self.roomJID, newNick)
     661        self.assertFailure(d, StanzaError)
     662
     663        element = self.stub.output[-1]
     664        self.assertEquals('presence', element.name, "Need to be presence")
     665        self.assertNotIdentical(None, element.x, 'No muc x element')
     666
     667        # send back user presence, nick changed
     668        xml = u"""
     669            <presence from='%s/%s' type='error'>
     670                <x xmlns='http://jabber.org/protocol/muc'/>
     671                <error type='cancel'>
     672                  <conflict xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'/>
     673                </error>
     674            </presence>
     675        """ % (self.roomJID, newNick)
    587676        self.stub.send(parseXml(xml))
    588677        return d
     
    598687            self.assertTrue(give_voice, 'Did not give voice user')
    599688
    600         d = self.protocol.grantVoice(self.occupantJID, nick, sender=self.userJID)
     689        d = self.protocol.grantVoice(self.occupantJID, nick,
     690                                     sender=self.userJID)
    601691        d.addCallback(cb)
    602692
     
    612702
    613703
    614     def test_changeStatus(self):
     704    def test_status(self):
    615705        """
    616706        Change status
    617707        """
    618708        self._createRoom()
    619         room = self.protocol._getRoom(self.occupantJID)
     709        room = self.protocol._getRoom(self.roomJID)
    620710        user = muc.User(self.nick)
    621711        room.addUser(user)
     
    628718            self.assertEquals('xa', user.show, 'Wrong show')
    629719
    630         d = self.protocol.status(self.occupantJID, 'xa', 'testing MUC')
    631         d.addCallback(cb)
    632 
    633         prs = self.stub.output[-1]
    634 
    635         self.assertEquals('presence', prs.name, "Need to be presence")
    636         self.assertTrue(getattr(prs, 'x', None), 'No muc x element')
     720        d = self.protocol.status(self.roomJID, 'xa', 'testing MUC')
     721        d.addCallback(cb)
     722
     723        element = self.stub.output[-1]
     724
     725        self.assertEquals('presence', element.name, "Need to be presence")
     726        self.assertTrue(getattr(element, 'x', None), 'No muc x element')
    637727
    638728        # send back user presence, status changed
Note: See TracChangeset for help on using the changeset viewer.